Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate SSH keypair form PHP

Tags:

php

ssh

I want to generate ssh keypair from php can anyone please guide me how to do it? I have tried the shell_exec but the shell asks questions so that command does not work. I would like to specify filename and path in which to put the keys after generation.

like image 200
adityap Avatar asked Jul 11 '11 09:07

adityap


1 Answers

This is based on Converting an OpenSSL generated RSA public key to OpenSSH format (PHP). Thanks shevron.

<?php
$rsaKey = openssl_pkey_new(array( 
              'private_key_bits' => 1024, 
              'private_key_type' => OPENSSL_KEYTYPE_RSA));

$privKey = openssl_pkey_get_private($rsaKey); 
openssl_pkey_export($privKey, $pem); //Private Key
$pubKey = sshEncodePublicKey($rsaKey); //Public Key

$umask = umask(0066); 
file_put_contents('/tmp/test.rsa', $pem); //save private key into file
file_put_contents('/tmp/test.rsa.pub', $pubKey); //save public key into file

print "Private Key:\n $pem \n\n";
echo "Public key:\n$pubKey\n\n";

function sshEncodePublicKey($privKey) {
    $keyInfo = openssl_pkey_get_details($privKey);
    $buffer  = pack("N", 7) . "ssh-rsa" .
    sshEncodeBuffer($keyInfo['rsa']['e']) . 
    sshEncodeBuffer($keyInfo['rsa']['n']);
    return "ssh-rsa " . base64_encode($buffer);
}

function sshEncodeBuffer($buffer) {
    $len = strlen($buffer);
    if (ord($buffer[0]) & 0x80) {
        $len++;
        $buffer = "\x00" . $buffer;
    }
    return pack("Na*", $len, $buffer);
}
?>
like image 73
StackKrish Avatar answered Sep 23 '22 04:09

StackKrish