【发布时间】:2018-02-03 09:55:24
【问题描述】:
在 Unity android 构建中使用 AES 解密字符串时出现空引用异常。它是一些 HMAC 初始化错误。
我使用 system.cryptorgraphy 的 AES 加密和解密算法在我的游戏中使用加密,但我在 Android 设备上遇到错误。有谁知道 HMAC Initialise() 是什么以及如何解决这个错误?我已经粘贴了我用来解密的代码。
错误的屏幕截图全部附在下面。
public string Decrypt (string cipherText)
{
string EncryptionKey = "abc123";
cipherText = cipherText.Replace (" ", "+");
byte[] cipherBytes = Convert.FromBase64String (cipherText);
using (Aes encryptor = Aes.Create ()) {
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes (EncryptionKey, new byte[] {
0x49,
0x76,
0x61,
0x6e,
0x20,
0x4d,
0x65,
0x64,
0x76,
0x65,
0x64,
0x65,
0x76
});
encryptor.Key = pdb.GetBytes (32);
encryptor.IV = pdb.GetBytes (16);
using (MemoryStream ms = new MemoryStream ()) {
using (CryptoStream cs = new CryptoStream (ms, encryptor.CreateDecryptor (), CryptoStreamMode.Write)) {
cs.Write (cipherBytes, 0, cipherBytes.Length);
cs.Close ();
}
cipherText = Encoding.Unicode.GetString (ms.ToArray ());
}
}
return cipherText;
}
我对 Stackoverflow 很陌生,我尝试查找重复项但失败了。如果您认为问题重复,请提供链接。
【问题讨论】:
-
我建议您阅读 how to ask perfect question 和 how to create Minimal, Complete and Verifable example 然后快速相应地编辑您的问题,以免被否决和埋葬。
-
感谢您的建议,通过它。
-
HMAC 用于 within Rfc2898DeriveBytes 从给定密码(和盐)生成密钥。这并不能解释为什么它没有被初始化。它也没有解释为什么先调用哈希然后调用 HMAC。我能给你的唯一想法是,还有一个构造函数,它还需要一个迭代计数(静态盐值后面的一个整数,比如设置为 40,000 左右)。请注意,静态盐几乎是无用的。
-
我得到了解决方案。我得到空 ref 是因为使用 HMAC .Net2.0 使用反射,当我进行构建时,我使用的是 .Net 2.0 子集,并且我正在剥离使用密码学所需的所有代码。感谢@MaartenBodewes 的评论
标签: c# android unity3d encryption cryptography