Looking at my code:
var keyData = `-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----`;
var ciphertext = '...';
// based on the reference from https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#PKCS_8_import
function str2ab(str) {
const buf = new ArrayBuffer(str.length);
const bufView = new Uint8Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
keyData = keyData
.replace(/-+[^-]+-+/g, '')
.replace("\n", '')
.replace("\r", '');
keyData = str2ab(window.atob(keyData));
window.crypto.subtle.importKey(
'pkcs8',
keyData,
{name: 'RSA-OAEP'},
true,
'decrypt'
).then(function(privateKey) {
alert('this far');
window.crypto.subtle.decrypt(
{
name: "RSA-OAEP"
},
privateKey,
ciphertext
).then(function(plaintext) {
alert(plaintext);
})
});
See it live on JSFiddle (including complete private key and ciphertext):
https://jsfiddle.net/akcq65o7/1/
In line with the documentation, window.crypto.subtle.importKey
utilizes a Promise, hence the need for then()
. However, the line alert('this far');
doesn't seem to be executing. No errors are appearing in the JS console either.
Any suggestions?