我在一端使用PHP解密算法,在另一端使用.Net加密算法。我在PHP代码中使用mcrypt_decrypt进行解密,并在.Net中寻找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的等价物?
发布于 2009-06-24 16:08:17
我已经和a solution in my blog出来了。
以下是摘录:
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))));发布于 2009-06-24 09:18:53
没有直接的等价物,但支持128位Rijndael (可能还有您想要的大多数其他密码)。有关详细信息和示例,请参阅Rijndael类。
基本上,框架的加密部分是基于您指定基类(CryptoStream、SymmetricAlgorithm等)的适当实例,而不是通过名称指定密码-但您应该能够执行所需的操作。
https://stackoverflow.com/questions/1037250
复制相似问题