I am facing a weird problem with WebCrypto Subtle. If I do the encryption and decryption in the same browser tab, it works perfectly. But, If I try to decrypt a ciphertext which was encrypted somewhere else, it just throws DOMException: The operation failed for an operation-specific reason
I am using this piece of code:
//encrypt
window.crypto.subtle.importKey(
"jwk",
key,
{
name: "RSA-OAEP",
hash: "SHA-256",
},
true,
['encrypt']
)
.then(pkey => {
const iv = window.crypto.getRandomValues(new Uint8Array(16))
window.crypto.subtle.encrypt(
{
name: "RSA-OAEP",
hash: "SHA-256",
iv
},
pkey,
new TextEncoder().encode('hello world')
).then(encrypted => {
str = ab2str(encrypted) //special function to convert it to string
})
})
//decrypt
window.crypto.subtle.importKey(
"jwk",
privateKey,
{
name: "RSA-OAEP",
hash: "SHA-256"
},
true,
['decrypt']
)
.then(prkey => {
window.crypto.subtle.decrypt(
{
name: "RSA-OAEP",
hash: "SHA-256",
iv: new TextEncoder().encode(msg.data.iv)
},
prkey,
str2ab(msg.data.message) //special function convert it to ArrayBuffer
)
.then(t => console.log(new TextDecoder().decode(t)))
.catch(console.log)
})
//Helper functions
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
function str2ab(str) {
var buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
I have tried both with and without the Initialization vector. But nothing works. Could not find any information in google as well. Can someone please solve this issue?