Wednesday, May 24, 2017

PHP Encrypt Data With OpenSSL Public Key And Decrypt With OpenSSL Private Key

Below is a PHP code snippet to encrypt data with a public key and then again decrypt the encrypted data with a private key.
 

If you have fetched the problem "error:0406D06E:rsa routines:RSA_padding_add_PKCS1_type_2:data too large for key size" then use the below code snippet to overcome this problem.
 

It's a good solution to handle big size data, but don't try too big size data with this method actually when you post file.
Raw data is fine.  




$data = "Large data to test. Large data to test. Large data to test. Large data to test.";
$data = $data . $data . $data . $data . $data . $data . $data . $data;
$data = $data . $data . $data . $data . $data . $data . $data . $data;
encryptAndDecrypt($data);

function encryptAndDecrypt($data)
{
    echo "Original data length=" . strlen($data) . "<BR>";

    $private_key = openssl_pkey_get_private(readServerFile("./XeroCerts/privatekey.pem"));
    $public_key = openssl_pkey_get_public(readServerFile("./XeroCerts/publickey.cer"));

    //Block size for encryption block cipher for 1024 bit key
    $encrypt_size = 110;

    //Block size for decryption block cipher for 1024 bit key
    $decrypt_size = 128;

    //For encryption we would use:
    $encrypted = '';
    $data = str_split($data, $encrypt_size);
    foreach ($data as $chunk) {
        openssl_public_encrypt($chunk, $partial, $public_key, OPENSSL_PKCS1_PADDING);
        $encrypted .= $partial;
    }
    openssl_free_key($public_key);
    $encrypted = base64_encode($encrypted);
    echo "Encrypted=" . $encrypted . "<BR>";

    //For decryption we would use:
    $decrypted = '';
    $data = str_split(base64_decode($encrypted), $decrypt_size);
    foreach ($data as $chunk) {
        openssl_private_decrypt($chunk, $partial, $private_key, OPENSSL_PKCS1_PADDING);
        $decrypted .= $partial;
    }
    openssl_free_key($private_key);
    echo "Decrypted=" . $decrypted;
    die();
}

Output of the above code snippet is below: 


If you don't want to save strings in clear text, there are new php functions (php >= 5.3.0) that can be of help; openssl_encrypt() and openssl_decrypt().

Original data length=5056
Encrypted=Vf2GHkx..............LgpFjM9gY/FkIYWaELHl3I=
Decrypted=Large data to test. ............ Large data to test. Large data to test. Large data to test.

No comments:

Post a Comment