Tech
Forums
Jobs
Books
Events
Videos
Live
More
Interviews
Certification
Training
Career
Members
News
Blogs
Contribute
An Article
A Blog
A Video
An Ebook
An Interview Question
Register
Login
2
Answers
DES encryption (c#) and mcrypt (php)
Keith
8y
6.1k
1
Reply
I have a problem trying to encrypt a string in C# and also in PHP using DES (cbc) encryption. The problem I'm facing is that I'm getting different results using the different languages.
In C#:
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;
}
}
Results
Encrypted=HLp51qoFW0ojU8eGEGkk4w==
In PHP:
$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;
Results
Encrypted=HLp51qoFW0rimOTafCVTVQ==
You can see that they are close...
PHP: HLp51qoFW0rimOTafCVTVQ==
C# : HLp51qoFW0ojU8eGEGkk4w==
But something is going wrong somewhere, I suspect it's a difference between (PHP) pack("H*", '0F26EF560F26EF56') and (C#) StringToBytes.ConvertHex("0F26EF560F26EF56") but I'm really struggling to spot it.
Any help would be greatly appreciated!!
Post
Reset
Cancel
Answers (
2
)
Next Recommended Forum
SOAP missing HEADER
Which Encryption Method?