0

I am using Node.js RSA library (https://github.com/rzcoder/node-rsa) to generate a public and private key pair with the following codes:

const key = new nodeRSA();
key.generateKeyPair(2048, 65537);

const pemPublicKey = key.exportKey('pkcs1-public-pem');
const pemPrivateKey = key.exportKey('pkcs1-private-pem');

The key I get is as follows:

-----BEGIN RSA PUBLIC KEY-----\nMIIBCgKCAQEAnvrbDfGOT9pmKWZafkEizt8WfMbhmf46e7zyHMRQNHTxPKuP89fc\n5BAkhXylC9ozfjTjiQb5wDh1yw5HafyAKE4Jh28fzX1TJnVra1ijpQTte4+v1WVe\na8qxBuzUI6bxJtR/AV1XyfeWbYx27lSenw2ynqiut+oQ5MZ9kOxX4ba+/cWYcvMn\ni0OnhnNIQp0a+cY78sfz/LpDMumWDVZKvOTREg1y9KxGkd/yyYrHyxAAsfijY/47\n70KH0c4FjjYrWipVHAHj/ayhoAFRBFY9uI9pqLamf8AfBsjvIT16/viT4LE6kUEu\nU2zxOUevkjTq3tgOZoFomiSDJC1EopVhvQIDAQAB\n-----END RSA PUBLIC KEY-----

Question is: how can I get rid of the header and footer and the \n in the base64 string?

The reason I want to do it is just because I wanna the key to be consistent with what I have in the database

Thanks!

leonsPAPA
  • 657
  • 2
  • 13
  • 29

1 Answers1

1

According to Import/Export documentation you can export the key as DER and convert the result to base64. (PEM is DER binary format converted to base64 and adding header and footer)

const derPublicKey = key.exportKey('pkcs1-public-der');
const derPrivateKey = key.exportKey('pkcs1-private-der');

I'm not familiar with node.js. Converting binary to base64 should look something like this

var derB64PublicKey  = new Buffer(derPublicKey , 'binary').toString('base64');
var derB64PrivateKey  = new Buffer(derPrivateKey , 'binary').toString('base64');

Alternatively it would be easy to delete header, footer and \n from the PEM data, but the option to export to DER seems more reasonable

Community
  • 1
  • 1
pedrofb
  • 37,271
  • 5
  • 94
  • 142