我一直尝试使用PHP的openssl扩展生成RSA密钥对,并将结果保存为OpenSSH兼容密钥对 - 意味着私钥是PEM编码(这很容易),公钥存储在以下形式的OpenSSH特定格式:
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABA...more base64 encoded stuff...
据我所知,这种格式包括:
我尝试使用PHP的pack()函数实现这一点,但无论我尝试什么,结果都永远不等于我在openssl生成的同一RSA私钥上使用ssh-keygen -y -f
命令得到的结果。
以下是我的代码的简化版本:
<?php
// 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的情况下执行此操作的任何提示?
答案 0 :(得分:9)
好的,我刚刚通过仔细查看Convert pem key to ssh-rsa format的C实现引用来解决我自己的问题(之前我做过,但显然我错过了一些重要的东西)。我需要AND和N的第一个字符和0x80,如果匹配则在数字的开头添加另一个NULL字符并分别将大小增加1。
我不知道为什么会这样做(我没有在网上搜索中找到任何对此的引用)但是它有效。
我只对此进行了基本测试,但似乎效果很好,而且我的代码在这里:
<?php
$privKey = openssl_pkey_get_private($rsaKey);
$pubKey = sshEncodePublicKey($privKey);
echo "PHP generated RSA 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);
}
?>
答案 1 :(得分:1)
更简单的方法,使用phpseclib, a pure-PHP RSA implementation:
<?php
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->loadKey('-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0
FPqri0cb2JZfXJ/DgYSF6vUpwmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/
3j+skZ6UtW+5u09lHNsj6tQ51s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQAB
-----END PUBLIC KEY-----');
$rsa->setPublicKey();
$publickey = $rsa->getPublicKey(CRYPT_RSA_PUBLIC_FORMAT_OPENSSH);
?>
输出:
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0FPqri0cb2JZfXJ/DgYSF6vUpwmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/3j+skZ6UtW+5u09lHNsj6tQ51s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZw== phpseclib-generated-key
来源:
http://phpseclib.sourceforge.net/rsa/examples.html#public,openssh