C# PHP mcrypt_加密到.NET
我几乎失去了我的头发,思想和其他一切!我一直在尝试将此PHP函数转换为C#: 我一直在Rijandel班级工作:C# PHP mcrypt_加密到.NET,c#,php,rijndaelmanaged,C#,Php,Rijndaelmanaged,我几乎失去了我的头发,思想和其他一切!我一直在尝试将此PHP函数转换为C#: 我一直在Rijandel班级工作: function encrypt_decrypt(string password) { UTF8Encoding encoding = new UTF8Encoding(); // For consistency with PHP function, MD5Encrypt applies MD5 encryption and does a bin2hex byte[]
function encrypt_decrypt(string password) {
UTF8Encoding encoding = new UTF8Encoding();
// For consistency with PHP function, MD5Encrypt applies MD5 encryption and does a bin2hex
byte[] Key = Encoding.ASCII.GetBytes(MD5Encrypt(password).ToLower());
byte[] IV = Encoding.ASCII.GetBytes(MD5Encrypt(MD5Encrypt(password).ToLower()).ToLower());
RijndaelManaged rj = new RijndaelManaged();
rj.BlockSize = 256;
rj.KeySize = 256;
rj.Key = Key;
rj.IV = IV;
rj.Mode = CipherMode.CBC;
MemoryStream ms = new MemoryStream();
using (CryptoStream cs = new CryptoStream(ms, rj.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(message);
sw.Close();
}
cs.Close();
}
byte[] encoded = ms.ToArray();
string output = "";
foreach (var ele in encoded)
{
output += ele.ToString("X2");
}
return output;
}
我一直在验证PHP代码的输出与C#代码的输出,但它们不匹配。(). 任何反馈都将不胜感激。在执行此操作时,需要记住多个问题,如转换二进制文件、检查编码和填充问题。由于我们无法看到您的完整代码,因此在这种情况下我们无能为力。查看本教程了解更多信息:请尝试以下方法:
using (RijndaelManaged myRijndael = new RijndaelManaged())
{
myRijndael.Key = Encoding.UTF8.GetBytes(password);
string strIv16 = "\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0";
myRijndael.IV = Encoding.UTF8.GetBytes(strIv16);
// Encrypt the string to an array of bytes.
byte[] encrypted = EncryptStringToBytes(message, myRijndael.Key, myRijndael.IV);
string output = Convert.ToBase64String(encrypted);
}
这真的是一个重复的为您加密的密钥和文本匹配,请匹配字节[]密钥和字节[]IV。正如md5在两者上生成的结果不同一样。我也遇到了同样的问题。这是老问题,但我遇到了类似的问题。首先要检查的是编码。我认为PHP版本使用UTF8,而您使用的是ASCII。如果编码与您的不匹配,则获取不同的字节和内容将无法工作
using (RijndaelManaged myRijndael = new RijndaelManaged())
{
myRijndael.Key = Encoding.UTF8.GetBytes(password);
string strIv16 = "\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0";
myRijndael.IV = Encoding.UTF8.GetBytes(strIv16);
// Encrypt the string to an array of bytes.
byte[] encrypted = EncryptStringToBytes(message, myRijndael.Key, myRijndael.IV);
string output = Convert.ToBase64String(encrypted);
}