如何获取public键的指纹?

How to get the fingerprint of a public key?

在 PHP 中,我有一个 public 密钥(已经作为 OpenSSL 资源)。我想计算 public 键指纹(SHA1 或其他哈希)。

我该怎么做?

PHP 版本为 7.2 或更旧。

编辑:这不是另一个问题的重复,因为该问题是关于使用 SSH(和相关)命令为 SSH 密钥执行此操作。我想使用 PHP 和 PHP-extension openssl.

做同样的事情

如果您需要哈希 php 有多个可用的哈希函数:

sha1() - https://php.net/manual/en/function.sha1.php

md5() - https://www.php.net/manual/en/function.md5.php

或者如果您需要更具体的算法,请使用 hash() - see the docs

我自己找到了解决办法。基本思路:

  1. 解码 PEM 格式密钥的 base64 编码部分(从中删除空格后)
  2. 对生成的二进制数据进行哈希处理。

代码中(PHP):

function getPublicKeyFingerprint(string $pemEncodedKey, string $hashAlgorithm = 'sha1')
{
    $keyWithoutPemWrapper = \preg_replace(
        '/^-----BEGIN (?:[A-Z]+ )?PUBLIC KEY-----([A-Za-z0-9\/\+\s=]+)-----END (?:[A-Z]+ )?PUBLIC KEY-----$/ms',
        '\1',
        $pemEncodedKey
    );
    $keyDataWithoutSpaces = \preg_replace('/\s+/', '', $keyWithoutPemWrapper);

    $binaryKey = \base64_decode($keyDataWithoutSpaces);

    return \hash($hashAlgorithm, $binaryKey);
}