I’m trying to import a private key to sign an XML file in NodeJS.
To sign the XML, I’m using xmldsigjs which requires the key to be passed in a CryptoKey
object that is obtained by crypto.subtle.importKey
.
In my understanding importKey
takes the key in the DER format.
I have generated a key and certificate using the following command:
openssl req -newkey rsa-pss -new -nodes -x509 -days 3650 -pkeyopt rsa_keygen_bits:4096 -sigopt rsa_pss_saltlen:32 -keyout key.pem -out cert.pem
This creates a pkcs8 formatted private key. When using any private keys generated by this command, i receive this error DataError: Invalid key type
.
This is the code used to import the key.
const privateKey = await fs.readFile(path.join(__dirname, 'certificates', 'key.pem'), 'utf-8');
const pemHeader = '-----BEGIN PRIVATE KEY-----';
const pemFooter = '-----END PRIVATE KEY-----';
const pemContents = privateKey.substring(pemHeader.length, privateKey.length - pemFooter.length - 1);
const key = await crypto.subtle.importKey(
'pkcs8',
Buffer.from(pemContents, 'base64'),
{ name: 'RSA-PSS', hash: { name: 'SHA-256' } },
false,
['sign'],
);
When using another key that I created using an online tool here, the key import works perfectly.
The command to generate they keys was provided by an API specifications document.
Could it be that I’m generating the key in a wrong way?