I exported a CryptoKey to PEM style and now I want to import it back. I generated my keys using the following code:
function generate() {
return window.crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: {name: "SHA-256"},
},
true,
["encrypt", "decrypt"]
).then(function (key) {
return key;
})
.catch(function (err) {
console.error(err);
});
}
And I'm trying to import the private key which is string (pem style) using the next code:
function importPrivateKey(pemKey) {
return crypto.subtle.importKey("pkcs8", convertPemToBinary(pemKey), {name:"RSA-OAEP", hash:{name:"SHA-256"}}, true, ["encrypt", "decrypt"]);}
Unfortunately, it returns this error:
SyntaxError: Cannot create a key using the specified key usages.
UPDATE
convertPemToBinary function
function convertPemToBinary(pem) {
var lines = pem.split('\n');
var encoded = '';
for (var i = 0; i < lines.length; i++) {
if (lines[i].trim().length > 0 &&
lines[i].indexOf('-----BEGIN RSA PRIVATE KEY-----') < 0 &&
lines[i].indexOf('-----BEGIN RSA PUBLIC KEY-----') < 0 &&
lines[i].indexOf('-----BEGIN PUBLIC KEY-----') < 0 &&
lines[i].indexOf('-----END PUBLIC KEY-----') < 0 &&
lines[i].indexOf('-----BEGIN PRIVATE KEY-----') < 0 &&
lines[i].indexOf('-----END PRIVATE KEY-----') < 0 &&
lines[i].indexOf('-----END RSA PRIVATE KEY-----') < 0 &&
lines[i].indexOf('-----END RSA PUBLIC KEY-----') < 0) {
encoded += lines[i].trim();
}
}
return base64StringToArrayBuffer(encoded);
}
Sub Functions used in convertPemToBinary function:
function base64StringToArrayBuffer(b64str) {
b64str = b64EncodeUnicode(b64str);
var byteStr = atob(b64str);
var bytes = new Uint8Array(byteStr.length);
for (var i = 0; i < byteStr.length; i++) {
bytes[i] = byteStr.charCodeAt(i);
}
return bytes.buffer;
}
function b64EncodeUnicode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
You can not encrypt with a RSA-OAEP private key. The issue is probably due to you have set
encrypt
tag in key usage when importing.see webcrypto specification, section 22.4 https://w3c.github.io/webcrypto/Overview.html#rsa-oaep
UPDATED
The function
base64StringToArrayBuffer
is not correctPEM is base64 encoded, the function
b64EncodeUnicode
is encoding the content twice.See my answer here https://stackoverflow.com/a/38714970/6371459 that contains a full example to generate RSA-OAEP key, export, encode to PEM, decode and import again (note: without using headers)
Replace these two lines with