1<?php
2
3/**
4 * PublicKeyLoader
5 *
6 * Returns a PublicKey or PrivateKey object.
7 *
8 * @author    Jim Wigginton <terrafrost@php.net>
9 * @copyright 2009 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;
15
16use phpseclib3\Crypt\Common\AsymmetricKey;
17use phpseclib3\Crypt\Common\PrivateKey;
18use phpseclib3\Crypt\Common\PublicKey;
19use phpseclib3\Exception\NoKeyLoadedException;
20use phpseclib3\File\X509;
21
22/**
23 * PublicKeyLoader
24 *
25 * @author  Jim Wigginton <terrafrost@php.net>
26 */
27abstract class PublicKeyLoader
28{
29    /**
30     * Loads a public or private key
31     *
32     * @return AsymmetricKey
33     * @param string|array $key
34     * @param string $password optional
35     */
36    public static function load($key, $password = false)
37    {
38        try {
39            return EC::load($key, $password);
40        } catch (NoKeyLoadedException $e) {
41        }
42
43        try {
44            return RSA::load($key, $password);
45        } catch (NoKeyLoadedException $e) {
46        }
47
48        try {
49            return DSA::load($key, $password);
50        } catch (NoKeyLoadedException $e) {
51        }
52
53        try {
54            $x509 = new X509();
55            $x509->loadX509($key);
56            $key = $x509->getPublicKey();
57            if ($key) {
58                return $key;
59            }
60        } catch (\Exception $e) {
61        }
62
63        throw new NoKeyLoadedException('Unable to read key');
64    }
65
66    /**
67     * Loads a private key
68     *
69     * @return PrivateKey
70     * @param string|array $key
71     * @param string $password optional
72     */
73    public static function loadPrivateKey($key, $password = false)
74    {
75        $key = self::load($key, $password);
76        if (!$key instanceof PrivateKey) {
77            throw new NoKeyLoadedException('The key that was loaded was not a private key');
78        }
79        return $key;
80    }
81
82    /**
83     * Loads a public key
84     *
85     * @return PublicKey
86     * @param string|array $key
87     */
88    public static function loadPublicKey($key)
89    {
90        $key = self::load($key);
91        if (!$key instanceof PublicKey) {
92            throw new NoKeyLoadedException('The key that was loaded was not a public key');
93        }
94        return $key;
95    }
96
97    /**
98     * Loads parameters
99     *
100     * @return AsymmetricKey
101     * @param string|array $key
102     */
103    public static function loadParameters($key)
104    {
105        $key = self::load($key);
106        if (!$key instanceof PrivateKey && !$key instanceof PublicKey) {
107            throw new NoKeyLoadedException('The key that was loaded was not a parameter');
108        }
109        return $key;
110    }
111}
112