SSH Key Generator — PHP source
Generate Ed25519 or RSA SSH key pairs in your browser. Copy or download the public and private keys. No server involved.
This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
/**
* ssh-keygen — Ed25519 / RSA SSH key pair generation in OpenSSH format.
*
* Language: PHP 7.4+ (standard library plus the bundled ext-openssl).
* CosmoDev polyglot showcase port of the `ssh-keygen` tool, ported from
* src/lib/ssh-keygen.ts (the canonical TypeScript implementation).
*
* Substitution note: PHP's bundled ext-openssl generates RSA keys but only
* exports them as PKCS#1, so this port adds the small ASN.1 wrapper the TS
* lib gets for free from WebCrypto (PKCS#8). ext-openssl exposes no Ed25519
* keygen, so — like the C# sibling — build_ed25519_key_pair() takes raw key
* material from any PHP Ed25519 library and assembles the exact OpenSSH
* wire formats around it.
*
* display source — part of CosmoDev's polyglot tool pages.
*/
declare(strict_types=1);
const MAGIC = "openssh-key-v1\x00"; // leading magic of every unencrypted OpenSSH private key
/** SSH "string": 4-byte big-endian length + raw bytes. */
function ssh_string(string $data): string
{
return pack('N', strlen($data)) . $data;
}
/** SSH "mpint": big-endian integer, minimal, with a leading zero when the high bit is set. */
function mpint(string $bytes): string
{
$i = 0;
$len = strlen($bytes);
while ($i + 1 < $len && $bytes[$i] === "\x00") {
$i++;
}
$v = substr($bytes, $i);
if ($v !== '' && (ord($v[0]) & 0x80) !== 0) {
$v = "\x00" . $v;
}
return ssh_string($v);
}
function pem_wrap(string $base64, string $label, int $width): string
{
$lines = str_split($base64, $width);
return "-----BEGIN {$label}-----\n" . implode("\n", $lines) . "\n-----END {$label}-----\n";
}
/** "SHA256:<base64 digest of the public blob, unpadded>" - the OpenSSH fingerprint format. */
function ssh_fingerprint(string $pub_blob): string
{
return 'SHA256:' . rtrim(base64_encode(hash('sha256', $pub_blob, true)), '=');
}
/**
* Build the unencrypted "openssh-key-v1" private key structure for Ed25519
* (cipher "none", kdf "none"), wrapped in an OPENSSH PRIVATE KEY PEM.
*/
function open_ssh_private_pem(string $pub_blob, string $private_key, string $comment): string
{
$check = random_bytes(4);
$inner = $check . $check . $pub_blob . ssh_string($private_key) . ssh_string($comment);
$pad_len = (8 - strlen($inner) % 8) % 8;
for ($i = 1; $i <= $pad_len; $i++) {
$inner .= chr($i); // pad to the 8-byte block with 1,2,3,...
}
$outer = MAGIC
. ssh_string('none') // ciphername
. ssh_string('none') // kdfname
. ssh_string('') // kdfoptions
. pack('N', 1) // number of keys
. ssh_string($pub_blob)
. ssh_string($inner);
return pem_wrap(base64_encode($outer), 'OPENSSH PRIVATE KEY', 70);
}
/** Minimal DER encoder: tag + length + payload, short or long form. */
function asn1(string $tag, string $payload): string
{
$len = strlen($payload);
if ($len < 0x80) {
$length = chr($len);
} else {
$bytes = ltrim(pack('N', $len), "\x00");
$length = chr(0x80 | strlen($bytes)) . $bytes;
}
return $tag . $length . $payload;
}
/**
* Normalize an RSA private key PEM to the PKCS#8 form the TS lib emits
* (WebCrypto exports RSA private keys as "BEGIN PRIVATE KEY"). Recent PHP
* builds already export PKCS#8; older ones emit PKCS#1 ("BEGIN RSA PRIVATE
* KEY"), which we wrap in the PKCS#8 structure here.
*/
function rsa_pkcs8_pem(string $pem): string
{
$base64 = (string) preg_replace('/-----[^-]+-----|\s+/', '', $pem);
if (strpos($pem, '-----BEGIN PRIVATE KEY-----') === 0) {
return pem_wrap($base64, 'PRIVATE KEY', 64); // already PKCS#8; just re-wrap
}
// SEQUENCE { INTEGER 0, SEQUENCE { OID rsaEncryption, NULL }, OCTET STRING pkcs1 }
$rsa_oid = "\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01"; // 1.2.840.113549.1.1.1
$algorithm = asn1("\x30", asn1("\x06", $rsa_oid) . asn1("\x05", ''));
$pkcs8 = asn1("\x30", asn1("\x02", "\x00") . $algorithm . asn1("\x04", base64_decode($base64, true)));
return pem_wrap(base64_encode($pkcs8), 'PRIVATE KEY', 64);
}
/** Generate an RSA SSH key pair in OpenSSH format (2048 or 4096 bits). */
function generate_rsa_key_pair(int $bits, ?string $comment = null): array
{
$key = openssl_pkey_new(['private_key_bits' => $bits, 'private_key_type' => OPENSSL_KEYTYPE_RSA]);
if ($key === false) {
throw new RuntimeException('openssl_pkey_new failed: ' . (string) openssl_error_string());
}
$details = openssl_pkey_get_details($key);
if ($details === false || !isset($details['rsa']['e'], $details['rsa']['n'])) {
throw new RuntimeException('Failed to export the RSA public key.');
}
$trimmed = trim($comment ?? '');
$suffix = $trimmed !== '' ? " {$trimmed}" : '';
// $details['rsa']['e'] / ['n'] are the raw big-endian integers.
$pub_blob = ssh_string('ssh-rsa') . mpint($details['rsa']['e']) . mpint($details['rsa']['n']);
if (!openssl_pkey_export($key, $pkcs1)) {
throw new RuntimeException('openssl_pkey_export failed.');
}
return [
'public_key' => "ssh-rsa " . base64_encode($pub_blob) . $suffix,
'private_key' => rsa_pkcs8_pem($pkcs1),
'fingerprint' => ssh_fingerprint($pub_blob),
];
}
/**
* Assemble the Ed25519 OpenSSH key pair from raw key material ($private_key
* blob carries seed || public, 64 bytes, per OpenSSH).
*/
function build_ed25519_key_pair(string $public_key, string $seed, ?string $comment = null): array
{
if (strlen($public_key) !== 32 || strlen($seed) !== 32) {
throw new InvalidArgumentException('Ed25519 public key and seed must each be 32 bytes.');
}
$trimmed = trim($comment ?? '');
$suffix = $trimmed !== '' ? " {$trimmed}" : '';
$pub_blob = ssh_string('ssh-ed25519') . ssh_string($public_key);
return [
'public_key' => "ssh-ed25519 " . base64_encode($pub_blob) . $suffix,
'private_key' => open_ssh_private_pem($pub_blob, $seed . $public_key, $trimmed),
'fingerprint' => ssh_fingerprint($pub_blob),
];
}
/** Entry point mirroring generateSSHKeyPair() in the TS lib. */
function generate_ssh_key_pair(array $options = []): array
{
$algorithm = $options['algorithm'] ?? null;
switch ($algorithm) {
case 'ed25519':
throw new InvalidArgumentException(
'ext-openssl cannot generate Ed25519 keys; pass raw material to build_ed25519_key_pair().'
);
case 'rsa-2048':
return generate_rsa_key_pair(2048, $options['comment'] ?? null);
case 'rsa-4096':
return generate_rsa_key_pair(4096, $options['comment'] ?? null);
default:
throw new InvalidArgumentException('Unsupported algorithm: ' . var_export($algorithm, true));
}
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →