Pure-PHP PKCS#1 (v2.1) compliant implementation of RSA.
PHP versions 4 and 5
Here's an example of how to encrypt and decrypt text with this library:
createKey());
$plaintext = 'terrafrost';
$rsa->loadKey($privatekey);
$ciphertext = $rsa->encrypt($plaintext);
$rsa->loadKey($publickey);
echo $rsa->decrypt($ciphertext);
?>
Here's an example of how to create signatures and verify signatures with this library:
createKey());
$plaintext = 'terrafrost';
$rsa->loadKey($privatekey);
$signature = $rsa->sign($plaintext);
$rsa->loadKey($publickey);
echo $rsa->verify($plaintext, $signature) ? 'verified' : 'unverified';
?>
LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Constants
CRYPT_RSA_ENCRYPTION_OAEP
= 1
Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding}
(OAEP) for encryption / decryption. Uses sha1 by default.
CRYPT_RSA_ENCRYPTION_PKCS1
= 2
Use PKCS#1 padding. Although CRYPT_RSA_ENCRYPTION_OAEP offers more security, including PKCS#1 padding is necessary for purposes of backwards
compatability with protocols (like SSH-1) written before OAEP's introduction.
CRYPT_RSA_SIGNATURE_PSS
= 1
Use the Probabilistic Signature Scheme for signing Uses sha1 by default.
CRYPT_RSA_SIGNATURE_PKCS1
= 2
Use the PKCS#1 scheme by default. Although CRYPT_RSA_SIGNATURE_PSS offers more security, including PKCS#1 signing is necessary for purposes of backwards
compatability with protocols (like SSH-2) written before PSS's introduction.
CRYPT_RSA_ASN1_INTEGER
= 2
ASN1 Integer
CRYPT_RSA_ASN1_SEQUENCE
= 48
ASN1 Sequence (with the constucted bit set)
CRYPT_RSA_MODE_INTERNAL
= 1
To use the pure-PHP implementation
CRYPT_RSA_MODE_OPENSSL
= 2
To use the OpenSSL library (if enabled; otherwise, the internal implementation will be used)
CRYPT_RSA_PRIVATE_FORMAT_PKCS1
= 0
PKCS#1 formatted private key Used by OpenSSH
CRYPT_RSA_PRIVATE_FORMAT_PUTTY
= 1
PuTTY formatted private key
CRYPT_RSA_PRIVATE_FORMAT_XML
= 2
XML formatted private key
CRYPT_RSA_PUBLIC_FORMAT_RAW
= 3
Raw public key An array containing two 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
CRYPT_RSA_PUBLIC_FORMAT_PKCS1
= 4
PKCS#1 formatted public key
CRYPT_RSA_PUBLIC_FORMAT_XML
= 5
XML formatted public key
CRYPT_RSA_PUBLIC_FORMAT_OPENSSH
= 6
OpenSSH formatted public key Place in $HOME/.ssh/authorized_keys
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.
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.
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}.
Arguments
Name
Type
Description
Default
$m
String
$l
String
''
Return value
Type
Description
String
Tags
Name
Description
access
private
_rsaes_pkcs1_v1_5_decrypt(
String
$c,
)
:
String
Description
RSAES-PKCS1-V1_5-DECRYPT See {@link http://tools.ietf.org/html/rfc3447#section-7.2.2 RFC3447#section-7.2.2}.
For compatability 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 compatability 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.
Arguments
Name
Type
Description
Default
$c
String
Return value
Type
Description
String
Tags
Name
Description
access
private
_rsaes_pkcs1_v1_5_encrypt(
String
$m,
)
:
String
Description
RSAES-PKCS1-V1_5-ENCRYPT See {@link http://tools.ietf.org/html/rfc3447#section-7.2.1 RFC3447#section-7.2.1}.
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.
Arguments
Name
Type
Description
Default
$bits
n/a
1024
$timeout
n/a
false
$partial
n/a
array()
Return value
Type
Description
n/a
n/a
Tags
Name
Description
access
public
decrypt(
$ciphertext,
)
:
String
Description
Decryption
Arguments
Name
Type
Description
Default
$ciphertext
n/a
Return value
Type
Description
String
Tags
Name
Description
see
access
public
encrypt(
String
$plaintext,
)
:
String
Description
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.
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.
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)
Arguments
Name
Type
Description
Default
$key
String
$type
Integer
optional
false
Return value
Type
Description
n/a
n/a
Tags
Name
Description
access
public
setEncryptionMode(
Integer
$mode,
)
:
n/a
Description
Set Encryption Mode Valid values include CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1.
Arguments
Name
Type
Description
Default
$mode
Integer
Return value
Type
Description
n/a
n/a
Tags
Name
Description
access
public
setHash(
String
$hash,
)
:
n/a
Description
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.
Arguments
Name
Type
Description
Default
$hash
String
Return value
Type
Description
n/a
n/a
Tags
Name
Description
access
public
setMGFHash(
String
$hash,
)
:
n/a
Description
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.
Arguments
Name
Type
Description
Default
$hash
String
Return value
Type
Description
n/a
n/a
Tags
Name
Description
access
public
setPassword(
String
$password,
)
:
n/a
Description
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 true.
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.
Do note that when a new key is loaded the index will be cleared.
Returns true on success, false on failure
Arguments
Name
Type
Description
Default
$key
String
$type
Integer
optional
CRYPT_RSA_PUBLIC_FORMAT_PKCS1
Return value
Type
Description
Boolean
Tags
Name
Description
see
access
public
setPublicKeyFormat(
Integer
$format,
)
:
n/a
Description
Determines the public key format
Arguments
Name
Type
Description
Default
$format
Integer
Return value
Type
Description
n/a
n/a
Tags
Name
Description
see
access
public
setSaltLength(
$sLen,
)
:
n/a
Description
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.
Arguments
Name
Type
Description
Default
$sLen
n/a
Return value
Type
Description
n/a
n/a
Tags
Name
Description
access
public
setSignatureMode(
Integer
$mode,
)
:
n/a
Description
Set Signature Mode Valid values include CRYPT_RSA_SIGNATURE_PSS and CRYPT_RSA_SIGNATURE_PKCS1
Coefficients for Chinese Remainder Theorem (ie. qInv)
Array
public
$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.
Mixed
public
$current
=
Current String For use with parsing XML formatted keys.
Integer
public
$encryptionMode
=
CRYPT_RSA_ENCRYPTION_OAEP
Encryption mode
\Math_BigInteger
public
$exponent
=
Exponent (ie. e or d)
Array
public
$exponents
=
Exponents for Chinese Remainder Theorem (ie. dP and dQ)
Integer
public
$hLen
=
Length of hash function output
\Crypt_Hash
public
$hash
=
Hash function
String
public
$hashName
=
Hash name
\Math_BigInteger
public
$k
=
Modulus length
Integer
public
$mgfHLen
=
Length of MGF hash function output
\Crypt_Hash
public
$mgfHash
=
Hash function for the Mask Generation Function
\Math_BigInteger
public
$modulus
=
Modulus (ie. n)
Array
public
$one
=
Precomputed One
String
public
$password
=
''
Password
Array
public
$primes
=
Primes for Chinese Remainder Theorem (ie. p and q)
Integer
public
$privateKeyFormat
=
CRYPT_RSA_PRIVATE_FORMAT_PKCS1
Private Key Format
Mixed
public
$publicExponent
=
false
Public Exponent
Integer
public
$publicKeyFormat
=
CRYPT_RSA_PUBLIC_FORMAT_PKCS1
Public Key Format
Integer
public
$sLen
=
Length of salt
Integer
public
$signatureMode
=
CRYPT_RSA_SIGNATURE_PSS