0

In PHP, I have a public key (already as an OpenSSL resource). I'd like to calculate that public keys fingerprint (SHA1 or other hash).

How do I do this?

PHP version is 7.2 or older.

EDIT: This is not a duplicate of the other question, because that question is about doing this for an SSH key with SSH (and related) commands. I want to do the same thing using PHP and the PHP-extension openssl.

Jost
  • 5,948
  • 8
  • 42
  • 72
  • Possible duplicate of [Calculate RSA key fingerprint](https://stackoverflow.com/questions/9607295/calculate-rsa-key-fingerprint) – NanoPish May 24 '19 at 15:49

2 Answers2

1

I've found the solution myself. The basic idea:

  1. Decode the base64 encoded part of the key in PEM format (after removing spaces from it)
  2. Hash the resulting binary data.

In code (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);
}
Jost
  • 5,948
  • 8
  • 42
  • 72
-1

if you need a hash php has multiple hashing functions available:

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

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

or use hash() if you need a more specific algorithm - see the docs

ggdx
  • 3,024
  • 4
  • 32
  • 48
Auris
  • 1,309
  • 1
  • 9
  • 18
  • Sorry, but calculating a hash is not the problem - the problem to a) find out from what exactly (which format) to calculate the hash and b) how to get the key into the format I need to calculate the hash from. – Jost May 25 '19 at 14:09
  • ah, sorry, missunderstood the question. a fingerprint is either a sha256 (newer systems) or md5 older systems encrypted string in hex format. what format to use really depends on who will be consuming it. Open ssh can generate this for you quite easily, but with pure PHP you would have to replicate exactly what "ssh-keygen -l -E" does with the pub key in the background. Sry cant help you out more. – Auris May 29 '19 at 08:58