I have a problem trying to encrypt a string in PHP and also in C# using DES (cbc) encryption. The problem I'm facing is that I'm getting different results using the different languages.
In PHP:
Results in
In C#:
Results in
You can see that they are close...
PHP: HLp51qoFW0rimOT afCVTVQ==
C# : HLp51qoFW0ojU8e GEGkk4w==
But something is going wrong somewhere, I suspect it's a difference between (PHP) pack("H*", '0F26EF560F26EF 56') and (C#) StringToBytes.C onvertHex("0F26 EF560F26EF56") but I'm really struggling to spot it.
Any help would be greatly appreciated!!
In PHP:
Code:
$td = mcrypt_module_open('des', '', 'cbc', '');
mcrypt_generic_init($td, pack("H*", '0F26EF560F26EF56'), pack("H*", '0F26EF560F26EF56'));
$encryptedText = base64_encode(mcrypt_generic($td, 'My Secret Text'));
echo "Encrypted=".$encryptedText;
Code:
Encrypted=HLp51qoFW0rimOTafCVTVQ==
In C#:
Code:
SymmetricAlgorithm objCryptoService = (SymmetricAlgorithm)new DESCryptoServiceProvider();
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, objCryptoService.CreateEncryptor(StringToBytes.ConvertHex("0F26EF560F26EF56"), StringToBytes.ConvertHex("0F26EF560F26EF56")), CryptoStreamMode.Write);
StreamWriter writer = new StreamWriter(cryptoStream);
writer.Write("My Secret Text");
writer.Flush();
cryptoStream.FlushFinalBlock();
writer.Flush();
Response.Write("Encrypted=" + Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length));
Public static class StringToBytes
{
public static byte[] ConvertHex(String sHexString)
{
int iCharCount = sHexString.Length;
byte[] oBytes = new byte[iCharCount / 2];
for (int i = 0; i < iCharCount; i += 2)
{
oBytes[i / 2] = Convert.ToByte(sHexString.Substring(i, 2), 16);
}
return oBytes;
}
}
Code:
Encrypted=HLp51qoFW0ojU8eGEGkk4w==
You can see that they are close...
PHP: HLp51qoFW0rimOT afCVTVQ==
C# : HLp51qoFW0ojU8e GEGkk4w==
But something is going wrong somewhere, I suspect it's a difference between (PHP) pack("H*", '0F26EF560F26EF 56') and (C#) StringToBytes.C onvertHex("0F26 EF560F26EF56") but I'm really struggling to spot it.
Any help would be greatly appreciated!!
Comment