1<?php
2
3/**
4 * XML Formatted DSA Key Handler
5 *
6 * While XKMS defines a private key format for RSA it does not do so for DSA. Quoting that standard:
7 *
8 * "[XKMS] does not specify private key parameters for the DSA signature algorithm since the algorithm only
9 *  supports signature modes and so the application of server generated keys and key recovery is of limited
10 *  value"
11 *
12 * PHP version 5
13 *
14 * @category  Crypt
15 * @package   DSA
16 * @author    Jim Wigginton <terrafrost@php.net>
17 * @copyright 2015 Jim Wigginton
18 * @license   http://www.opensource.org/licenses/mit-license.html  MIT License
19 * @link      http://phpseclib.sourceforge.net
20 */
21
22namespace phpseclib3\Crypt\DSA\Formats\Keys;
23
24use ParagonIE\ConstantTime\Base64;
25use phpseclib3\Math\BigInteger;
26use phpseclib3\Common\Functions\Strings;
27
28/**
29 * XML Formatted DSA Key Handler
30 *
31 * @package DSA
32 * @author  Jim Wigginton <terrafrost@php.net>
33 * @access  public
34 */
35abstract class XML
36{
37    /**
38     * Break a public or private key down into its constituent components
39     *
40     * @access public
41     * @param string $key
42     * @param string $password optional
43     * @return array
44     */
45    public static function load($key, $password = '')
46    {
47        if (!Strings::is_stringable($key)) {
48            throw new \UnexpectedValueException('Key should be a string - not a ' . gettype($key));
49        }
50
51        $use_errors = libxml_use_internal_errors(true);
52
53        $dom = new \DOMDocument();
54        if (substr($key, 0, 5) != '<?xml') {
55            $key = '<xml>' . $key . '</xml>';
56        }
57        if (!$dom->loadXML($key)) {
58            throw new \UnexpectedValueException('Key does not appear to contain XML');
59        }
60        $xpath = new \DOMXPath($dom);
61        $keys = ['p', 'q', 'g', 'y', 'j', 'seed', 'pgencounter'];
62        foreach ($keys as $key) {
63            // $dom->getElementsByTagName($key) is case-sensitive
64            $temp = $xpath->query("//*[translate(local-name(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='$key']");
65            if (!$temp->length) {
66                continue;
67            }
68            $value = new BigInteger(Base64::decode($temp->item(0)->nodeValue), 256);
69            switch ($key) {
70                case 'p': // a prime modulus meeting the [DSS] requirements
71                    // Parameters P, Q, and G can be public and common to a group of users. They might be known
72                    // from application context. As such, they are optional but P and Q must either both appear
73                    // or both be absent
74                    $components['p'] = $value;
75                    break;
76                case 'q': // an integer in the range 2**159 < Q < 2**160 which is a prime divisor of P-1
77                    $components['q'] = $value;
78                    break;
79                case 'g': // an integer with certain properties with respect to P and Q
80                    $components['g'] = $value;
81                    break;
82                case 'y': // G**X mod P (where X is part of the private key and not made public)
83                    $components['y'] = $value;
84                    // the remaining options do not do anything
85                case 'j': // (P - 1) / Q
86                    // Parameter J is available for inclusion solely for efficiency as it is calculatable from
87                    // P and Q
88                case 'seed': // a DSA prime generation seed
89                    // Parameters seed and pgenCounter are used in the DSA prime number generation algorithm
90                    // specified in [DSS]. As such, they are optional but must either both be present or both
91                    // be absent
92                case 'pgencounter': // a DSA prime generation counter
93            }
94        }
95
96        libxml_use_internal_errors($use_errors);
97
98        if (!isset($components['y'])) {
99            throw new \UnexpectedValueException('Key is missing y component');
100        }
101
102        switch (true) {
103            case !isset($components['p']):
104            case !isset($components['q']):
105            case !isset($components['g']):
106                return ['y' => $components['y']];
107        }
108
109        return $components;
110    }
111
112    /**
113     * Convert a public key to the appropriate format
114     *
115     * See https://www.w3.org/TR/xmldsig-core/#sec-DSAKeyValue
116     *
117     * @access public
118     * @param \phpseclib3\Math\BigInteger $p
119     * @param \phpseclib3\Math\BigInteger $q
120     * @param \phpseclib3\Math\BigInteger $g
121     * @param \phpseclib3\Math\BigInteger $y
122     * @return string
123     */
124    public static function savePublicKey(BigInteger $p, BigInteger $q, BigInteger $g, BigInteger $y)
125    {
126        return "<DSAKeyValue>\r\n" .
127               '  <P>' . Base64::encode($p->toBytes()) . "</P>\r\n" .
128               '  <Q>' . Base64::encode($q->toBytes()) . "</Q>\r\n" .
129               '  <G>' . Base64::encode($g->toBytes()) . "</G>\r\n" .
130               '  <Y>' . Base64::encode($y->toBytes()) . "</Y>\r\n" .
131               '</DSAKeyValue>';
132    }
133}
134