Search code examples
phpencryptioncryptographymcryptencryption-symmetric

Need matching PHP encryption function


I built a multi-tiered app 3 years ago that encrypts on the .NET side and decrypts on the PHP side. I never did create a corresponding PHP Encrypt function because I didn't think I would ever need it. Now I do, and I can't remember where I got the PHP decrypt from. I don't know php encryption well enough to build it from scratch and have it work with my existing php Decrypt() function.

I need someone to point me to a PHP Encrypt() function that my php Decrypt() will correct decrypt. All details below.

.NET Encrypt function:

private string Encrypt(string plainText)
{
    if (string.IsNullOrEmpty(plainText))
        return string.Empty;

    string passPhrase = "secret1";
    string saltValue = "secret2";
    int passwordIterations = 1000;
    string initVector = "pOWaTbO92LfXbh69JkYzfT7P465TNc0h";
    int keySize = 256;

    byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
    byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
    byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

    Rfc2898DeriveBytes password = new Rfc2898DeriveBytes(passPhrase, saltValueBytes, passwordIterations);

    byte[] keyBytes = password.GetBytes(keySize / 8);

    // Create uninitialized Rijndael encryption object.
    RijndaelManaged symmetricKey = new RijndaelManaged();
    symmetricKey.BlockSize = 256;
    symmetricKey.KeySize = 256;
    symmetricKey.Padding = PaddingMode.Zeros;
    symmetricKey.Mode = CipherMode.CBC;

    ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
    MemoryStream memoryStream = new MemoryStream();
    CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
    cryptoStream.FlushFinalBlock();
    byte[] cipherTextBytes = memoryStream.ToArray();
    memoryStream.Close();
    cryptoStream.Close();
    string cipherText = Convert.ToBase64String(cipherTextBytes);
    return cipherText;
}

PHP Decrypt function:

function Decrypt($encryptedText) {
    $p = "secret1";
    $s = "secret2";
    $iv = "pOWaTbO92LfXbh69JkYzfT7P465TNc0h";
    $c = 1000;
    $kl = 32;
    $a = 'sha1';
    $hl = strlen(hash($a, null, true)); # Hash length
    $kb = ceil($kl / $hl);              # Key blocks to compute
    $dk = '';                           # Derived key

    # Create key
    for ( $block = 1; $block <= $kb; $block ++ ) {

        # Initial hash for this block
        $ib = $b = hash_hmac($a, $s . pack('N', $block), $p, true);

        # Perform block iterations
        for ( $i = 1; $i < $c; $i ++ )

            # XOR each iterate
            $ib ^= ($b = hash_hmac($a, $b, $p, true));

        $dk .= $ib; # Append iterated block
    }

    $key = substr($dk, 0, $kl);
    $plainText = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, base64_decode($encryptedText), MCRYPT_MODE_CBC, $iv));

    $textArray = str_split($plainText);
    foreach($textArray as $char) {
        $ascii = ord($char);
        if($ascii < 32 || $ascii > 127){
            return "";
        }
    }

    return $plainText;
}

My .NET Encrypt() and PHP Decrypt() work great together, no problems. Is there a PHP encryption hero out there that can show me a php Encrypt() function that works with the posted php Decrypt() function?

One encryption example: "SnoqL/xcgfFBkhZld+QXRnsl7zS9viJpJsbm4MocDUQ=" decrypts to the string "443". No quotes.


Solution

  • Below is the Encrypt code with proof. I take 'This is a test!' encrypted with my function as an input to your decrypt function which decrypts it successfully and prints 'This is a test!' to the screen.

    <?
    
    echo Decrypt(Encrypt('This is a test!'));
    
    function Encrypt($plainText) {
      $key = createKey();
      $encryptedText = rtrim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $plainText, MCRYPT_MODE_CBC, "pOWaTbO92LfXbh69JkYzfT7P465TNc0h")));
    
      return $encryptedText;
    }
    
    function Decrypt($encryptedText) {
      $key = createKey();
      $plainText = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, base64_decode($encryptedText), MCRYPT_MODE_CBC, "pOWaTbO92LfXbh69JkYzfT7P465TNc0h"));
    
      return $plainText;
    }
    
    function createKey() {
      $p = "secret1";
      $s = "secret2";
      $dk = '';
    
      for ($block = 1; $block <= 2; $block++) {
        $ib = $b = hash_hmac('sha1', $s . pack('N', $block), $p, true);
    
        for ($i = 1; $i < 1000; $i++)
          $ib ^= ($b = hash_hmac('sha1', $b, $p, true));
          $dk .= $ib;
      }
    
      return substr($dk, 0, 32);
    }
    

    Created a createKey() function which moves a lot of duplicate code out of our otherwise simple Decrypt() / Encrypt() functions.