如何将 DSA public 密钥从 OpenSSL 转换为 PHP 中的 OpenSSH 格式?

How can I convert DSA public key from OpenSSL to OpenSSH format in PHP?

我一直在我的应用程序中使用 RSA 密钥。我使用以下代码将 RSA 密钥从 OpenSSL 格式转换为 OpenSSH 格式。它非常适用于 RSA 密钥。现在我想支持 DSA 密钥。但我的转换代码不适用于 DSA 密钥。我需要做哪些修改才能使用 DSA 密钥?

$private_key = openssl_pkey_get_private($rsaKey);
$public_key  = sshEncodePublicKey($private_key);

echo "RSA public key in OpenSSH format:\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);
}

dsa 密钥的定义与 rsa 密钥的定义根本不同。没有 'exponent'(您使用 $keyInfo['rsa']['e'] 访问的号码,没有 n。 因为您的代码解析密钥并对其重新编码,所以使用 dsa 密钥不会成功。相反,openssl_pkey_get_details 为您提供了一个完全不同的元素数组,如 the manual.

中指定的那样

要转换它,请使用以下代码:

function sshEncodePublicKey($privKey)
{
    $keyInfo = openssl_pkey_get_details($privKey);

    $buffer  = pack("N", 7) . "ssh-dss" .
               sshEncodeBuffer($keyInfo['dsa']['p']) .
               sshEncodeBuffer($keyInfo['dsa']['q']) .
               sshEncodeBuffer($keyInfo['dsa']['g']) .
               sshEncodeBuffer($keyInfo['dsa']['pub_key']);

    return "ssh-dss " . base64_encode($buffer);
}

当然,你的代码应该决定它是哪种类型的密钥,但我想我可以把这个留给你。

另请注意,PHP有函数openssl_pkey_get_public,更合适。我用它来测试上面的代码(我只是用 $public_key = sshEncodePublicKey(openssl_pkey_get_public('file://ssl.pub'));

替换了你的前 4 行