【发布时间】:2021-06-30 09:05:32
【问题描述】:
我正在尝试使用SubtleCrypto 加密字符串、存储加密字符串并再次解密该字符串,所有这些都使用生成的 RSA-OAEP 密钥对。
以下代码在解密阶段会产生 DOMException,但我似乎无法获得有关该错误的任何详细信息。我尝试使用“SHA-1”进行散列,但有同样的问题。
有什么提示吗?
let encoder = new TextEncoder();
let decoder = new TextDecoder('utf-8');
// Generate a key pair
let keyPair = await window.crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 4096,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256"
},
true,
["encrypt", "decrypt"]
);
let publicKey = await crypto.subtle.exportKey('jwk', keyPair.publicKey);
let privateKey = await crypto.subtle.exportKey('jwk', keyPair.privateKey);
// Encrypt a string
let encodedSecret = encoder.encode("MYSECRETVALUE");
let pubcryptokey = await window.crypto.subtle.importKey(
'jwk',
publicKey,
{
name: "RSA-OAEP",
hash: "SHA-256"
},
false,
["encrypt"]
);
let encrypted = await window.crypto.subtle.encrypt(
{
name: "RSA-OAEP"
},
pubcryptokey,
encodedSecret
);
let encDV = new DataView(encrypted);
let ct = decoder.decode(encDV);
// Decrypt the string
let encodedCiphertext = encoder.encode(ct);
let privcryptokey = await window.crypto.subtle.importKey(
'jwk',
privateKey,
{
name: "RSA-OAEP",
hash: "SHA-256"
},
false,
["decrypt"]
);
console.log("Before decrypt");
let decrypted = await window.crypto.subtle.decrypt(
{
name: "RSA-OAEP"
},
privcryptokey,
encodedCiphertext
);
console.log("After decrypt");
let decDV = new DataView(decrypted);
let pt = decoder.decode(decDV);
console.log(pt);
【问题讨论】:
-
对于现代加密算法,例如 WebCrypto 中的加密算法,无论是 RSA 还是对称,密文是二进制,因此尝试将其解码为 UTF8 然后再次对其进行编码会改变其中的大部分变成垃圾,对于现代加密货币来说,即使是一点点改变也会破坏你的数据。不要那样做。如果您无法按原样存储或处理它,
UInt8Array,并且需要一个字符串,请使用保留二进制的数据编码(不是字符编码)之一,如 base64 或十六进制。此外,由于它不包含大于字节的元素,DataView是无用且不必要的。
标签: encryption cryptography rsa subtlecrypto