0

I've to implement an aes256 encryption in PHP with the same key an iv from an existing .NET application to encrypt passwords identical (same ciphertext). I've to use the same IV (16 Byte) and Key (32 Byte) as the .NET Application. My problem is, that I don't understand how I've to convert the key and IV from .NET Application to php strings (the php mycrypt_encrypt function, which I'd like to use for the php aes encryption, need IV and key as strings parameters), because php doesn't have byte arrays. For example the IV and key are following .NET arrays

byte[] iv = {128,44,74,135,31,23,0,133,22,13,118,17,187,113,33,111};
byte[] key = {100,123,214,125,109,19,10,229,118,31,44,157,36,10,0,103,15,16,101,126,0,122,122,86,119,29,140,213,27,129,119,50};

Now I'd like to use these key and iv to encrypt in PHP an password with

mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $paddedPlainText, MCRYPT_MODE_CBC, $iv).

How I've the convert the byte arrays from .NET to strings so that I can use them in the PHP mcrypt_encrypt function?

I tried a base64 encode for the .NET Byte Arrays ( Convert.ToBase64String(key), Convert.ToBase64String(iv)).The following PHP I already wrote:

function pkcs7pad($plaintext, $blocksize = 16)
{
    $padsize = $blocksize - (strlen($plaintext) % $blocksize);
    return $plaintext . str_repeat(chr($padsize), $padsize);
}

public function testPW()
{
    $key = base64_decode('[HERE IS MY KEY base64 encoded]');
    $iv = base64_decode('[HERE IS MY IV base64 encoded]');

    $plaintext = 'test1234';

    $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $this->pkcs7pad($plaintext), MCRYPT_MODE_CBC, $iv);

    return base64_encode($ciphertext);
}

But the returned cipher of testPW isn't the same as the one of the .NET Application. The returned Cipher has also a smaller length than the .NET one.

Overtronje
  • 53
  • 1
  • 5
  • You should never encrypt your user's passwords. You need to use hashing instead with some strong ones being PBKDF2, bcrypt and scrypt. Since hash functions are one-way function, you won't be able to "decrypt" the hashes. In order to authenticate your user, you can run the password through the hash function again in order to compare with the hash that is stored in the database. See more: [How to securely hash passwords?](http://security.stackexchange.com/q/211/45523) – Artjom B. Nov 13 '15 at 10:46
  • Yes you're right. But it's a requirement that I've to use the same mechanism as in the .NET Application. So I can't change that. – Overtronje Nov 13 '15 at 12:37
  • I suggest that you encode the key and IV into some common format such as Hex or Base64 and decode it in PHP. There are many solutions available. Furthermore, note that mcrypt uses Zero Padding by default. I suggest that you use the [PKCS#7 padding (default in .Net) in PHP](http://stackoverflow.com/a/27590539/1816580). – Artjom B. Nov 13 '15 at 14:31

0 Answers0