Viewed   135 times

Is there any class for PHP 5.3 that provides RSA encryption/decryption without padding?

I've got private and public key, p,q, and modulus.



You can use phpseclib, a pure PHP RSA implementation:


$privatekey = file_get_contents('private.key');

$rsa = new Crypt_RSA();

$plaintext = new Math_BigInteger('aaaaaa');
echo $rsa->_exponentiate($plaintext)->toBytes();
Friday, November 25, 2022

Start with this:

After that, have a look at Pascal MARTIN's answer in How do I encrypt a string in PHP?

Tuesday, December 13, 2022



public static string RSAEncryption(string aes_key, string aes_iv)
        //encode key and iv to byte array
        byte[] KeyToEncrypt = Encoding.Default.GetBytes(aes_key);
        byte[] IVToEncrypt = Encoding.Default.GetBytes(aes_iv);

        //get RSA public key from xml file
        TextReader reader = new StreamReader("publicKey.xml");
        string publicKey = reader.ReadToEnd();

        //Values to store encrypted symmetric keys.
        byte[] EncryptedKey;
        byte[] EncryptedIV;

        //Create a new instance of RSACryptoServiceProvider.
        RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

        //set xml string as public key

        //Encrypt the symmetric key and IV.
        EncryptedKey = RSA.Encrypt(KeyToEncrypt, false);
        EncryptedIV = RSA.Encrypt(IVToEncrypt, false);
        System.IO.File.WriteAllText(@"C:WriteTextCryptKey.txt", Convert.ToBase64String(EncryptedKey));
        System.IO.File.WriteAllText(@"C:WriteTextCryptIV.txt", Convert.ToBase64String(EncryptedIV));
        return Convert.ToBase64String(EncryptedKey);


public function RSADecryption($key, $iv) {
    $PrivateKeyFile = RSA_Private;
    $rsa = new Crypt_RSA();
    $rsa->loadKey($PrivateKeyFile); //private key in xml
    // decrypt key and iv for aes decryption
    $aes_key = $rsa->decrypt(base64_decode($key));
    $aes_iv = $rsa->decrypt(base64_decode($iv));
Sunday, August 21, 2022

By default phpseclib uses sha1 as the hash. You probably need to do $rsa->setHash('md5').

Saturday, October 15, 2022

My first thought... you may need to do define('CRYPT_RSA_PKCS15_COMPAT', true). phpseclib - which you're using on the PHP side - uses a padding technique defined in PKCS1 v2.0+, which differs slightly from the padding technique described in PKCS1 v1.5. Doing define('CRYPT_RSA_PKCS15_COMPAT', true) before you do the encryption might help.

Failing that, it might be worthwhile to try to do $rsa->publicExponent = new Math_BigInteger($exp, -16)

I'll try to play around with this some more when I get home from work..

Wednesday, August 10, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :