phpseclib API Documentation
Class

Crypt_RSA

class Crypt_RSA

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.
Math_BigInteger $k Modulus length
Math_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
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

Crypt_RSA __construct()

The constructor

Crypt_RSA()

PHP4 compatible Default Constructor.

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

Create public / private key pair

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

Convert a private key to the appropriate format.

string _convertPublicKey($n, $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($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS8)

Returns the public key

mixed getPublicKeyFingerprint(string $algorithm = 'md5')

Returns the public key's fingerprint

mixed getPrivateKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)

Returns the private key

_getPrivatePublicKey($mode = CRYPT_RSA_PUBLIC_FORMAT_PKCS8)

Returns a minimalistic private key

string __toString()

__toString() magic method

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

Determines the salt length

string _i2osp(Math_BigInteger $x, int $xLen)

Integer-to-Octet-String primitive

Math_BigInteger _os2ip(string $x)

Octet-String-to-Integer primitive

Math_BigInteger _exponentiate(Math_BigInteger $x)

Exponentiate with or without Chinese Remainder Theorem

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

Performs RSA Blinding

bool _equals(string $x, string $y)

Performs blinded RSA equality testing

Math_BigInteger _rsaep(Math_BigInteger $m)

RSAEP

Math_BigInteger _rsadp(Math_BigInteger $c)

RSADP

Math_BigInteger _rsasp1(Math_BigInteger $m)

RSASP1

Math_BigInteger _rsavp1(Math_BigInteger $s)

RSAVP1

string _mgf1($mgfSeed, $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 _rsassa_pkcs1_v1_5_sign(string $m)

RSASSA-PKCS1-V1_5-SIGN

string _rsassa_pkcs1_v1_5_verify($m, $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($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

at line 498
public 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 CryptRSA doesn't do it is because OpenSSL doesn't fail gracefully. opensslpkey_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

at line 575
public Crypt_RSA()

PHP4 compatible Default Constructor.

See also

self::__construct()

at line 594
public createKey($bits = 1024, $timeout = false, $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

$bits
$timeout
$partial

at line 774
public string _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients)

Convert a private key to the appropriate format.

Parameters

$n
$e
$d
$primes
$exponents
$coefficients

Return Value

string

See also

self::setPrivateKeyFormat()

at line 1067
public string _convertPublicKey($n, $e)

Convert a public key to the appropriate format

Parameters

$n
$e

Return Value

string

See also

self::setPublicKeyFormat()

at line 1147
public 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()

at line 1637
public int getSize()

Returns the key size

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

Return Value

int

at line 1652
public _start_element_handler(resource $parser, string $name, array $attribs)

Start Element Handler

Called by xmlsetelement_handler()

Parameters

resource $parser
string $name
array $attribs

at line 1692
public _stop_element_handler(resource $parser, string $name)

Stop Element Handler

Called by xmlsetelement_handler()

Parameters

resource $parser
string $name

at line 1709
public _data_handler(resource $parser, string $data)

Data Handler

Called by xmlsetcharacterdatahandler()

Parameters

resource $parser
string $data

at line 1726
public 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

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

at line 1878
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 1938
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 1968
public getPublicKey($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

$type

See also

self::getPublicKey()

at line 1993
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 2027
public mixed getPrivateKey($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

$type

Return Value

mixed

See also

self::getPublicKey()

at line 2051
public _getPrivatePublicKey($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

$mode

See also

self::getPrivateKey()

at line 2070
public string __toString()

__toString() magic method

Return Value

string

at line 2086
public Crypt_RSA __clone()

__clone() magic method

Return Value

Crypt_RSA

at line 2100
public array _generateMinMax(int $bits)

Generates the smallest and largest numbers requiring $bits bits

Parameters

int $bits

Return Value

array

at line 2129
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 2150
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 2170
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 2184
public setPrivateKeyFormat(int $format)

Determines the private key format

Parameters

int $format

See also

self::createKey()

at line 2196
public setPublicKeyFormat(int $format)

Determines the public key format

Parameters

int $format

See also

self::createKey()

at line 2210
public setHash(string $hash)

Determines which hashing function should be used

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

Parameters

string $hash

at line 2239
public setMGFHash(string $hash)

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

The mask generation function is used by CRYPTRSAENCRYPTIONOAEP and CRYPTRSASIGNATUREPSS 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 2268
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 2283
public 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

at line 2302
public Math_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

Math_BigInteger

at line 2316
public 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

at line 2402
public 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

at line 2428
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 2456
public 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

at line 2474
public 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

at line 2492
public 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

at line 2510
public 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

at line 2529
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 2554
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

at line 2617
public 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

at line 2682
public string _raw_encrypt(string $m)

Raw Encryption / Decryption

Doesn't use padding and is not recommended.

Parameters

string $m

Return Value

string

at line 2698
public 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

at line 2757
public 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

at line 2806
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

at line 2844
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 2889
public 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

at line 2916
public 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

at line 2956
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

at line 3007
public 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

at line 3037
public string _rsassa_pkcs1_v1_5_verify($m, $s)

RSASSA-PKCS1-V1_5-VERIFY

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

Parameters

$m
$s

Return Value

string

at line 3080
public setEncryptionMode(int $mode)

Set Encryption Mode

Valid values include CRYPTRSAENCRYPTIONOAEP and CRYPTRSAENCRYPTIONPKCS1.

Parameters

int $mode

at line 3093
public setSignatureMode(int $mode)

Set Signature Mode

Valid values include CRYPTRSASIGNATUREPSS and CRYPTRSASIGNATUREPKCS1

Parameters

int $mode

at line 3104
public setComment(string $comment)

Set public key comment.

Parameters

string $comment

at line 3115
public string getComment()

Get public key comment.

Return Value

string

at line 3132
public string encrypt(string $plaintext)

Encryption

Both CRYPTRSAENCRYPTIONOAEP and CRYPTRSAENCRYPTIONPKCS1 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()

at line 3178
public string decrypt($ciphertext)

Decryption

Parameters

$ciphertext

Return Value

string

See also

self::encrypt()

at line 3220
public string sign(string $message)

Create a signature

Parameters

string $message

Return Value

string

See also

self::verify()

at line 3244
public bool verify(string $message, string $signature)

Verifies a signature

Parameters

string $message
string $signature

Return Value

bool

See also

self::sign()

at line 3266
public string _extractBER(string $str)

Extract raw BER from Base64 encoding

Parameters

string $str

Return Value

string