700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > php字符串转openssl格式 将OpenSSL生成的RSA公钥转换为OpenSSH格式(PHP)

php字符串转openssl格式 将OpenSSL生成的RSA公钥转换为OpenSSH格式(PHP)

时间:2019-09-07 10:59:19

相关推荐

php字符串转openssl格式 将OpenSSL生成的RSA公钥转换为OpenSSH格式(PHP)

我一直在尝试使用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的情况下做到这一点的任何提示?

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。