Skip to content

Instantly share code, notes, and snippets.

@TomCan
Last active September 12, 2023 18:21
Show Gist options
  • Save TomCan/e5b9c91205ed6642e7d6568eeca4ee15 to your computer and use it in GitHub Desktop.
Save TomCan/e5b9c91205ed6642e7d6568eeca4ee15 to your computer and use it in GitHub Desktop.
Convert public part of OpenSSL RSA private key to SSH authorized_keys format
<?php
function encodeMPINT($binary)
{
// If the most significant bit is set, prepend a zero byte to make it positive
if (ord($binary[0]) & 0x80) {
$binary = "\x00".$binary;
}
// Encode the length as a 32-bit big-endian integer
$length = strlen($binary);
$lengthBytes = pack('N', $length);
// Combine the length and binary data
return $lengthBytes.$binary;
}
// Load private key from file key.txt
$pkey = openssl_pkey_get_private(file_get_contents('key.txt'));
// Get details of the key
$details = openssl_pkey_get_details($pkey);
echo 'ssh-rsa '.base64_encode(encodeMPINT('ssh-rsa').encodeMPINT($details['rsa']['e']).encodeMPINT($details['rsa']['n']));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment