Difference between .NET and PHP Encryption

I have the following C # code that generates keys:

public static byte[] Encrypt(byte[] plainData, string salt) { DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); DES.Key = ASCIIEncoding.ASCII.GetBytes(salt); DES.IV = ASCIIEncoding.ASCII.GetBytes(salt); ICryptoTransform desencrypt = DES.CreateEncryptor(); byte[] encryptedData = desencrypt.TransformFinalBlock(plainData, 0, plainData.Length); return encryptedData; } private string GetEncryptedKey(string key) { return BitConverter.ToString(KeyGeneratorForm.Encrypt(ASCIIEncoding.ASCII.GetBytes(key), "abcdefgh")).Replace("-", ""); } 

I am trying to do the exact same thing in PHP:

 function get_encrypted_key($key){ $salt = "abcdefgh"; return bin2hex(mcrypt_encrypt(MCRYPT_DES, $salt, $key, MCRYPT_MODE_CBC, $salt)); } 

However, there is a slight discrepancy in the results, since the last 16 characters are always different:

 With key "Benjamin Franklin": C# : 0B3C6E5DF5D747FB3C50DE952FECE3999768F35B890BC391 PHP: 0B3C6E5DF5D747FB3C50DE952FECE3993A881F9AF348C64D With key "President Franklin D Roosevelt": C# : C119B50A5A7F8C905A86A43F5694B4D7DD1E8D0577F1CEB32A86FABCEA5711E1 PHP: C119B50A5A7F8C905A86A43F5694B4D7DD1E8D0577F1CEB37ACBE60BB1D21F3F 

I also tried converting padding to my key using the following code:

 function get_encrypted_key($key){ $salt = "abcdefgh"; $extra = 8 - (strlen($key) % 8); if($extra > 0) { for($i = 0; $i < $extra; $i++) { $key.= "\0"; } } return bin2hex(mcrypt_encrypt(MCRYPT_DES, $salt, $key, MCRYPT_MODE_CBC, $salt)); } 

But I get the same results as without filling.

If you have any clue as to what is happening, I would be happy to hear about it! :)

thanks

+7
source share
1 answer

You mentioned trying the "classic" debugger. The following quick adaptation of the snippet published in the mcrypt_encrypt documentation gives the same results as you, starting with C #.

PKCS # 7 (the default padding scheme used by C # SymmetricAlgorithm ), with bytes, where each byte padding value is equal to the number of padding bytes, rather than zero bytes.

 function get_encrypted_key($key) { $salt = 'abcdefgh'; $block = mcrypt_get_block_size('des', 'cbc'); $pad = $block - (strlen($key) % $block); $key .= str_repeat(chr($pad), $pad); return bin2hex(mcrypt_encrypt(MCRYPT_DES, $salt, $key, MCRYPT_MODE_CBC, $salt)); } 

Test output:

 php > echo get_encrypted_key('Benjamin Franklin'); 0b3c6e5df5d747fb3c50de952fece3999768f35b890bc391 php > echo get_encrypted_key('President Franklin D Roosevelt'); c119b50a5a7f8c905a86a43f5694b4d7dd1e8d0577f1ceb32a86fabcea5711e1 
+4
source

All Articles