OpenSSL extension

  1. Enable extension in php.ini file:
extension=openssl
  1. Generate PEM-encoded PKCS#8 format RSA key pair:
<?php

$keySize = 2048;

$key = openssl_pkey_new([
    "private_key_bits" => $keySize,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
]);

openssl_pkey_export($key, $privateKey);
$publicKey = openssl_pkey_get_details($key)['key'];

echo $privateKey;
echo $publicKey;

phpseclib library

  1. Add phpseclib library to composer.json file:
"require": {
    "phpseclib/phpseclib": "^3.0"
}
  1. Install library from the command line:
composer install
  1. Generate PEM-encoded PKCS#8 format RSA key pair:
<?php

use phpseclib3\Crypt\RSA;

require_once __DIR__.'/vendor/autoload.php';

$keySize = 2048;

$privateKey = RSA::createKey($keySize);
$publicKey = $privateKey->getPublicKey();

$privateKey = $privateKey->toString('PKCS8');
$publicKey = $publicKey->toString('PKCS8');

echo $privateKey.PHP_EOL;
echo $publicKey.PHP_EOL;

Leave a Comment

Your email address will not be published. Required fields are marked *