我想使用 C# 加密数据并使用 JS 解密它。
该表表明 AES-GCM 是使用 WebCryptoApi https://diafygi.github.io/webcrypto-examples/的方式。
我成功地使用 BouncyCastle https://codereview.stackexchange.com/questions/14892/simplified-secure-encryption-of-a-string在.NET 中加密(和解密)。
var message = "This is the test message";
var key = AESGCM.NewKey();
Console.Out.WriteLine("KEY:" + Convert.ToBase64String(key));
>> KEY:5tgX6AOHot1T9SrImyILIendQXwfdjfOSRAVfMs0ed4=
string encrypted = AESGCM.SimpleEncrypt(message, key);
Console.Out.WriteLine("ENCRYPTED:" + encrypted);
>> ENCRYPTED:Ct0/VbOVsyp/LMxaaFqKKw91+ts+8uzDdHLrTG1XVjPNL7KiBGYB4kfdNGl+xj4fYqdb4JXgdTk=
var decrypted = AESGCM.SimpleDecrypt(encrypted, key);
Console.Out.WriteLine("DECRYPTED:" + decrypted);
>> DECRYPTED:This is the test message
但是,我不知道如何解密这个客户端。在https://github.com/diafygi/webcrypto-examples#aes-cbc---decrypt上有很多 WebCryptoApi 示例,包括 AES-GCM 。
第一步(似乎可行)是导入密钥,我将其作为 base-64 编码字符串:
var keyString = "+6yDdIiJJl8Lqt60VOHuP25p4yNxz0CRMoE/WKA+Mqo=";
function _base64ToArrayBuffer(base64) {
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array( len );
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
var key = _base64ToArrayBuffer(keyString )
var cryptoKey; // we'll get this out in the promise below
window.crypto.subtle.importKey(
"raw",
key,
{ //this is the algorithm options
name: "AES-GCM",
},
true, // whether the key is extractable
["encrypt", "decrypt"] // usages
)
.then(function(key){
//returns the symmetric key
console.log(key);
cryptoKey = key;
})
.catch(function(err){
console.error(err);
});
最后一步应该是解密编码的消息,这也是一个base-64编码的字符串
var encryptedString = "adHb4UhM93uWyRIV6L1SrYFbxEpIbj3sQW8VwJDP7v+XoxGi6fjmucEEItP1kQWxisZp3qhoAhQ=";
var encryptedArrayBuffer = _base64ToArrayBuffer(encryptedString)
window.crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: new ArrayBuffer(12), //The initialization vector you used to encrypt
//additionalData: ArrayBuffer, //The addtionalData you used to encrypt (if any)
// tagLength: 128, //The tagLength you used to encrypt (if any)
},
cryptoKey, //from above
encryptedArrayBuffer //ArrayBuffer of the data
)
.then(function(decrypted){
//returns an ArrayBuffer containing the decrypted data
console.log(new Uint8Array(decrypted));
})
.catch(function(err){
debugger; console.error(err);
});
不幸的是,这是一个 DomError。
我不知道在解密方法中我应该为“iv”使用什么。我试过空,ArrayBuffer(0),ArrayBuffer(12)。这几乎是我的理解结束的地方。