RSA
class RSA (View source)
Pure-PHP PKCS#1 compliant implementation of RSA.
Constants
ENCRYPTION_OAEP |
Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding} (OAEP) for encryption / decryption. Uses sha1 by default. |
ENCRYPTION_PKCS1 |
Use PKCS#1 padding. Although self::ENCRYPTION_OAEP offers more security, including PKCS#1 padding is necessary for purposes of backwards compatibility with protocols (like SSH-1) written before OAEP's introduction. |
ENCRYPTION_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. |
SIGNATURE_PSS |
Use the Probabilistic Signature Scheme for signing Uses sha1 by default. |
SIGNATURE_PKCS1 |
Use the PKCS#1 scheme by default. Although self::SIGNATURE_PSS offers more security, including PKCS#1 signing is necessary for purposes of backwards compatibility with protocols (like SSH-2) written before PSS's introduction. |
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) |
PRIVATE_FORMAT_PKCS1 |
PKCS#1 formatted private key Used by OpenSSH |
PRIVATE_FORMAT_PUTTY |
PuTTY formatted private key |
PRIVATE_FORMAT_XML |
XML formatted private key |
PRIVATE_FORMAT_PKCS8 |
PKCS#8 formatted private key |
PRIVATE_FORMAT_OPENSSH |
OpenSSH formatted private key |
PUBLIC_FORMAT_RAW |
Raw public key An array containing two \phpseclib\Math\BigInteger objects. The exponent can be indexed with any of the following: 0, e, exponent, publicExponent The modulus can be indexed with any of the following: 1, n, modulo, modulus |
PUBLIC_FORMAT_PKCS1 |
PKCS#1 formatted public key (raw) Used by File/X509.php Has the following header: -----BEGIN RSA PUBLIC KEY----- Analogous to ssh-keygen's pem format (as specified by -m) |
PUBLIC_FORMAT_PKCS1_RAW |
|
PUBLIC_FORMAT_XML |
XML formatted public key |
PUBLIC_FORMAT_OPENSSH |
OpenSSH formatted public key Place in $HOME/.ssh/authorized_keys |
PUBLIC_FORMAT_PKCS8 |
PKCS#1 formatted public key (encapsulated) Used by PHP's openssl_public_encrypt() and openssl's rsautl (when -pubin is set) Has the following header: -----BEGIN PUBLIC KEY----- Analogous to ssh-keygen's pkcs8 format (as specified by -m). Although PKCS8 is specific to private keys it's basically creating a DER-encoded wrapper for keys. This just extends that same concept to public keys (much like ssh-keygen) |
Properties
BigInteger | $zero | Precomputed Zero | |
BigInteger | $one | Precomputed One | |
int | $privateKeyFormat | Private Key Format | |
int | $publicKeyFormat | Public Key Format | |
BigInteger | $modulus | Modulus (ie. n) | |
BigInteger | $k | Modulus length | |
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 | |
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 | |
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
The constructor
Create public / private key pair
Convert a private key to the appropriate format.
Convert a public key to the appropriate format
Break a public or private key down into its constituant components
Returns the key size
Start Element Handler
Stop Element Handler
Data Handler
Loads a public or private key
Sets the password
Defines the public key
Defines the private key
Returns the public key
Returns the public key's fingerprint
Returns the private key
Returns a minimalistic private key
__toString() magic method
__clone() magic method
Generates the smallest and largest numbers requiring $bits bits
DER-decode the length
DER-encode the length
String Shift
Determines the private key format
Determines the public key format
Determines which hashing function should be used
Determines which hashing function should be used for the mask generation function
Determines the salt length
Octet-String-to-Integer primitive
Performs blinded RSA equality testing
MGF1
RSAES-OAEP-ENCRYPT
RSAES-OAEP-DECRYPT
Raw Encryption / Decryption
RSAES-PKCS1-V1_5-ENCRYPT
RSAES-PKCS1-V1_5-DECRYPT
EMSA-PSS-ENCODE
EMSA-PSS-VERIFY
RSASSA-PSS-SIGN
RSASSA-PSS-VERIFY
EMSA-PKCS1-V1_5-ENCODE
EMSA-PKCS1-V1_5-ENCODE (without NULL)
RSASSA-PKCS1-V1_5-SIGN
RSASSA-PKCS1-V1_5-VERIFY
Set Encryption Mode
Set Signature Mode
Set public key comment.
Get public key comment.
Encryption
Decryption
Create a signature
Verifies a signature
Extract raw BER from Base64 encoding
Details
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. openssl_pkey_new(), in particular, requires openssl.cnf be present somewhere and, unfortunately, the only real way to find out is too late.
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 \phpseclib\Crypt\RSA::createKey() as the third parameter for further processing.
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|bool
_parseKey(string|array $key, int $type)
Break a public or private key down into its constituant components
int
getSize()
Returns the key size
More specifically, this returns the size of the modulo in bits.
_start_element_handler(resource $parser, string $name, array $attribs)
Start Element Handler
Called by xml_set_element_handler()
_stop_element_handler(resource $parser, string $name)
Stop Element Handler
Called by xml_set_element_handler()
_data_handler(resource $parser, string $data)
Data Handler
Called by xml_set_character_data_handler()
bool
loadKey(string|RSA|array $key, bool|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)
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.
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
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
getPublicKey(int $type = self::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.
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)
mixed
getPrivateKey(int $type = self::PUBLIC_FORMAT_PKCS1)
Returns the private key
The private key is only returned if the currently loaded key contains the constituent prime numbers.
_getPrivatePublicKey(int $mode = self::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
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
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.
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.
string
_string_shift(string $string, int $index = 1)
String Shift
Inspired by array_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
Used with signature production / verification and (if the encryption mode is self::ENCRYPTION_OAEP) encryption and decryption. If $hash isn't supported, sha1 is used.
setMGFHash(string $hash)
Determines which hashing function should be used for the mask generation function
The mask generation function is used by self::ENCRYPTION_OAEP and self::SIGNATURE_PSS and although it's best if Hash and MGFHash are set to the same thing this is not a requirement.
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.
string
_i2osp(BigInteger $x, int $xLen)
Integer-to-Octet-String primitive
See {@link http://tools.ietf.org/html/rfc3447#section-4.1 RFC3447#section-4.1}.
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}.
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}.
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])
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!
BigInteger
_rsaep(BigInteger $m)
RSAEP
See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.1}.
BigInteger
_rsadp(BigInteger $c)
RSADP
See {@link http://tools.ietf.org/html/rfc3447#section-5.1.2 RFC3447#section-5.1.2}.
BigInteger
_rsasp1(BigInteger $m)
RSASP1
See {@link http://tools.ietf.org/html/rfc3447#section-5.2.1 RFC3447#section-5.2.1}.
BigInteger
_rsavp1(BigInteger $s)
RSAVP1
See {@link http://tools.ietf.org/html/rfc3447#section-5.2.2 RFC3447#section-5.2.2}.
string
_mgf1(string $mgfSeed, int $maskLen)
MGF1
See {@link http://tools.ietf.org/html/rfc3447#appendix-B.2.1 RFC3447#appendix-B.2.1}.
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}.
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.
string
_raw_encrypt(string $m)
Raw Encryption / Decryption
Doesn't use padding and is not recommended.
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}.
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.
_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}.
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}.
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}.
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}.
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}.
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"
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}.
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}.
setEncryptionMode(int $mode)
Set Encryption Mode
Valid values include self::ENCRYPTION_OAEP and self::ENCRYPTION_PKCS1.
setSignatureMode(int $mode)
Set Signature Mode
Valid values include self::SIGNATURE_PSS and self::SIGNATURE_PKCS1
setComment(string $comment)
Set public key comment.
string
getComment()
Get public key comment.
string
encrypt(string $plaintext)
Encryption
Both self::ENCRYPTION_OAEP and self::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.
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