1<?php
2
3/**
4 * DH Private Key
5 *
6 * @author    Jim Wigginton <terrafrost@php.net>
7 * @copyright 2015 Jim Wigginton
8 * @license   http://www.opensource.org/licenses/mit-license.html  MIT License
9 * @link      http://phpseclib.sourceforge.net
10 */
11
12namespace phpseclib3\Crypt\DH;
13
14use phpseclib3\Crypt\Common;
15use phpseclib3\Crypt\DH;
16
17/**
18 * DH Private Key
19 *
20 * @author  Jim Wigginton <terrafrost@php.net>
21 */
22final class PrivateKey extends DH
23{
24    use Common\Traits\PasswordProtected;
25
26    /**
27     * Private Key
28     *
29     * @var \phpseclib3\Math\BigInteger
30     */
31    protected $privateKey;
32
33    /**
34     * Public Key
35     *
36     * @var \phpseclib3\Math\BigInteger
37     */
38    protected $publicKey;
39
40    /**
41     * Returns the public key
42     *
43     * @return DH\PublicKey
44     */
45    public function getPublicKey()
46    {
47        $type = self::validatePlugin('Keys', 'PKCS8', 'savePublicKey');
48
49        if (!isset($this->publicKey)) {
50            $this->publicKey = $this->base->powMod($this->privateKey, $this->prime);
51        }
52
53        $key = $type::savePublicKey($this->prime, $this->base, $this->publicKey);
54
55        return DH::loadFormat('PKCS8', $key);
56    }
57
58    /**
59     * Returns the private key
60     *
61     * @param string $type
62     * @param array $options optional
63     * @return string
64     */
65    public function toString($type, array $options = [])
66    {
67        $type = self::validatePlugin('Keys', $type, 'savePrivateKey');
68
69        if (!isset($this->publicKey)) {
70            $this->publicKey = $this->base->powMod($this->privateKey, $this->prime);
71        }
72
73        return $type::savePrivateKey($this->prime, $this->base, $this->privateKey, $this->publicKey, $this->password, $options);
74    }
75}
76