unable to create signature using cryto in nodejs

Viewed 729

I am trying to create a signature using RSA-SHA25 algorithm. This is the code bellow

const data = "My data";    
const sign = crypto.createSign("RSA-SHA256");
sign.update(Buffer.from(data, "utf8"));
signature = sign
  .sign({ key: privateKey, padding: crypto.constants.RSA_PKCS1_PSS_PADDING })
  .toString("base64");

The problem is I am getting this error. I searched through out the internet but unable to find the right solution.

internal/crypto/sig.js:105 const ret = this[kHandle].sign(data, format, type, passphrase, rsaPadding, ^

Error: error:0909006C:PEM routines:get_name:no start line

1 Answers

In the posted NodeJS code the key is passed as an object, so in general the properties key, format and type must be used for the key description, which is explained in detail in the documentation of sign.sign(privateKey[, outputEncoding]) and crypto.createPrivateKey(key).

Hereby key contains the key material, format specifies the encoding ('pem' or 'der', where 'pem' is the default) and type the type (for RSA this can be 'pkcs1' or 'pkcs8', where this parameter is only required if format is equal to 'der').

If these properties are inconsistent, generally an error will occur.

For example, in the case of the posted code, format is not explicitly specified, so the default 'pem' is used. If the key privateKey is a DER encoded key (in a buffer), there is an inconsistency which leads to the error message Error: error:0909006C:PEM routines:get_name:no start line: Because of the implicitly specified format 'pem', a PEM encoded key is expected with the respective header, which is missing for a DER encoded key, resulting in the error. The solution is to explicitly specify format and type, e.g.:

{ key: privateKey, format: 'der', type: 'pkcs8', padding: crypto.constants.RSA_PKCS1_PSS_PADDING }

for a PKCS#8 key (or 'pkcs1' for a PKCS#1 key).

Conversely, for

{ key: privateKey, padding: crypto.constants.RSA_PKCS1_PSS_PADDING }

privateKey must be a PEM encoded key as string or buffer.

Related