在网络上尝试了很多例子,但我在C#中得不到与PHP相同的结果。
我有一个C#Web服务,它将接收我需要解密的加密字符串。该字符串已使用类似下面的代码在PHP中加密。当输入字符串为“1234”时,此PHP代码将输出“eGtLMUc5cXdEblY2dHhDVUhjcm56Zz09”。然后我尝试用C#解密它,但无法做到这一点,尝试了我能找到的每个例子,但我的输出总是不同于“1234”(大多数情况下只是一堆随机字母/数字)。
输入:1234
输出:eGtLMUc5cXdEblY2dHhDVUhjcm56Zz09
<?php
$secret_key = 'verySecretKey';
$secret_iv = 'secret_iv_string';
$key = hash('sha256', $secret_key);
$iv = substr(md5(md5($secret_iv)), 0, 16);
$method = 'AES-256-CBC';
$inputString = '1234';
$encrypted = openssl_encrypt($inputString, $method, $key,FALSE,$iv);
echo base64_encode($encrypted);
?>
我可以使用下面的代码在PHP中解密它。
输入:eGtLMUc5cXdEblY2dHhDVUhjcm56Zz09
输出:1234
<?php
$encryptedString = 'eGtLMUc5cXdEblY2dHhDVUhjcm56Zz09';
$encrypt_method = 'AES-256-CBC';
$secret_key = 'verySecretKey';
$secret_iv = 'secret_iv_string';
$key = hash('sha256', $secret_key);
$iv = substr(md5(md5($secret_iv)), 0, 16);
$plain_password = openssl_decrypt(base64_decode($encryptedString), $encrypt_method, $key, FALSE, $iv);
echo $plain_password;
?>
任何人都知道如何在C#中获得相同的结果?
我在C#中的代码,我希望生成与PHP相同的代码。
输入:1234
加密:HNEm25Nuqj4mWvkXPWL / Ww ==
private static void tester()
{
RijndaelManaged AesEncryption = new RijndaelManaged();
string plainStr = "1234"; // The text that would be encrypted
AesEncryption.KeySize = 256;
AesEncryption.BlockSize = 128;
AesEncryption.Mode = CipherMode.CBC;
AesEncryption.Padding = PaddingMode.Zeros;
string keyStr = "verySecretKey";
string ivStr = "secret_iv_string";
AesEncryption.Key = GetSHA256HashBytes(keyStr);
AesEncryption.IV = ASCIIEncoding.UTF8.GetBytes(GetMD5Hash(GetMD5Hash(ivStr)).Substring(0, 16));
byte[] plainText = Convert.FromBase64String(plainStr);
ICryptoTransform crypto = AesEncryption.CreateEncryptor();
ICryptoTransform decrypto = AesEncryption.CreateDecryptor();
byte[] cipherText = crypto.TransformFinalBlock(plainText, 0, plainText.Length);
byte[] decryptedText = decrypto.TransformFinalBlock(cipherText, 0, cipherText.Length);
Console.Write("The plain text\"{0}\" in the encrypted format is:{1} \n", plainStr, Convert.ToBase64String(cipherText));
Console.Write("The encrypted text \"{0}\" is decrypted to: {1}", Convert.ToBase64String(cipherText), Convert.ToBase64String(decryptedText));
Console.Read();
}
private static byte[] GetSHA256HashBytes(string input)
{
System.Security.Cryptography.SHA256CryptoServiceProvider x = new System.Security.Cryptography.SHA256CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);
bs = x.ComputeHash(bs);
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (byte b in bs)
{
s.Append(b.ToString("x2").ToLower());
}
return bs;
}
private static string GetMD5Hash(string input)
{
System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);
bs = x.ComputeHash(bs);
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (byte b in bs)
{
s.Append(b.ToString("x2").ToLower());
}
return s.ToString();
}