将OpenSSL生成的RSA公钥转换为OpenSSH格式(PHP)
我一直尝试使用PHP的openssl扩展生成RSA密钥对,并将结果保存为OpenSSH兼容密钥对 - 意味着私钥是PEM编码(这很容易),公钥以OpenSSH特定格式存储以下形式:
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABA...more base64 encoded stuff...
据我所知,这种格式包括:
明文中的密钥类型,后跟空格(即“openssh-rsa”)
base64编码的字符串,表示以下数据:
算法名称的长度(以字节为单位)(在本例中为7)编码为32位无符号长大端
算法名称,在本例中为'ssh-rsa'
RSA'e'数字的长度,以字节为单位,编码为32位无符号长大端
RSA'e'号码
RSA'n'的长度,以字节为单位,编码为32位无符号长大端
RSA'n'号码
我尝试使用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$pubKeynn";
// 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$otherPubKeynn";
echo ($pubKey == $otherPubKey ? "yes! they are the samen" : "FAIL! they are differentn");
?>
关于如何在不依赖ssh-keygen的情况下做到这一点的任何提示?
没有找到相关结果
已邀请:
2 个回复
马口
先对冈蒲
输出:
资源: http://phpseclib.sourceforge.net/rsa/examples.html#public,openssh