Skip to content

Instantly share code, notes, and snippets.

@poulou0
Created October 14, 2022 07:11
Show Gist options
  • Save poulou0/a09ed696d6d6c7f8cf6e98136ddecb1a to your computer and use it in GitHub Desktop.
Save poulou0/a09ed696d6d6c7f8cf6e98136ddecb1a to your computer and use it in GitHub Desktop.
Asymetric PEM keypair generators with PHP and Node.js

PEM format https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail

PHP

OPENSSL_KEYTYPE_DSA, OPENSSL_KEYTYPE_DH, OPENSSL_KEYTYPE_RSA or OPENSSL_KEYTYPE_EC

<?php
$keyPair = openssl_pkey_new(['private_key_bits' => 512, 'private_key_type' => OPENSSL_KEYTYPE_RSA]);
openssl_pkey_export($keyPair, $privateKey);
$publicKey = openssl_pkey_get_details($keyPair)['key'];

var_dump($privateKey, $publicKey);

See also openssl_csr_new Self signed ssl certificate in the examples https://www.php.net/manual/en/function.openssl-csr-new.php#example-931

Node.js

https://stackoverflow.com/a/53173811/1748645

const { generateKeyPairSync } = require('crypto');
const { publicKey, privateKey } = generateKeyPairSync('rsa', {
  modulusLength: 512,
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem'
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem',
    cipher: 'aes-256-cbc',
    passphrase: 'top secret'
  }
});

console.log(publicKey, privateKey);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment