gpt4 book ai didi

php - 从 PHP 生成 SSH key 对

转载 作者:可可西里 更新时间:2023-11-01 13:33:10 25 4
gpt4 key购买 nike

我想从 php 生成 ssh key 对,谁能指导我怎么做?我已经尝试过 shell_exec 但 shell 会询问问题,因此该命令不起作用。我想指定生成后放置 key 的文件名和路径。

最佳答案

这是基于Converting an OpenSSL generated RSA public key to OpenSSH format (PHP) .谢谢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);
}
?>

关于php - 从 PHP 生成 SSH key 对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6648337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com