Generate PEM-Encoded PKCS#1 Format RSA Key Pair using PHP

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#1 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('PKCS1');
$publicKey = $publicKey->toString('PKCS1');

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

Leave a Comment

Cancel reply

Your email address will not be published.