无法使用PHP(Rijdael-128)加密的C#解密数据

时间:2010-02-11 16:03:51

标签: c# php encryption rijndael

我使用PHP使用以下代码解密数据:

$content="1234";
$cp = mcrypt_module_open('rijndael-128', '', 'cbc', '');
$iv = mcrypt_create_iv(16, MCRYPT_RAND);
$key = pack("H*",md5('a'));
mcrypt_generic_init($cp, $key, $iv);
$encrypted = mcrypt_generic($cp, $content);
echo base64_encode($key)."\n";
echo base64_encode($iv)."\n";
echo base64_encode($encrypted)."\n";
mcrypt_generic_deinit($cp);
mcrypt_module_close($cp);
然后将 $ iv和$ encrypted保存到文件中并在C#示例应用程序中读取:

var iv=...;
var encrypted=...;
var md5 = new MD5CryptoServiceProvider();
var key = md5.ComputeHash(Encoding.Default.GetBytes("a"));
md5.Clear();

Console.WriteLine(Convert.ToBase64String(key));
Console.WriteLine(Convert.ToBase64String(iv));
Console.WriteLine(Convert.ToBase64String(encrypted));

这里的输出与PHP的输出完全相同,所以我可以保证中间没有编码错误。

var rd = new RijndaelManaged {
  Key = key,
  IV = iv,
  Mode = CipherMode.CBC,
  KeySize = 128,
  Padding = PaddingMode.Zeros
};

var buffer = new byte[encrypted.Length];
using(var ms = new MemoryStream(buffer)) {
  using(var cs = new CryptoStream(ms, rd.CreateDecryptor(), CryptoStreamMode.Write)) {
    cs.Write(encrypted, 0, encrypted.Length);
    ms.Read(buffer, 0, buffer.Length);
    Console.WriteLine(Encoding.Default.GetString(buffer));
  } 
}
rd.Clear();

解密结果在每个程序启动时都会有所不同,即使输入数据完全相同:

首先运行:
DMF1ucDxtqgxw5niaXcmYQ ==< -Key
GoCeRkrL / EMKNH / BYeLsqQ ==< -IV
UBE3DkgbJgj1K / TISugLxA ==< -Encrypted
OlOB99yiCYRDoLx + 0xxZxQ ==< - “Decrypted”

第二轮:
DMF1ucDxtqgxw5niaXcmYQ ==< -Key
GoCeRkrL / EMKNH / BYeLsqQ ==< -IV
UBE3DkgbJgj1K / TISugLxA ==< -Encrypted
w5fcY5Fbb9KRgoHfhqAztA ==< - “Decrypted”

密钥,IV,加密数据是相同的,但解密日期仍然不一样,并且总是错误的。缓冲区应包含“1234”或“1234”加上12个尾随零。

我不明白为什么结果会有所不同,哪些不起作用,但我现在已经盯着这段代码几个小时了,可能会错过明显的错误......

像这样反转CryptoStream会产生完全错误的结果:

using(var ms = new MemoryStream(encrypted)) {
  using(var cs = new CryptoStream(ms, rd.CreateDecryptor(), CryptoStreamMode.Read)) {
    cs.Read(buffer, 0, buffer.Length);
    Console.WriteLine(Convert.ToBase64String(buffer));
  }
}

帮助? 谢谢! 亚历山大

1 个答案:

答案 0 :(得分:5)

好吧,修改过去我的罪过的旧样本我最终得到了这个:

static string Decrypt() {            
  byte[] keyBytes = Convert.FromBase64String("DMF1ucDxtqgxw5niaXcmYQ==");
  byte[] iv = Convert.FromBase64String("GoCeRkrL/EMKNH/BYeLsqQ==");
  byte[] cipherTextBytes = Convert.FromBase64String("UBE3DkgbJgj1K/TISugLxA==");

  var symmetricKey = new RijndaelManaged { Mode = CipherMode.CBC, IV = iv, KeySize = 128, Key = keyBytes, Padding = PaddingMode.Zeros};

  using (var decryptor = symmetricKey.CreateDecryptor())
  using (var ms = new MemoryStream(cipherTextBytes))
  using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) {
    var plainTextBytes = new byte[cipherTextBytes.Length];
    int decryptedByteCount = cs.Read(plainTextBytes, 0, plainTextBytes.Length);
    return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
  }
}

给了“1234”尾随\ 0字符..你是否忘记将字节[]再次转换为字符串?我还缺少其他什么区别?