class Crypt_RSA (View source)

Pure-PHP PKCS#1 compliant implementation of RSA.

Properties

Math_BigInteger $zero Precomputed Zero
Math_BigInteger $one Precomputed One
int $privateKeyFormat Private Key Format
int $publicKeyFormat Public Key Format
Math_BigInteger $modulus Modulus (ie. n)
Math_BigInteger $k Modulus length
Math_BigInteger $exponent Exponent (ie. e or d)
array $primes Primes for Chinese Remainder Theorem (ie. p and q)
array $exponents Exponents for Chinese Remainder Theorem (ie. dP and dQ)
array $coefficients Coefficients for Chinese Remainder Theorem (ie. qInv)
string $hashName Hash name
Crypt_Hash $hash Hash function
int $hLen Length of hash function output
int $sLen Length of salt
Crypt_Hash $mgfHash Hash function for the Mask Generation Function
int $mgfHLen Length of MGF hash function output
int $encryptionMode Encryption mode
int $signatureMode Signature mode
mixed $publicExponent Public Exponent
string $password Password
array $components Components
mixed $current Current String
mixed $configFile OpenSSL configuration file name.
string $comment Public key comment field.

Methods

__construct()

The constructor

Crypt_RSA()

PHP4 compatible Default Constructor.

createKey(int $bits = 1024, int $timeout = false, array $partial = array())

Create public / private key pair

string
_convertPrivateKey(Math_BigInteger $n, Math_BigInteger $e, Math_BigInteger $d, Math_BigInteger> $primes, Math_BigInteger> $exponents, Math_BigInteger> $coefficients)

Convert a private key to the appropriate format.

string|Math_BigInteger>
_convertPublicKey(Math_BigInteger $n, Math_BigInteger $e)

Convert a public key to the appropriate format

array
_parseKey(string $key, int $type)

Break a public or private key down into its constituant components

int
getSize()

Returns the key size

_start_element_handler(resource $parser, string $name, array $attribs)

Start Element Handler

_stop_element_handler(resource $parser, string $name)

Stop Element Handler

_data_handler(resource $parser, string $data)

Data Handler

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

Loads a public or private key

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

getPublicKey(int $type = CRYPT_RSA_PUBLIC_FORMAT_PKCS8)

Returns the public key

mixed
getPublicKeyFingerprint(string $algorithm = 'md5')

Returns the public key's fingerprint

mixed
getPrivateKey(int $type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)

Returns the private key

_getPrivatePublicKey(int $mode = CRYPT_RSA_PUBLIC_FORMAT_PKCS8)

Returns a minimalistic private key

string
__toString()

__toString() magic method

__clone()

__clone() magic method

array
_generateMinMax(int $bits)

Generates the smallest and largest numbers requiring $bits bits

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(int $sLen)

Determines the salt length

string
_i2osp(Math_BigInteger $x, int $xLen)

Integer-to-Octet-String primitive

_os2ip(int|string|resource $x)

Octet-String-to-Integer primitive

_exponentiate(Math_BigInteger $x)

Exponentiate with or without Chinese Remainder Theorem

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

Performs RSA Blinding

bool
_equals(string $x, string $y)

Performs blinded RSA equality testing

string
_mgf1(string $mgfSeed, int $maskLen)

MGF1

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

RSAES-OAEP-ENCRYPT

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

RSAES-OAEP-DECRYPT

string
_raw_encrypt(string $m)

Raw Encryption / Decryption

string
_rsaes_pkcs1_v1_5_encrypt(string $m)

RSAES-PKCS1-V1_5-ENCRYPT

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

string
_rsassa_pss_sign(string $m)

RSASSA-PSS-SIGN

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

string
_emsa_pkcs1_v1_5_encode_without_null(string $m, int $emLen)

EMSA-PKCS1-V1_5-ENCODE (without NULL)

string
_rsassa_pkcs1_v1_5_sign(string $m)

RSASSA-PKCS1-V1_5-SIGN

string
_rsassa_pkcs1_v1_5_verify(string $m, string $s)

RSASSA-PKCS1-V1_5-VERIFY

setEncryptionMode(int $mode)

Set Encryption Mode

setSignatureMode(int $mode)

Set Signature Mode

setComment(string $comment)

Set public key comment.

string
getComment()

Get public key comment.

string
encrypt(string $plaintext)

Encryption

string
decrypt(string $ciphertext)

Decryption

string
sign(string $message)

Create a signature

bool
verify(string $message, string $signature)

Verifies a signature

string
_extractBER(string $str)

Extract raw BER from Base64 encoding

Details

Crypt_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 Crypt_RSA doesn't do it is because OpenSSL doesn't fail gracefully. openssl_pkey_new(), in particular, requires openssl.cnf be present somewhere and, unfortunately, the only real way to find out is too late.

Return Value

Crypt_RSA

Crypt_RSA()

PHP4 compatible Default Constructor.

See also

\self::__construct()

createKey(int $bits = 1024, int $timeout = false, array $partial = array())

Create public / private key pair

Returns an array with the following three elements: - 'privatekey': The private key. - 'publickey': The public key. - 'partialkey': A partially computed key (if the execution time exceeded $timeout). Will need to be passed back to Crypt_RSA::createKey() as the third parameter for further processing.

Parameters

int $bits
int $timeout
array $partial

string _convertPrivateKey(Math_BigInteger $n, Math_BigInteger $e, Math_BigInteger $d, Math_BigInteger> $primes, Math_BigInteger> $exponents, Math_BigInteger> $coefficients)

Convert a private key to the appropriate format.

Parameters

Math_BigInteger $n
Math_BigInteger $e
Math_BigInteger $d
Math_BigInteger> $primes
Math_BigInteger> $exponents
Math_BigInteger> $coefficients

Return Value

string

See also

\self::setPrivateKeyFormat()

string|Math_BigInteger> _convertPublicKey(Math_BigInteger $n, Math_BigInteger $e)

Convert a public key to the appropriate format

Parameters

Math_BigInteger $n
Math_BigInteger $e

Return Value

string|Math_BigInteger>

See also

\self::setPublicKeyFormat()

array _parseKey(string $key, int $type)

Break a public or private key down into its constituant components

Parameters

string $key
int $type

Return Value

array

See also

\self::_convertPublicKey()
\self::_convertPrivateKey()

int getSize()

Returns the key size

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

Return Value

int

_start_element_handler(resource $parser, string $name, array $attribs)

Start Element Handler

Called by xml_set_element_handler()

Parameters

resource $parser
string $name
array $attribs

_stop_element_handler(resource $parser, string $name)

Stop Element Handler

Called by xml_set_element_handler()

Parameters

resource $parser
string $name

_data_handler(resource $parser, string $data)

Data Handler

Called by xml_set_character_data_handler()

Parameters

resource $parser
string $data

loadKey(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

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::loadKey()

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()

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()

getPublicKey(int $type = CRYPT_RSA_PUBLIC_FORMAT_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

int $type optional

See also

\self::getPublicKey()

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

mixed getPrivateKey(int $type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)

Returns the private key

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

Parameters

int $type optional

Return Value

mixed

See also

\self::getPublicKey()

_getPrivatePublicKey(int $mode = CRYPT_RSA_PUBLIC_FORMAT_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

int $mode optional

See also

\self::getPrivateKey()

string __toString()

__toString() magic method

Return Value

string

Crypt_RSA __clone()

__clone() magic method

Return Value

Crypt_RSA

array _generateMinMax(int $bits)

Generates the smallest and largest numbers requiring $bits bits

Parameters

int $bits

Return Value

array

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

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

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

String Shift

Inspired by array_shift

Parameters

string $string
int $index

Return Value

string

setPrivateKeyFormat(int $format)

Determines the private key format

Parameters

int $format

See also

\self::createKey()

setPublicKeyFormat(int $format)

Determines the public key format

Parameters

int $format

See also

\self::createKey()

setHash(string $hash)

Determines which hashing function should be used

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

Parameters

string $hash

setMGFHash(string $hash)

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

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

Parameters

string $hash

setSaltLength(int $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

int $sLen

string _i2osp(Math_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

Math_BigInteger $x
int $xLen

Return Value

string

Math_BigInteger _os2ip(int|string|resource $x)

Octet-String-to-Integer primitive

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

Parameters

int|string|resource $x

Return Value

Math_BigInteger

Math_BigInteger _exponentiate(Math_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

Math_BigInteger $x

Return Value

Math_BigInteger

Math_BigInteger _blind(Math_BigInteger $x, Math_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

Math_BigInteger $x
Math_BigInteger $r
int $i

Return Value

Math_BigInteger

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

Math_BigInteger _rsaep(Math_BigInteger $m)

RSAEP

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

Parameters

Math_BigInteger $m

Return Value

Math_BigInteger

Math_BigInteger _rsadp(Math_BigInteger $c)

RSADP

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

Parameters

Math_BigInteger $c

Return Value

Math_BigInteger

Math_BigInteger _rsasp1(Math_BigInteger $m)

RSASP1

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

Parameters

Math_BigInteger $m

Return Value

Math_BigInteger

Math_BigInteger _rsavp1(Math_BigInteger $s)

RSAVP1

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

Parameters

Math_BigInteger $s

Return Value

Math_BigInteger

string _mgf1(string $mgfSeed, int $maskLen)

MGF1

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

Parameters

string $mgfSeed
int $maskLen

Return Value

string

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/Optimal_Asymmetric_Encryption_Padding OAES}.

Parameters

string $m
string $l

Return Value

string

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

string

string _raw_encrypt(string $m)

Raw Encryption / Decryption

Doesn't use padding and is not recommended.

Parameters

string $m

Return Value

string

string _rsaes_pkcs1_v1_5_encrypt(string $m)

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

Return Value

string

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 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

string

_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

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

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

string

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

string

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

string _emsa_pkcs1_v1_5_encode_without_null(string $m, int $emLen)

EMSA-PKCS1-V1_5-ENCODE (without NULL)

Quoting https://tools.ietf.org/html/rfc8017#page-65,

"The parameters field associated with id-sha1, id-sha224, id-sha256, id-sha384, id-sha512, id-sha512/224, and id-sha512/256 should generally be omitted, but if present, it shall have a value of type NULL"

Parameters

string $m
int $emLen

Return Value

string

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

string

string _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

string

setEncryptionMode(int $mode)

Set Encryption Mode

Valid values include CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1.

Parameters

int $mode

setSignatureMode(int $mode)

Set Signature Mode

Valid values include CRYPT_RSA_SIGNATURE_PSS and CRYPT_RSA_SIGNATURE_PKCS1

Parameters

int $mode

setComment(string $comment)

Set public key comment.

Parameters

string $comment

string getComment()

Get public key comment.

Return Value

string

string encrypt(string $plaintext)

Encryption

Both CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1 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

Return Value

string

See also

\self::decrypt()

string decrypt(string $ciphertext)

Decryption

Parameters

string $ciphertext

Return Value

string

See also

\self::encrypt()

string sign(string $message)

Create a signature

Parameters

string $message

Return Value

string

See also

\self::verify()

bool verify(string $message, string $signature)

Verifies a signature

Parameters

string $message
string $signature

Return Value

bool

See also

\self::sign()

string _extractBER(string $str)

Extract raw BER from Base64 encoding

Parameters

string $str

Return Value

string