xref: /dokuwiki/vendor/phpseclib/phpseclib/phpseclib/Crypt/Common/Traits/Fingerprint.php (revision 927933f55f286c8bea68959a13975cbcb59eb8ee)
1<?php
2
3/**
4 * Fingerprint Trait for Public Keys
5 *
6 * PHP version 5
7 *
8 * @author    Jim Wigginton <terrafrost@php.net>
9 * @copyright 2015 Jim Wigginton
10 * @license   http://www.opensource.org/licenses/mit-license.html  MIT License
11 * @link      http://phpseclib.sourceforge.net
12 */
13
14namespace phpseclib3\Crypt\Common\Traits;
15
16use phpseclib3\Crypt\Hash;
17
18/**
19 * Fingerprint Trait for Private Keys
20 *
21 * @author  Jim Wigginton <terrafrost@php.net>
22 */
23trait Fingerprint
24{
25    /**
26     * Returns the public key's fingerprint
27     *
28     * The public key's fingerprint is returned, which is equivalent to running `ssh-keygen -lf rsa.pub`. If there is
29     * no public key currently loaded, false is returned.
30     * Example output (md5): "c1:b1:30:29:d7:b8:de:6c:97:77:10:d7:46:41:63:87" (as specified by RFC 4716)
31     *
32     * @param string $algorithm The hashing algorithm to be used. Valid options are 'md5' and 'sha256'. False is returned
33     * for invalid values.
34     * @return mixed
35     */
36    public function getFingerprint($algorithm = 'md5')
37    {
38        $type = self::validatePlugin('Keys', 'OpenSSH', 'savePublicKey');
39        if ($type === false) {
40            return false;
41        }
42        $key = $this->toString('OpenSSH', ['binary' => true]);
43        if ($key === false) {
44            return false;
45        }
46        switch ($algorithm) {
47            case 'sha256':
48                $hash = new Hash('sha256');
49                $base = base64_encode($hash->hash($key));
50                return substr($base, 0, strlen($base) - 1);
51            case 'md5':
52                return substr(chunk_split(md5($key), 2, ':'), 0, -1);
53            default:
54                return false;
55        }
56    }
57}
58