srdjan
srdjan

Reputation: 41

Mirror code snippet that generates key and initialization vector in PHP

I have a method written in C# that generates a Key and Initialization Vector and uses them to encrypt data. I am trying to mirror that method to PHP implementation, but the problem is the different encrypted values generated from C# and PHP. I did the investigation and found that the Key and IV used for encryption are different in the two implementations.

Below are the corresponding code blocks used to generate key and IV in C# and PHP.

C# code snippet

string password = 'pass here';
byte[] salt = new byte[] { 0x43, 0x87, 0x23, 0x72, 0x45, 0x56, 0x68, 0x14, 0x62, 0x84 };
PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, salt);
aesAlg.Key = pdb.GetBytes(32);
aesAlg.IV = pdb.GetBytes(16);
Console.WriteLine("Key: " + BitConverter.ToString(aesAlg.Key).Replace("-", ""));
Console.WriteLine("IV: " + BitConverter.ToString(aesAlg.IV).Replace("-", ""));

PHP code snippet

$password = 'pass here';
$salt = hex2bin('43872372455668146284');
$keyLength = 32; // 32 bytes for AES-256 key
$ivLength = 16;  // 16 bytes for AES block size
$combinedLength = $keyLength + $ivLength;
$derivedBytes = hash_pbkdf2("sha1", $password, $salt, 100, $combinedLength, true);
$key = substr($derivedBytes, 0, $keyLength);
$iv = substr($derivedBytes, $keyLength, $ivLength);
echo "Key: " . bin2hex($key) . "\n";
echo "IV: " . bin2hex($iv) . "\n";

Does anyone notice what is different in that two implementations that cause code to generate different key and IV?

Upvotes: 0

Views: 74

Answers (0)

Related Questions