phpseclib API Documentation
Class

phpseclib\Crypt\RSA

class RSA

Pure-PHP PKCS#1 compliant implementation of RSA.

Constants

PADDING_OAEP

Use {@link http://en.wikipedia.org/wiki/OptimalAsymmetricEncryption_Padding Optimal Asymmetric Encryption Padding} (OAEP) for encryption / decryption.

Uses sha256 by default

PADDING_PKCS1

Use PKCS#1 padding.

Although self::PADDINGOAEP / self::PADDINGPSS offers more security, including PKCS#1 padding is necessary for purposes of backwards compatibility with protocols (like SSH-1) written before OAEP's introduction.

PADDING_NONE

Do not use any padding

Although this method is not recommended it can none-the-less sometimes be useful if you're trying to decrypt some legacy stuff, if you're trying to diagnose why an encrypted message isn't decrypting, etc.

PADDING_PKCS15_COMPAT

Use PKCS#1 padding with PKCS1 v1.5 compatability

A PKCS1 v2.1 encrypted message may not successfully decrypt with a PKCS1 v1.5 implementation (such as OpenSSL).

PADDING_PSS

Use the Probabilistic Signature Scheme for signing

Uses sha256 and 0 as the salt length

PADDING_RELAXED_PKCS1

Use a relaxed version of PKCS#1 padding for signature verification

ASN1_INTEGER

ASN1 Integer

ASN1_BITSTRING

ASN1 Bit String

ASN1_OCTETSTRING

ASN1 Octet String

ASN1_OBJECT

ASN1 Object Identifier

ASN1_SEQUENCE

ASN1 Sequence (with the constucted bit set)

MODE_INTERNAL

To use the pure-PHP implementation

MODE_OPENSSL

To use the OpenSSL library

(if enabled; otherwise, the internal implementation will be used)

Properties

string $privateKeyFormat Private Key Format
string $publicKeyFormat Public Key Format
BigInteger $modulus Modulus (ie.
BigInteger $k Modulus length
BigInteger $exponent Exponent (ie.
array $primes Primes for Chinese Remainder Theorem (ie.
array $exponents Exponents for Chinese Remainder Theorem (ie.
array $coefficients Coefficients for Chinese Remainder Theorem (ie.
string $hashName Hash name
Hash $hash Hash function
int $hLen Length of hash function output
int $sLen Length of salt
Hash $mgfHash Hash function for the Mask Generation Function
int $mgfHLen Length of MGF hash function output
mixed $publicExponent Public Exponent
string $password Password
string $format Loaded File Format

Methods

RSA __construct()

The constructor

load(string $key, int $type = false)

Loads a public or private key

mixed getLoadedFormat()

Returns the format of the loaded key.

mixed getPrivateKey(string $type = 'PKCS1')

Returns the private key

int getSize()

Returns the key size

setPassword(string $password = false)

Sets the password

bool setPublicKey(string $key = false, int $type = false)

Defines the public key

bool setPrivateKey(string $key = false, int $type = false)

Defines the private key

mixed getPublicKey(string $type = 'PKCS8')

Returns the public key

mixed getPublicKeyFingerprint(string $algorithm = 'md5')

Returns the public key's fingerprint

mixed _getPrivatePublicKey(string $type = 'PKCS8')

Returns a minimalistic private key

string __toString()

__toString() magic method

RSA __clone()

__clone() magic method

int _decodeLength(string $string)

DER-decode the length

string _encodeLength(int $length)

DER-encode the length

string _string_shift(string $string, int $index = 1)

String Shift

setPrivateKeyFormat(int $format)

Determines the private key format

setPublicKeyFormat(int $format)

Determines the public key format

setHash(string $hash)

Determines which hashing function should be used

setMGFHash(string $hash)

Determines which hashing function should be used for the mask generation function

setSaltLength($sLen)

Determines the salt length

bool|string _i2osp(bool|BigInteger $x, int $xLen)

Integer-to-Octet-String primitive

BigInteger _os2ip(string $x)

Octet-String-to-Integer primitive

BigInteger _exponentiate(BigInteger $x)

Exponentiate with or without Chinese Remainder Theorem

BigInteger _blind(BigInteger $x, BigInteger $r, int $i)

Performs RSA Blinding

bool _equals(string $x, string $y)

Performs blinded RSA equality testing

bool|BigInteger _rsaep(BigInteger $m)

RSAEP

bool|BigInteger _rsadp(BigInteger $c)

RSADP

bool|BigInteger _rsasp1(BigInteger $m)

RSASP1

bool|BigInteger _rsavp1(BigInteger $s)

RSAVP1

string _mgf1($mgfSeed, $maskLen)

MGF1

string _rsaes_oaep_encrypt(string $m, string $l = '')

RSAES-OAEP-ENCRYPT

bool|string _rsaes_oaep_decrypt(string $c, string $l = '')

RSAES-OAEP-DECRYPT

bool|string _raw_encrypt(string $m)

Raw Encryption / Decryption

bool|string _rsaes_pkcs1_v1_5_encrypt(string $m, bool $pkcs15_compat = false)

RSAES-PKCS1-V1_5-ENCRYPT

bool|string _rsaes_pkcs1_v1_5_decrypt(string $c)

RSAES-PKCS1-V1_5-DECRYPT

_emsa_pss_encode(string $m, int $emBits)

EMSA-PSS-ENCODE

string _emsa_pss_verify(string $m, string $em, int $emBits)

EMSA-PSS-VERIFY

bool|string _rsassa_pss_sign(string $m)

RSASSA-PSS-SIGN

bool|string _rsassa_pss_verify(string $m, string $s)

RSASSA-PSS-VERIFY

string _emsa_pkcs1_v1_5_encode(string $m, int $emLen)

EMSA-PKCS1-V1_5-ENCODE

bool|string _rsassa_pkcs1_v1_5_sign(string $m)

RSASSA-PKCS1-V1_5-SIGN

bool _rsassa_pkcs1_v1_5_verify(string $m, string $s)

RSASSA-PKCS1-V1_5-VERIFY

bool _rsassa_pkcs1_v1_5_relaxed_verify(string $m, string $s)

RSASSA-PKCS1-V1_5-VERIFY (relaxed matching)

bool|string encrypt(string $plaintext, int $padding = self::PADDING_OAEP)

Encryption

bool|string decrypt($ciphertext, $padding = self::PADDING_OAEP)

Decryption

string sign(string $message, int $padding = self::PADDING_PSS)

Create a signature

bool verify(string $message, string $signature, int $padding = self::PADDING_PSS)

Verifies a signature

Details

at line 380
public RSA __construct()

The constructor

If you want to make use of the openssl extension, you'll need to set the mode manually, yourself. The reason \phpseclib\Crypt\RSA doesn't do it is because OpenSSL doesn't fail gracefully. opensslpkeynew(), in particular, requires openssl.cnf be present somewhere and, unfortunately, the only real way to find out is too late.

Return Value

RSA

at line 685
public load(string $key, int $type = false)

Loads a public or private key

Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed)

Parameters

string $key
int $type optional

at line 793
public mixed getLoadedFormat()

Returns the format of the loaded key.

If the key that was loaded wasn't in a valid or if the key was auto-generated with RSA::createKey() then this will return false.

Return Value

mixed

See also

self::load()

at line 813
public mixed getPrivateKey(string $type = 'PKCS1')

Returns the private key

The private key is only returned if the currently loaded key contains the constituent prime numbers.

Parameters

string $type optional

Return Value

mixed

See also

self::getPublicKey()

at line 843
public int getSize()

Returns the key size

More specifically, this returns the size of the modulo in bits.

Return Value

int

at line 859
public setPassword(string $password = false)

Sets the password

Private keys can be encrypted with a password. To unset the password, pass in the empty string or false. Or rather, pass in $password such that empty($password) && !is_string($password) is true.

Parameters

string $password

See also

self::createKey()
self::load()

at line 885
public bool setPublicKey(string $key = false, int $type = false)

Defines the public key

Some private key formats define the public exponent and some don't. Those that don't define it are problematic when used in certain contexts. For example, in SSH-2, RSA authentication works by sending the public key along with a message signed by the private key to the server. The SSH-2 server looks the public key up in an index of public keys and if it's present then proceeds to verify the signature. Problem is, if your private key doesn't include the public exponent this won't work unless you manually add the public exponent. phpseclib tries to guess if the key being used is the public key but in the event that it guesses incorrectly you might still want to explicitly set the key as being public.

Do note that when a new key is loaded the index will be cleared.

Returns true on success, false on failure

Parameters

string $key optional
int $type optional

Return Value

bool

See also

self::getPublicKey()

at line 958
public bool setPrivateKey(string $key = false, int $type = false)

Defines the private key

If phpseclib guessed a private key was a public key and loaded it as such it might be desirable to force phpseclib to treat the key as a private key. This function will do that.

Do note that when a new key is loaded the index will be cleared.

Returns true on success, false on failure

Parameters

string $key optional
int $type optional

Return Value

bool

See also

self::getPublicKey()

at line 988
public mixed getPublicKey(string $type = 'PKCS8')

Returns the public key

The public key is only returned under two circumstances - if the private key had the public key embedded within it or if the public key was set via setPublicKey(). If the currently loaded key is supposed to be the public key this function won't return it since this library, for the most part, doesn't distinguish between public and private keys.

Parameters

string $type optional

Return Value

mixed

See also

self::getPrivateKey()

at line 1022
public mixed getPublicKeyFingerprint(string $algorithm = 'md5')

Returns the public key's fingerprint

The public key's fingerprint is returned, which is equivalent to running ssh-keygen -lf rsa.pub. If there is no public key currently loaded, false is returned. Example output (md5): "c1:b1:30:29:d7:b8:de:6c:97:77:10:d7:46:41:63:87" (as specified by RFC 4716)

Parameters

string $algorithm The hashing algorithm to be used. Valid options are 'md5' and 'sha256'. False is returned for invalid values.

Return Value

mixed

at line 1056
public mixed _getPrivatePublicKey(string $type = 'PKCS8')

Returns a minimalistic private key

Returns the private key without the prime number constituants. Structurally identical to a public key that hasn't been set as the public key

Parameters

string $type optional

Return Value

mixed

See also

self::getPrivateKey()

at line 1085
public string __toString()

__toString() magic method

Return Value

string

at line 1101
public RSA __clone()

__clone() magic method

Return Value

RSA

at line 1144
public int _decodeLength(string $string)

DER-decode the length

DER supports lengths up to (28)127, however, we'll only support lengths up to (28)4. See {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information.

Parameters

string $string

Return Value

int

at line 1165
public string _encodeLength(int $length)

DER-encode the length

DER supports lengths up to (28)127, however, we'll only support lengths up to (28)4. See {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information.

Parameters

int $length

Return Value

string

at line 1185
public string _string_shift(string $string, int $index = 1)

String Shift

Inspired by array_shift

Parameters

string $string
int $index

Return Value

string

at line 1199
public setPrivateKeyFormat(int $format)

Determines the private key format

Parameters

int $format

See also

self::createKey()

at line 1211
public setPublicKeyFormat(int $format)

Determines the public key format

Parameters

int $format

See also

self::createKey()

at line 1225
public setHash(string $hash)

Determines which hashing function should be used

Used with signature production / verification and (if the encryption mode is self::PADDING_OAEP) encryption and decryption. If $hash isn't supported, sha256 is used.

Parameters

string $hash

at line 1254
public setMGFHash(string $hash)

Determines which hashing function should be used for the mask generation function

The mask generation function is used by self::PADDINGOAEP and self::PADDINGPSS and although it's best if Hash and MGFHash are set to the same thing this is not a requirement.

Parameters

string $hash

at line 1283
public setSaltLength($sLen)

Determines the salt length

To quote from {@link http://tools.ietf.org/html/rfc3447#page-38 RFC3447#page-38}:

Typical salt lengths in octets are hLen (the length of the output of the hash function Hash) and 0.

Parameters

$sLen

at line 1298
public bool|string _i2osp(bool|BigInteger $x, int $xLen)

Integer-to-Octet-String primitive

See {@link http://tools.ietf.org/html/rfc3447#section-4.1 RFC3447#section-4.1}.

Parameters

bool|BigInteger $x
int $xLen

Return Value

bool|string

at line 1319
public BigInteger _os2ip(string $x)

Octet-String-to-Integer primitive

See {@link http://tools.ietf.org/html/rfc3447#section-4.2 RFC3447#section-4.2}.

Parameters

string $x

Return Value

BigInteger

at line 1333
public BigInteger _exponentiate(BigInteger $x)

Exponentiate with or without Chinese Remainder Theorem

See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.2}.

Parameters

BigInteger $x

Return Value

BigInteger

at line 1411
public BigInteger _blind(BigInteger $x, BigInteger $r, int $i)

Performs RSA Blinding

Protects against timing attacks by employing RSA Blinding. Returns $x->modPow($this->exponents[$i], $this->primes[$i])

Parameters

BigInteger $x
BigInteger $r
int $i

Return Value

BigInteger

at line 1437
public bool _equals(string $x, string $y)

Performs blinded RSA equality testing

Protects against a particular type of timing attack described.

See {@link http://codahale.com/a-lesson-in-timing-attacks/ A Lesson In Timing Attacks (or, Don't use MessageDigest.isEquals)}

Thanks for the heads up singpolyma!

Parameters

string $x
string $y

Return Value

bool

at line 1460
public bool|BigInteger _rsaep(BigInteger $m)

RSAEP

See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.1}.

Parameters

BigInteger $m

Return Value

bool|BigInteger

at line 1477
public bool|BigInteger _rsadp(BigInteger $c)

RSADP

See {@link http://tools.ietf.org/html/rfc3447#section-5.1.2 RFC3447#section-5.1.2}.

Parameters

BigInteger $c

Return Value

bool|BigInteger

at line 1494
public bool|BigInteger _rsasp1(BigInteger $m)

RSASP1

See {@link http://tools.ietf.org/html/rfc3447#section-5.2.1 RFC3447#section-5.2.1}.

Parameters

BigInteger $m

Return Value

bool|BigInteger

at line 1511
public bool|BigInteger _rsavp1(BigInteger $s)

RSAVP1

See {@link http://tools.ietf.org/html/rfc3447#section-5.2.2 RFC3447#section-5.2.2}.

Parameters

BigInteger $s

Return Value

bool|BigInteger

at line 1529
public string _mgf1($mgfSeed, $maskLen)

MGF1

See {@link http://tools.ietf.org/html/rfc3447#appendix-B.2.1 RFC3447#appendix-B.2.1}.

Parameters

$mgfSeed
$maskLen

Return Value

string

at line 1555
public string _rsaes_oaep_encrypt(string $m, string $l = '')

RSAES-OAEP-ENCRYPT

See {@link http://tools.ietf.org/html/rfc3447#section-7.1.1 RFC3447#section-7.1.1} and {http://en.wikipedia.org/wiki/OptimalAsymmetricEncryption_Padding OAES}.

Parameters

string $m
string $l

Return Value

string

Exceptions

OutOfBoundsException if strlen($m) > $this->k - 2 * $this->hLen - 2

at line 1617
public bool|string _rsaes_oaep_decrypt(string $c, string $l = '')

RSAES-OAEP-DECRYPT

See {@link http://tools.ietf.org/html/rfc3447#section-7.1.2 RFC3447#section-7.1.2}. The fact that the error messages aren't distinguishable from one another hinders debugging, but, to quote from RFC3447#section-7.1.2:

Note. Care must be taken to ensure that an opponent cannot distinguish the different error conditions in Step 3.g, whether by error message or timing, or, more generally, learn partial information about the encoded message EM. Otherwise an opponent may be able to obtain useful information about the decryption of the ciphertext C, leading to a chosen-ciphertext attack such as the one observed by Manger [36].

As for $l... to quote from {@link http://tools.ietf.org/html/rfc3447#page-17 RFC3447#page-17}:

Both the encryption and the decryption operations of RSAES-OAEP take the value of a label L as input. In this version of PKCS #1, L is the empty string; other uses of the label are outside the scope of this document.

Parameters

string $c
string $l

Return Value

bool|string

at line 1672
public bool|string _raw_encrypt(string $m)

Raw Encryption / Decryption

Doesn't use padding and is not recommended.

Parameters

string $m

Return Value

bool|string

Exceptions

OutOfBoundsException if strlen($m) > $this->k

at line 1694
public bool|string _rsaes_pkcs1_v1_5_encrypt(string $m, bool $pkcs15_compat = false)

RSAES-PKCS1-V1_5-ENCRYPT

See {@link http://tools.ietf.org/html/rfc3447#section-7.2.1 RFC3447#section-7.2.1}.

Parameters

string $m
bool $pkcs15_compat optional

Return Value

bool|string

Exceptions

OutOfBoundsException if strlen($m) > $this->k - 11

at line 1752
public bool|string _rsaes_pkcs1_v1_5_decrypt(string $c)

RSAES-PKCS1-V1_5-DECRYPT

See {@link http://tools.ietf.org/html/rfc3447#section-7.2.2 RFC3447#section-7.2.2}.

For compatibility purposes, this function departs slightly from the description given in RFC3447. The reason being that RFC2313#section-8.1 (PKCS#1 v1.5) states that ciphertext's encrypted by the private key should have the second byte set to either 0 or 1 and that ciphertext's encrypted by the public key should have the second byte set to 2. In RFC3447 (PKCS#1 v2.1), the second byte is supposed to be 2 regardless of which key is used. For compatibility purposes, we'll just check to make sure the second byte is 2 or less. If it is, we'll accept the decrypted string as valid.

As a consequence of this, a private key encrypted ciphertext produced with \phpseclib\Crypt\RSA may not decrypt with a strictly PKCS#1 v1.5 compliant RSA implementation. Public key encrypted ciphertext's should but not private key encrypted ciphertext's.

Parameters

string $c

Return Value

bool|string

at line 1797
public _emsa_pss_encode(string $m, int $emBits)

EMSA-PSS-ENCODE

See {@link http://tools.ietf.org/html/rfc3447#section-9.1.1 RFC3447#section-9.1.1}.

Parameters

string $m
int $emBits

Exceptions

RuntimeException on encoding error

at line 1834
public string _emsa_pss_verify(string $m, string $em, int $emBits)

EMSA-PSS-VERIFY

See {@link http://tools.ietf.org/html/rfc3447#section-9.1.2 RFC3447#section-9.1.2}.

Parameters

string $m
string $em
int $emBits

Return Value

string

at line 1879
public bool|string _rsassa_pss_sign(string $m)

RSASSA-PSS-SIGN

See {@link http://tools.ietf.org/html/rfc3447#section-8.1.1 RFC3447#section-8.1.1}.

Parameters

string $m

Return Value

bool|string

at line 1906
public bool|string _rsassa_pss_verify(string $m, string $s)

RSASSA-PSS-VERIFY

See {@link http://tools.ietf.org/html/rfc3447#section-8.1.2 RFC3447#section-8.1.2}.

Parameters

string $m
string $s

Return Value

bool|string

at line 1941
public string _emsa_pkcs1_v1_5_encode(string $m, int $emLen)

EMSA-PKCS1-V1_5-ENCODE

See {@link http://tools.ietf.org/html/rfc3447#section-9.2 RFC3447#section-9.2}.

Parameters

string $m
int $emLen

Return Value

string

Exceptions

LengthException if the intended encoded message length is too short

at line 1989
public bool|string _rsassa_pkcs1_v1_5_sign(string $m)

RSASSA-PKCS1-V1_5-SIGN

See {@link http://tools.ietf.org/html/rfc3447#section-8.2.1 RFC3447#section-8.2.1}.

Parameters

string $m

Return Value

bool|string

Exceptions

LengthException if the RSA modulus is too short

at line 2023
public bool _rsassa_pkcs1_v1_5_verify(string $m, string $s)

RSASSA-PKCS1-V1_5-VERIFY

See {@link http://tools.ietf.org/html/rfc3447#section-8.2.2 RFC3447#section-8.2.2}.

Parameters

string $m
string $s

Return Value

bool

Exceptions

LengthException if the RSA modulus is too short

at line 2072
public bool _rsassa_pkcs1_v1_5_relaxed_verify(string $m, string $s)

RSASSA-PKCS1-V1_5-VERIFY (relaxed matching)

Per {@link http://tools.ietf.org/html/rfc3447#page-43 RFC3447#page-43} PKCS1 v1.5 specified the use BER encoding rather than DER encoding that PKCS1 v2.0 specified. This means that under rare conditions you can have a perfectly valid v1.5 signature that fails to validate with rsassapkcs1v15verify(). PKCS1 v2.1 also recommends that if you're going to validate these types of signatures you "should indicate whether the underlying BER encoding is a DER encoding and hence whether the signature is valid with respect to the specification given in [PKCS1 v2.0+]". so if you do $rsa->getLastPadding() and get RSA::PADDINGRELAXEDPKCS1 back instead of RSA::PADDINGPKCS1... that means BER encoding was used.

Parameters

string $m
string $s

Return Value

bool

at line 2171
public bool|string encrypt(string $plaintext, int $padding = self::PADDING_OAEP)

Encryption

Both self::PADDINGOAEP and self::PADDINGPKCS1 both place limits on how long $plaintext can be. If $plaintext exceeds those limits it will be broken up so that it does and the resultant ciphertext's will be concatenated together.

Parameters

string $plaintext
int $padding optional

Return Value

bool|string

Exceptions

LengthException if the RSA modulus is too short

See also

self::decrypt()

at line 2194
public bool|string decrypt($ciphertext, $padding = self::PADDING_OAEP)

Decryption

Parameters

$ciphertext
$padding

Return Value

bool|string

See also

self::encrypt()

at line 2216
public string sign(string $message, int $padding = self::PADDING_PSS)

Create a signature

Parameters

string $message
int $padding optional

Return Value

string

See also

self::verify()

at line 2242
public bool verify(string $message, string $signature, int $padding = self::PADDING_PSS)

Verifies a signature

Parameters

string $message
string $signature
int $padding optional

Return Value

bool

See also

self::sign()