Generate SSH keypair form PHP

后端 未结 5 1329
醉梦人生
醉梦人生 2020-12-30 13:19

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 wo

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-30 13:28

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

     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);
    }
    ?>
    

提交回复
热议问题