我一直在尝试使用PHP的openssl扩展生成一个RSA密钥对,并将结果保存为OpenSSH兼容密钥对 - 这意味着私钥是PEM编码的(这很简单),公钥以OpenSSH特定格式存储以下形式:
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABA...more base64 encoded stuff...据我所知,这种格式包括:
密钥类型为明文,后跟空格(即“openssh-rsa”)
表示以下数据的base64编码的字符串:
算法名称的长度(以字节为单位)(编码为32位)unsigned long big endian
算法名称,在本例中为'ssh-rsa'
RSA'e'的字节长度(以字节为单位),编码为32位无符号long long endian
RSA'e'号码
RSA'n'个字节的长度(以字节为单位),编码为32位无符号long long endian
RSA'n'号码
我尝试过使用PHP的pack()函数来实现这一点,但无论我尝试什么,结果都不会等同于在openssl生成的相同RSA私钥上使用ssh-keygen -y -f命令时所得到的结果。
以下是我的代码的简化版本:
// generate private key
$privKey = openssl_pkey_new(array(
'private_key_bits' => 1024,
'private_key_type' => OPENSSL_KEYTYPE_RSA
));
// convert public key to OpenSSH format
$keyInfo = openssl_pkey_get_details($privKey);
$data = pack("Na*", 7, 'ssh-rsa');
$data .= pack("Na*", strlen($keyInfo['rsa']['e']), $keyInfo['rsa']['e']);
$data .= pack("Na*", strlen($keyInfo['rsa']['n']), $keyInfo['rsa']['n']);
$pubKey = "ssh-rsa " . base64_encode($data);
echo "PHP generated RSA public key:\n$pubKey\n\n";
// For comparison, generate public key using ssh-keygen
openssl_pkey_export($privKey, $pem);
$umask = umask(0066); // this is needed for ssh-keygen to work properly
file_put_contents('/tmp/ssh-keygen-test', $pem);
umask($umask);
exec('ssh-keygen -y -f /tmp/ssh-keygen-test', $out, $ret);
$otherPubKey = $out[0];
echo "ssh-keygen generated RSA public key:\n$otherPubKey\n\n";
echo ($pubKey == $otherPubKey ? "yes! they are the same\n" : "FAIL! they are different\n");
?>有关如何在不依赖于ssh-keygen的情况下做到这一点的任何提示?