shaiss shaiss - 2 months ago 38
PHP Question

PHP Encryption & Decryption

I'm trying to do a simple task. Encypt a value in PHP and Decrypt it in my app.
I figure I'd use tripleDES or Rijdael 128 or 256

I though this should be simple. Can anyone point me in the right direction?

Thank you


We have some ciphers working between C# on .NET and PHP. I am not familiar with I assume it uses the same crypto library System.Security.Cryptography.

On PHP side, we switched from mcrypt to OpenSSL because some modes and paddings are not supported by mcrypt.

As long as you use same algorithm (DES, AES etc), same mode (CBC, ECB etc), same padding (PKCS1, PKCS5), the cipher should work on both platforms.

Example of encryption using AES-128 on PHP side using mcrypt,

    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128);
    $data = $this->paddingAlgorithm->padData($data, $blockSize);
    return $iv . mcrypt_encrypt($this->MCRYPT_DES, $keyBytes, $data, MCRYPT_MODE_CBC, $iv);

Please note that we use PKCS7 padding but mcrypt doesn't support it so we have to write the padding algorithm. We also prepend the IV (Initial Vector) to the cipher text. You might store it somewhere else but you need that to decrypt.

Here is the corresponding C# code to setup the cipher to decrypt,

    // create the underlying symmetric algorithm with the given name
    algorithm = (SymmetricAlgorithm)CryptoConfig.CreateFromName("RIJNDAEL");
    // set cipher mode
    algorithm.Mode = CipherMode.CBC;
    // set padding mode
    algorithm.Padding = PaddingMode.PKCS7;