我必须加密一些私有字段,并且发现(jbtule’s)类using AESGCM.
当我只是加密和解密时,它可以正常工作:
string nonSecretPayload = "asda23432a3@!$#@#%a";
string encryptThisStr = "CakeCat";
string key = "12345678912365478912365478965412";
var encryptAESGCM = AESGCM.SimpleEncrypt(Encoding.UTF8.GetBytes(encryptThisStr), Encoding.UTF8.GetBytes(key), Encoding.UTF8.GetBytes(nonSecretPayload));
//addedJson += "c" + count + "{\"" + @Encoding.UTF8.GetString(encryptAESGCM) + "\"}";
var decrypyAESGCM2 = AESGCM.SimpleDecrypt(encryptAESGCM , Encoding.UTF8.GetBytes(key), Encoding.UTF8.GetBytes(salt).Length);
但是,当我将cryptoAESGCM byte []作为字符串保存在json文件中,然后在对它执行Encoding.UTF8.GetBytes()之后对该字符串进行解密时,它将失败,并显示:
Org.BouncyCastle.Crypto.InvalidCipherTextException: mac check in GCM failed
at Org.BouncyCastle.Crypto.Modes.GcmBlockCipher.DoFinal(Byte[] output, Int32
outOff) in C:\BouncyCastle\crypto\src\crypto\modes\GCMBlockCipher.cs:line 295
at Encryption.AESGCM.SimpleDecrypt(Byte[] encryptedMessage, Byte[] key, I
nt32 nonSecretPayloadLength)
我看到它使用MAC来检查密文是否未被篡改.我要做的就是使用Encoding.UTF8.GetString(encryptAESGCM)将加密结果(byte [])作为字符串添加到json字符串中,然后将其保存到Couchbase.当我找回它时,我Encoding.UTF8.GetBytes(encryptAESGCM)存储的字符串,然后尝试对其进行解密.这会影响Mac吗?有没有解决的办法?还有其他问题吗?
解决方法:
您不能将Encoding.UTF8.GetString应用于任意二进制数据.它只能解码使用UTF-8编码字符串的结果字节. .net实现将以静默方式破坏数据,而不是默认情况下引发异常.
您应该改用Base64:Convert.FromBase64String
和Convert.ToBase64String