javascript – 使用Microsoft Edge的Web加密API(38.14393.0.0)
作者:互联网
我在Chrome上成功使用Web Crypto API(https://www.w3.org/TR/WebCryptoAPI/)(自第一次Web Crypto支持以来),Firefox(自第一次Web Crypto支持以来),甚至在Safari TP(10.2)上使用WebCrypto Liner支持WebCrypto API的pollyfill(https://github.com/PeculiarVentures/webcrypto-liner) ).
现在我想使用Microsoft Edge测试我们的代码.但加密和解密示例ArrayBuffer已经失败.这里的代码:
var crypto = window.crypto;
if (crypto.subtle) {
var aesGcmKey = null;
// always create a new, random iv in production systems!!!
var tempIv = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
// needed for edge, if additional data missing decrypting is failing
var tempAdditionalData = new Uint8Array(0);
var dataToEncrypt = new Uint8Array([1, 2, 3, 4, 5]);
// 1.) generate key
var generateKeyPromise = crypto.subtle.generateKey(
{name: "AES-GCM", length: 256}, true, ["encrypt", "decrypt"]
);
generateKeyPromise.then(function (tempKey) {
aesGcmKey = tempKey;
// 2.) start encryption with this key
var encryptedDataPromise = crypto.subtle.encrypt(
{name: "AES-GCM", iv: tempIv, additionalData: tempAdditionalData, tagLength: 128},
aesGcmKey,
dataToEncrypt
);
encryptedDataPromise.then(function (encryptedData) {
// 3.) decrypt using same key
var decryptedDataPromise = crypto.subtle.decrypt(
{name: "AES-GCM", iv: tempIv, additionalData: tempAdditionalData, tagLength: 128},
aesGcmKey,
encryptedData
);
decryptedDataPromise.then(function (decryptedData) {
// 4.) compare decrypted array buffer and inital data
console.log('data decrypted!');
console.log(decryptedData);
});
decryptedDataPromise.catch(function (error) {
console.log('decrypting sample data failed');
console.log(error);
});
});
// if 2.) is failing
encryptedDataPromise.catch(function (error) {
console.log('encrypting sample data failed');
console.log(error);
});
});
// if 1.) is failing
generateKeyPromise.catch(function (error) {
console.log('creating aec gcm key failed');
console.log(error);
});
}
此代码在Edge的解密阶段(代码中的第3步)失败,而它在Chrome,Firefox甚至Safari上运行良好.有线部分,decryptedDataPromise被拒绝但有异常,但返回的数据根本不像一个例外:
[object Object] {additionalData: Uint8Array {...}, iv: Uint8Array {...}, name: "AES-GCM", tagLength: 128}
有没有人知道为什么在Microsoft Edge上失败?
解决方法:
正如评论中所建议的那样,将IV更改为大小12而不是16,将其他数据更改为1而不是0来修复Edge中的问题
var tempIv = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
var tempAdditionalData = new Uint8Array(1);
您对其他数据的评论“//边缘需要,如果缺少解密的其他数据失败”,则确实不需要. additionalData可以是无效的
我在MSDN中查找了大约encrypt的操作,但是没有记录这种行为.所以我认为WebCrypto的实现还不够成熟,但仍存在小错误
标签:javascript,encryption,promise,microsoft-edge,webcryptoapi 来源: https://codeday.me/bug/20190627/1307906.html