I try to generate a RSA key with Web Crypto and use it to sign a string with jsrsasign (Firefox does not support RSA-PSS). Therefore, I export the Web Crypto key and convert it to PKCS8-PEM, but when I call KEYUTIL.getKeyFromPlainPrivatePKCS8PEM
to import the key to jsrsasign an error is thrown: malformed plain PKCS8 private key(code:001)
What did I wrong? JSBin
window.crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: {name: "SHA-256"},
},
true,
["encrypt", "decrypt"]
)
.then(keyPair => window.crypto.subtle.exportKey("pkcs8", keyPair.privateKey))
.then(arrayBufferToBase64String)
.then(toPem)
.then(pem => {
var rsa = KEYUTIL.getKeyFromPlainPrivatePKCS8PEM(pem); // throws: malformed plain PKCS8 private key(code:001)
var sig = rsa.signStringPSS('text', 'sha256', 32);
console.log('signature', sig);
})
.catch(::console.error)
function arrayBufferToString(arrayBuffer) {
var byteArray = new Uint8Array(arrayBuffer)
var byteString = '';
for (var i=0; i<byteArray.byteLength; i++) {
byteString += String.fromCharCode(byteArray[i]);
}
return byteString;
}
function arrayBufferToBase64String(arrayBuffer) {
return btoa(arrayBufferToString(arrayBuffer));
}
function toPem(key) {
return `
-----BEGIN RSA PRIVATE KEY-----
${key}
-----END RSA PRIVATE KEY-----
`;
}
Edit:
I just realized that jsrsasign can handle jwk:
window.crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: {name: "SHA-256"},
},
true,
["encrypt", "decrypt"]
)
.then(keyPair => window.crypto.subtle.exportKey("jwk", keyPair.privateKey))
.then(jwk => {
var rsa = KEYUTIL.getKey(jwk);
var sig = rsa.signStringPSS('text', 'sha256', 32);
console.log('signature', sig);
})
.catch(::console.error)
I prefer this solution, but I still like to know why my pkcs8 solution does not work.