Home > Net >  DES encryption using openSSL in PHP
DES encryption using openSSL in PHP

Time:02-01

Trying to use openSSL for encryption and decryption using DES, decryption is working fine but encryption is not working

The output string generated by the encryption method is different than what we gave to the decryption method

function decrypt()
{
        $password         = 'thisIsASecretKey';
        $encryptedString  =  'YbpeWd70LAxTCQvZjNlnwQ=='; // sample
        $opensslDecrypt   = openssl_decrypt(base64_decode($encryptedString),'DES-ECB', $password, OPENSSL_RAW_DATA, '');  
        print("\nThe plain: ".$opensslDecrypt);  // OUTPUT :- 123123123
}

function encrypt()
{
    $password         = 'thisIsASecretKey';
    $plainString  =  '123123123'; // sample
    $opensslDecrypt   = openssl_encrypt(base64_encode($plainString),'DES-ECB', $password, OPENSSL_RAW_DATA, '');  
    print("\nThe plain: ".$opensslDecrypt);  // Expected OUTPUT :- YbpeWd70LAxTCQvZjNlnwQ==
}

CodePudding user response:

There's an error in the encrypt() function:

openssl_encrypt(base64_encode($plainString),'DES-ECB', $password, OPENSSL_RAW_DATA, '')

base64_encode() is at the wrong place, it should be used on the value returned by openssl_encrypt like this:

base64_encode(openssl_encrypt($plainString,'DES-ECB', $password, OPENSSL_RAW_DATA, ''));

This way the raw data is converted to base64 as the decrypt() function expects a base64 encoded string.

  • Related