[英]MCRYPT in .Net
我在一端使用PHP解密算法,在另一端使用.Net加密算法。 我在PHP代碼中使用mcrypt_decrypt
進行解密,並在.Net中尋找與mcrypt_encrypt
等效的mcrypt_encrypt
。 更具體地說,我要轉換為.Net的PHP代碼如下:
$cipher_alg = MCRYPT_RIJNDAEL_128;
$iv = mcrypt_create_iv ( mcrypt_get_iv_size ( $cipher_alg, MCRYPT_MODE_ECB ), MCRYPT_RAND );
$encrypted_string = mcrypt_encrypt ( $cipher_alg, $sessionkey, $string, MCRYPT_MODE_CBC, $iv );
$hex_encrypted_string = bin2hex ( $encrypted_string );
.net中是否有等效於mcrypt_encrypt
的文件?
這是節選:
private static string CreateEncryptedString(string myString, string hexiv, string key)
{
RijndaelManaged alg = new RijndaelManaged();
alg.Padding = PaddingMode.Zeros;
alg.Mode = CipherMode.CBC;
alg.BlockSize = 16 * 8;
alg.Key = ASCIIEncoding.UTF8.GetBytes(key);
alg.IV = StringToByteArray(hexiv);
ICryptoTransform encryptor = alg.CreateEncryptor(alg.Key, alg.IV);
MemoryStream msStream = new MemoryStream();
CryptoStream mCSWriter = new CryptoStream(msStream, encryptor, CryptoStreamMode.Write);
StreamWriter mSWriter = new StreamWriter(mCSWriter);
mSWriter.Write(myString);
mSWriter.Flush();
mCSWriter.FlushFinalBlock();
var EncryptedByte = new byte[msStream.Length];
msStream.Position = 0;
msStream.Read(EncryptedByte, 0, (int)msStream.Length);
return ByteArrayToHexString(EncryptedByte);
}
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
public static string ByteArrayToHexString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
有一件事情要注意。 密鑰大小必須為16。這意味着密鑰參數必須為16個字符的字符串。 否則,加密將無法正常工作,並會引發CryptographicException。
在PHP端,這是解碼的方法:
$cipher_alg = MCRYPT_RIJNDAEL_128;
$decrypted_string = mcrypt_decrypt($cipher_alg, $key,
$encrypted_string , MCRYPT_MODE_CBC, trim(hex2bin(trim($hexiv))));
沒有直接的等效項,但支持128位Rijndael(可能還需要大多數其他密碼)。 有關詳細信息和示例,請參見Rijndael類。
基本上,框架的加密部分基於您指定基類的適當實例( CryptoStream
, SymmetricAlgorithm
等),而不是通過名稱指定密碼-但是您應該能夠執行所需的操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.