1<?php
2
3/**
4 * "PKCS1" Formatted EC Key Handler
5 *
6 * PHP version 5
7 *
8 * Processes keys with the following headers:
9 *
10 * -----BEGIN DH PARAMETERS-----
11 *
12 * Technically, PKCS1 is for RSA keys, only, but we're using PKCS1 to describe
13 * DSA, whose format isn't really formally described anywhere, so might as well
14 * use it to describe this, too.
15 *
16 * @category  Crypt
17 * @package   DH
18 * @author    Jim Wigginton <terrafrost@php.net>
19 * @copyright 2015 Jim Wigginton
20 * @license   http://www.opensource.org/licenses/mit-license.html  MIT License
21 * @link      http://phpseclib.sourceforge.net
22 */
23
24namespace phpseclib3\Crypt\DH\Formats\Keys;
25
26use phpseclib3\Crypt\Common\Formats\Keys\PKCS1 as Progenitor;
27use phpseclib3\File\ASN1;
28use phpseclib3\File\ASN1\Maps;
29use phpseclib3\Math\BigInteger;
30
31/**
32 * "PKCS1" Formatted DH Key Handler
33 *
34 * @package DH
35 * @author  Jim Wigginton <terrafrost@php.net>
36 * @access  public
37 */
38abstract class PKCS1 extends Progenitor
39{
40    /**
41     * Break a public or private key down into its constituent components
42     *
43     * @access public
44     * @param string $key
45     * @param string $password optional
46     * @return array
47     */
48    public static function load($key, $password = '')
49    {
50        $key = parent::load($key, $password);
51
52        $decoded = ASN1::decodeBER($key);
53        if (empty($decoded)) {
54            throw new \RuntimeException('Unable to decode BER');
55        }
56
57        $components = ASN1::asn1map($decoded[0], Maps\DHParameter::MAP);
58        if (!is_array($components)) {
59            throw new \RuntimeException('Unable to perform ASN1 mapping on parameters');
60        }
61
62        return $components;
63    }
64
65    /**
66     * Convert EC parameters to the appropriate format
67     *
68     * @access public
69     * @return string
70     */
71    public static function saveParameters(BigInteger $prime, BigInteger $base, array $options = [])
72    {
73        $params = [
74            'prime' => $prime,
75            'base' => $base
76        ];
77        $params = ASN1::encodeDER($params, Maps\DHParameter::MAP);
78
79        return "-----BEGIN DH PARAMETERS-----\r\n" .
80               chunk_split(base64_encode($params), 64) .
81               "-----END DH PARAMETERS-----\r\n";
82    }
83}
84