\phpseclib\CryptRSA

Pure-PHP PKCS#1 compliant implementation of RSA.

Summary

Methods
Properties
Constants
__construct()
createKey()
_convertPrivateKey()
_convertPublicKey()
_parseKey()
getSize()
_start_element_handler()
_stop_element_handler()
_data_handler()
loadKey()
setPassword()
setPublicKey()
setPrivateKey()
getPublicKey()
getPublicKeyFingerprint()
getPrivateKey()
_getPrivatePublicKey()
__toString()
__clone()
_generateMinMax()
_decodeLength()
_encodeLength()
_string_shift()
setPrivateKeyFormat()
setPublicKeyFormat()
setHash()
setMGFHash()
setSaltLength()
_i2osp()
_os2ip()
_exponentiate()
_blind()
_equals()
_rsaep()
_rsadp()
_rsasp1()
_rsavp1()
_mgf1()
_rsaes_oaep_encrypt()
_rsaes_oaep_decrypt()
_raw_encrypt()
_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()
_rsassa_pkcs1_v1_5_sign()
_rsassa_pkcs1_v1_5_verify()
setEncryptionMode()
setSignatureMode()
setComment()
getComment()
encrypt()
decrypt()
sign()
verify()
_extractBER()
$zero
$one
$privateKeyFormat
$publicKeyFormat
$modulus
$k
$exponent
$primes
$exponents
$coefficients
$hashName
$hash
$hLen
$sLen
$mgfHash
$mgfHLen
$encryptionMode
$signatureMode
$publicExponent
$password
$components
$current
$configFile
$comment
ENCRYPTION_OAEP
ENCRYPTION_PKCS1
ENCRYPTION_NONE
SIGNATURE_PSS
SIGNATURE_PKCS1
ASN1_INTEGER
ASN1_BITSTRING
ASN1_OCTETSTRING
ASN1_OBJECT
ASN1_SEQUENCE
MODE_INTERNAL
MODE_OPENSSL
PRIVATE_FORMAT_PKCS1
PRIVATE_FORMAT_PUTTY
PRIVATE_FORMAT_XML
PRIVATE_FORMAT_PKCS8
PRIVATE_FORMAT_OPENSSH
PUBLIC_FORMAT_RAW
PUBLIC_FORMAT_PKCS1
PUBLIC_FORMAT_PKCS1_RAW
PUBLIC_FORMAT_XML
PUBLIC_FORMAT_OPENSSH
PUBLIC_FORMAT_PKCS8
No protected methods found
No protected properties found
N/A
No private methods found
No private properties found
N/A

Constants

ENCRYPTION_OAEP

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

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

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

SIGNATURE_PSS

Use the Probabilistic Signature Scheme for signing

Uses sha1 by default.

SIGNATURE_PKCS1

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 Integer

ASN1_BITSTRING

ASN1_BITSTRING

ASN1 Bit String

ASN1_OCTETSTRING

ASN1_OCTETSTRING

ASN1 Octet String

ASN1_OBJECT

ASN1_OBJECT

ASN1 Object Identifier

ASN1_SEQUENCE

ASN1_SEQUENCE

ASN1 Sequence (with the constucted bit set)

MODE_INTERNAL

MODE_INTERNAL

To use the pure-PHP implementation

MODE_OPENSSL

MODE_OPENSSL

To use the OpenSSL library

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

PRIVATE_FORMAT_PKCS1

PRIVATE_FORMAT_PKCS1

PKCS#1 formatted private key

Used by OpenSSH

PRIVATE_FORMAT_PUTTY

PRIVATE_FORMAT_PUTTY

PuTTY formatted private key

PRIVATE_FORMAT_XML

PRIVATE_FORMAT_XML

XML formatted private key

PRIVATE_FORMAT_PKCS8

PRIVATE_FORMAT_PKCS8

PKCS#8 formatted private key

PRIVATE_FORMAT_OPENSSH

PRIVATE_FORMAT_OPENSSH

OpenSSH formatted private key

PUBLIC_FORMAT_RAW

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

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_PKCS1_RAW

PUBLIC_FORMAT_XML

PUBLIC_FORMAT_XML

XML formatted public key

PUBLIC_FORMAT_OPENSSH

PUBLIC_FORMAT_OPENSSH

OpenSSH formatted public key

Place in $HOME/.ssh/authorized_keys

PUBLIC_FORMAT_PKCS8

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

$privateKeyFormat

$privateKeyFormat : integer

Private Key Format

Type

integer

$publicKeyFormat

$publicKeyFormat : integer

Public Key Format

Type

integer

$primes

$primes : array

Primes for Chinese Remainder Theorem (ie. p and q)

Type

array

$exponents

$exponents : array

Exponents for Chinese Remainder Theorem (ie. dP and dQ)

Type

array

$coefficients

$coefficients : array

Coefficients for Chinese Remainder Theorem (ie. qInv)

Type

array

$hashName

$hashName : string

Hash name

Type

string

$hLen

$hLen : integer

Length of hash function output

Type

integer

$sLen

$sLen : integer

Length of salt

Type

integer

$mgfHash

$mgfHash : \phpseclib\Crypt\Hash

Hash function for the Mask Generation Function

Type

\phpseclib\Crypt\Hash

$mgfHLen

$mgfHLen : integer

Length of MGF hash function output

Type

integer

$encryptionMode

$encryptionMode : integer

Encryption mode

Type

integer

$signatureMode

$signatureMode : integer

Signature mode

Type

integer

$publicExponent

$publicExponent : mixed

Public Exponent

Type

mixed

$password

$password : string

Password

Type

string

$components

$components : array

Components

For use with parsing XML formatted keys. PHP's XML Parser functions use utilized - instead of PHP's DOM functions - because PHP's XML Parser functions work on PHP4 whereas PHP's DOM functions - although surperior - don't.

Type

array

$current

$current : mixed

Current String

For use with parsing XML formatted keys.

Type

mixed

$configFile

$configFile : mixed

OpenSSL configuration file name.

Set to null to use system configuration file.

Type

mixed

$comment

$comment : string

Public key comment field.

Type

string

Methods

__construct()

__construct() : \phpseclib\Crypt\RSA

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.

Returns

\phpseclib\Crypt\RSA

createKey()

createKey(integer  $bits = 1024, integer  $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 \phpseclib\Crypt\RSA::createKey() as the third parameter for further processing.

Parameters

integer $bits
integer $timeout
$partial

_convertPrivateKey()

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

Convert a private key to the appropriate format.

Parameters

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

Returns

string

_convertPublicKey()

_convertPublicKey(  $n,   $e) : string

Convert a public key to the appropriate format

Parameters

$n
$e

Returns

string

_parseKey()

_parseKey(string|array  $key, integer  $type) : array|boolean

Break a public or private key down into its constituant components

Parameters

string|array $key
integer $type

Returns

array|boolean

getSize()

getSize() : integer

Returns the key size

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

Returns

integer

_start_element_handler()

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

_stop_element_handler(resource  $parser, string  $name) 

Stop Element Handler

Called by xml_set_element_handler()

Parameters

resource $parser
string $name

_data_handler()

_data_handler(resource  $parser, string  $data) 

Data Handler

Called by xml_set_character_data_handler()

Parameters

resource $parser
string $data

loadKey()

loadKey(string|\phpseclib\Crypt\RSA|array  $key, boolean|integer  $type = false) : boolean

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|\phpseclib\Crypt\RSA|array $key
boolean|integer $type

optional

Returns

boolean

setPassword()

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

setPublicKey()

setPublicKey(string  $key = false, integer  $type = false) : boolean

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

integer $type

optional

Returns

boolean

setPrivateKey()

setPrivateKey(string  $key = false, integer  $type = false) : boolean

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

integer $type

optional

Returns

boolean

getPublicKey()

getPublicKey(integer  $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.

Parameters

integer $type

optional

getPublicKeyFingerprint()

getPublicKeyFingerprint(string  $algorithm = 'md5') : mixed

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.

Returns

mixed

getPrivateKey()

getPrivateKey(integer  $type = self::PUBLIC_FORMAT_PKCS1) : mixed

Returns the private key

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

Parameters

integer $type

optional

Returns

mixed

_getPrivatePublicKey()

_getPrivatePublicKey(  $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

Parameters

$mode

__toString()

__toString() : string

__toString() magic method

Returns

string

__clone()

__clone() : \phpseclib\Crypt\Crypt_RSA

__clone() magic method

Returns

\phpseclib\Crypt\Crypt_RSA

_generateMinMax()

_generateMinMax(integer  $bits) : array

Generates the smallest and largest numbers requiring $bits bits

Parameters

integer $bits

Returns

array

_decodeLength()

_decodeLength(string  $string) : integer

DER-decode the length

DER supports lengths up to (28)127, however, we'll only support lengths up to (28)4. See X.690 paragraph 8.1.3 for more information.

Parameters

string $string

Returns

integer

_encodeLength()

_encodeLength(integer  $length) : string

DER-encode the length

DER supports lengths up to (28)127, however, we'll only support lengths up to (28)4. See X.690 paragraph 8.1.3 for more information.

Parameters

integer $length

Returns

string

_string_shift()

_string_shift(string  $string, integer  $index = 1) : string

String Shift

Inspired by array_shift

Parameters

string $string
integer $index

Returns

string

setPrivateKeyFormat()

setPrivateKeyFormat(integer  $format) 

Determines the private key format

Parameters

integer $format

setPublicKeyFormat()

setPublicKeyFormat(integer  $format) 

Determines the public key format

Parameters

integer $format

setHash()

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.

Parameters

string $hash

setMGFHash()

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.

Parameters

string $hash

setSaltLength()

setSaltLength(  $sLen) 

Determines the salt length

To quote from RFC3447#page-38:

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

Parameters

$sLen

_mgf1()

_mgf1(string  $mgfSeed,   $maskLen) : string

MGF1

See RFC3447#appendix-B.2.1.

Parameters

string $mgfSeed
$maskLen

Returns

string

_rsaes_oaep_decrypt()

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

RSAES-OAEP-DECRYPT

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

Returns

string

_raw_encrypt()

_raw_encrypt(string  $m) : string

Raw Encryption / Decryption

Doesn't use padding and is not recommended.

Parameters

string $m

Returns

string

_rsaes_pkcs1_v1_5_encrypt()

_rsaes_pkcs1_v1_5_encrypt(string  $m) : string

RSAES-PKCS1-V1_5-ENCRYPT

See RFC3447#section-7.2.1.

Parameters

string $m

Returns

string

_rsaes_pkcs1_v1_5_decrypt()

_rsaes_pkcs1_v1_5_decrypt(string  $c) : string

RSAES-PKCS1-V1_5-DECRYPT

See 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

Returns

string

_emsa_pss_encode()

_emsa_pss_encode(string  $m, integer  $emBits) 

EMSA-PSS-ENCODE

See RFC3447#section-9.1.1.

Parameters

string $m
integer $emBits

_emsa_pss_verify()

_emsa_pss_verify(string  $m, string  $em, integer  $emBits) : string

EMSA-PSS-VERIFY

See RFC3447#section-9.1.2.

Parameters

string $m
string $em
integer $emBits

Returns

string

_rsassa_pss_sign()

_rsassa_pss_sign(string  $m) : string

RSASSA-PSS-SIGN

See RFC3447#section-8.1.1.

Parameters

string $m

Returns

string

_rsassa_pss_verify()

_rsassa_pss_verify(string  $m, string  $s) : string

RSASSA-PSS-VERIFY

See RFC3447#section-8.1.2.

Parameters

string $m
string $s

Returns

string

_emsa_pkcs1_v1_5_encode()

_emsa_pkcs1_v1_5_encode(string  $m, integer  $emLen) : string

EMSA-PKCS1-V1_5-ENCODE

See RFC3447#section-9.2.

Parameters

string $m
integer $emLen

Returns

string

_rsassa_pkcs1_v1_5_sign()

_rsassa_pkcs1_v1_5_sign(string  $m) : string

RSASSA-PKCS1-V1_5-SIGN

See RFC3447#section-8.2.1.

Parameters

string $m

Returns

string

_rsassa_pkcs1_v1_5_verify()

_rsassa_pkcs1_v1_5_verify(string  $m,   $s) : string

RSASSA-PKCS1-V1_5-VERIFY

See RFC3447#section-8.2.2.

Parameters

string $m
$s

Returns

string

setEncryptionMode()

setEncryptionMode(integer  $mode) 

Set Encryption Mode

Valid values include self::ENCRYPTION_OAEP and self::ENCRYPTION_PKCS1.

Parameters

integer $mode

setSignatureMode()

setSignatureMode(integer  $mode) 

Set Signature Mode

Valid values include self::SIGNATURE_PSS and self::SIGNATURE_PKCS1

Parameters

integer $mode

setComment()

setComment(string  $comment) 

Set public key comment.

Parameters

string $comment

getComment()

getComment() : string

Get public key comment.

Returns

string

encrypt()

encrypt(string  $plaintext) : string

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.

Parameters

string $plaintext

Returns

string

decrypt()

decrypt(  $ciphertext) : string

Decryption

Parameters

$ciphertext

Returns

string

sign()

sign(string  $message) : string

Create a signature

Parameters

string $message

Returns

string

verify()

verify(string  $message, string  $signature) : boolean

Verifies a signature

Parameters

string $message
string $signature

Returns

boolean

_extractBER()

_extractBER(string  $str) : string

Extract raw BER from Base64 encoding

Parameters

string $str

Returns

string