genkeys.js 821 B

123456789101112131415161718192021222324
  1. const crypto = require('crypto');
  2. const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
  3. modulusLength: 2048,
  4. publicKeyEncoding: { type: 'spki', format: 'pem' },
  5. privateKeyEncoding: { type: 'pkcs1', format: 'pem' },
  6. });
  7. const privB64 = privateKey
  8. .replace('-----BEGIN RSA PRIVATE KEY-----\n', '')
  9. .replace('\n-----END RSA PRIVATE KEY-----', '')
  10. .replace(/\n/g, '');
  11. const fs = require('fs');
  12. fs.writeFileSync('_priv.txt', privB64);
  13. fs.writeFileSync('_pub.txt', publicKey);
  14. // Verify
  15. const privObj = crypto.createPrivateKey(privateKey);
  16. const pubObj = crypto.createPublicKey(privObj);
  17. const pubOut = pubObj.export({ type: 'spki', format: 'pem' });
  18. console.log('Generated and verified.');
  19. console.log('Private base64 length:', privB64.length);
  20. console.log('Public PEM:');
  21. console.log(pubOut);