我正在尝试使用SubtleCrypto加密 webextension 中的某些内容,并使用cryptography对其进行解密。我想使用密码来加密消息,将其发送到应用程序并使用相同的密码对其进行解密。为此,我使用 AES GCM 和 pbkdf2
我能够在 Mozilla 文档页面上找到一个加密片段。但是,我很难在颤抖中解密它。
我也有术语问题。SubtleCrypto 使用 iv、salt 和标签,而 Flutter 加密使用 nonce 和 mac。
Javascript代码:
test(){
// const salt = window.crypto.getRandomValues(new Uint8Array(16));
// const iv = window.crypto.getRandomValues(new Uint8Array(12));
const salt = new Uint8Array([0, 72, 16, 170, 232, 145, 179, 47, 241, 92, 75, 146, 25, 0, 193, 176]);
const iv = new Uint8Array([198, 0, 92, 253, 0, 245, 140, 79, 236, 215, 255, 0]);
console.log('salt: ', salt);
console.log('iv: ', iv);
console.log('salt: ', btoa(String.fromCharCode(...salt)));
console.log('iv: ', btoa(String.fromCharCode(...iv)));
this.encrypt('value', salt, iv).then(x => console.log('got encrypted: ', x));
}
getKeyMaterial(): Promise<CryptoKey> {
const password = 'key';
const enc = new TextEncoder();
return window.crypto.subtle.importKey(
'raw',
enc.encode(password),
'PBKDF2',
false,
['deriveBits', 'deriveKey']
);
}
async encrypt(plaintext: string, salt: Uint8Array, iv: Uint8Array): Promise<string> {
const keyMaterial = await this.getKeyMaterial();
const key = await window.crypto.subtle.deriveKey(
{
name: 'PBKDF2',
salt,
iterations: 100000,
hash: 'SHA-256'
},
keyMaterial,
{ name: 'AES-GCM', length: 256},
true,
[ 'encrypt', 'decrypt' ]
);
const encoder = new TextEncoder();
const tes = await window.crypto.subtle.encrypt(
{
name: 'AES-GCM',
iv
},
key,
encoder.encode(plaintext)
);
return btoa(String.fromCharCode(...new Uint8Array(tes)));
}
飞镖代码:
void decrypt(){
final algorithm = AesGcm.with256bits();
final encrypted = base64Decode('1MdEsqwqh4bUTlfpIk12SeziA9Pw');
final secretBox = SecretBox.fromConcatenation(encrypted, nonceLength: 12, macLength: 0);
// // Encrypt
final data = await algorithm.decrypt(
secretBox,
secretKey: await getKey(),
);
String res = utf8.decode(data);
}
Future<SecretKey> getKey() async{
final pbkdf2 = Pbkdf2(
macAlgorithm: Hmac.sha256(),
iterations: 100000,
bits: 128,
);
// Password we want to hash
final secretKey = SecretKey(utf8.encode('key'));
// A random salt
final salt = [0, 72, 16, 170, 232, 145, 179, 47, 241, 92, 75, 146, 25, 0, 193, 176];
// Calculate a hash that can be stored in the database
final newSecretKey = await pbkdf2.deriveKey(
secretKey: secretKey,
nonce: salt,
);
return Future<SecretKey>.value(newSecretKey);
}
我究竟做错了什么?