Subversion Repositories oidplus

Rev

Rev 874 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

  1. <?php
  2.  
  3. /**
  4.  * PKCS#8 Formatted EC Key Handler
  5.  *
  6.  * PHP version 5
  7.  *
  8.  * Processes keys with the following headers:
  9.  *
  10.  * -----BEGIN ENCRYPTED PRIVATE KEY-----
  11.  * -----BEGIN PRIVATE KEY-----
  12.  * -----BEGIN PUBLIC KEY-----
  13.  *
  14.  * Analogous to ssh-keygen's pkcs8 format (as specified by -m). Although PKCS8
  15.  * is specific to private keys it's basically creating a DER-encoded wrapper
  16.  * for keys. This just extends that same concept to public keys (much like ssh-keygen)
  17.  *
  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.  
  24. namespace phpseclib3\Crypt\EC\Formats\Keys;
  25.  
  26. use phpseclib3\Common\Functions\Strings;
  27. use phpseclib3\Crypt\Common\Formats\Keys\PKCS8 as Progenitor;
  28. use phpseclib3\Crypt\EC\BaseCurves\Base as BaseCurve;
  29. use phpseclib3\Crypt\EC\BaseCurves\Montgomery as MontgomeryCurve;
  30. use phpseclib3\Crypt\EC\BaseCurves\TwistedEdwards as TwistedEdwardsCurve;
  31. use phpseclib3\Crypt\EC\Curves\Ed25519;
  32. use phpseclib3\Crypt\EC\Curves\Ed448;
  33. use phpseclib3\Exception\UnsupportedCurveException;
  34. use phpseclib3\File\ASN1;
  35. use phpseclib3\File\ASN1\Maps;
  36. use phpseclib3\Math\BigInteger;
  37.  
  38. /**
  39.  * PKCS#8 Formatted EC Key Handler
  40.  *
  41.  * @author  Jim Wigginton <terrafrost@php.net>
  42.  */
  43. abstract class PKCS8 extends Progenitor
  44. {
  45.     use Common;
  46.  
  47.     /**
  48.      * OID Name
  49.      *
  50.      * @var array
  51.      */
  52.     const OID_NAME = ['id-ecPublicKey', 'id-Ed25519', 'id-Ed448'];
  53.  
  54.     /**
  55.      * OID Value
  56.      *
  57.      * @var string
  58.      */
  59.     const OID_VALUE = ['1.2.840.10045.2.1', '1.3.101.112', '1.3.101.113'];
  60.  
  61.     /**
  62.      * Break a public or private key down into its constituent components
  63.      *
  64.      * @param string $key
  65.      * @param string $password optional
  66.      * @return array
  67.      */
  68.     public static function load($key, $password = '')
  69.     {
  70.         // initialize_static_variables() is defined in both the trait and the parent class
  71.         // when it's defined in two places it's the traits one that's called
  72.         // the parent one is needed, as well, but the parent one is called by other methods
  73.         // in the parent class as needed and in the context of the parent it's the parent
  74.         // one that's called
  75.         self::initialize_static_variables();
  76.  
  77.         if (!Strings::is_stringable($key)) {
  78.             throw new \UnexpectedValueException('Key should be a string - not a ' . gettype($key));
  79.         }
  80.  
  81.         $isPublic = strpos($key, 'PUBLIC') !== false;
  82.  
  83.         $key = parent::load($key, $password);
  84.  
  85.         $type = isset($key['privateKey']) ? 'privateKey' : 'publicKey';
  86.  
  87.         switch (true) {
  88.             case !$isPublic && $type == 'publicKey':
  89.                 throw new \UnexpectedValueException('Human readable string claims non-public key but DER encoded string claims public key');
  90.             case $isPublic && $type == 'privateKey':
  91.                 throw new \UnexpectedValueException('Human readable string claims public key but DER encoded string claims private key');
  92.         }
  93.  
  94.         switch ($key[$type . 'Algorithm']['algorithm']) {
  95.             case 'id-Ed25519':
  96.             case 'id-Ed448':
  97.                 return self::loadEdDSA($key);
  98.         }
  99.  
  100.         $decoded = ASN1::decodeBER($key[$type . 'Algorithm']['parameters']->element);
  101.         if (!$decoded) {
  102.             throw new \RuntimeException('Unable to decode BER');
  103.         }
  104.         $params = ASN1::asn1map($decoded[0], Maps\ECParameters::MAP);
  105.         if (!$params) {
  106.             throw new \RuntimeException('Unable to decode the parameters using Maps\ECParameters');
  107.         }
  108.  
  109.         $components = [];
  110.         $components['curve'] = self::loadCurveByParam($params);
  111.  
  112.         if ($isPublic) {
  113.             $components['QA'] = self::extractPoint("\0" . $key['publicKey'], $components['curve']);
  114.  
  115.             return $components;
  116.         }
  117.  
  118.         $decoded = ASN1::decodeBER($key['privateKey']);
  119.         if (!$decoded) {
  120.             throw new \RuntimeException('Unable to decode BER');
  121.         }
  122.         $key = ASN1::asn1map($decoded[0], Maps\ECPrivateKey::MAP);
  123.         if (isset($key['parameters']) && $params != $key['parameters']) {
  124.             throw new \RuntimeException('The PKCS8 parameter field does not match the private key parameter field');
  125.         }
  126.  
  127.         $components['dA'] = new BigInteger($key['privateKey'], 256);
  128.         $components['curve']->rangeCheck($components['dA']);
  129.         $components['QA'] = isset($key['publicKey']) ?
  130.             self::extractPoint($key['publicKey'], $components['curve']) :
  131.             $components['curve']->multiplyPoint($components['curve']->getBasePoint(), $components['dA']);
  132.  
  133.         return $components;
  134.     }
  135.  
  136.     /**
  137.      * Break a public or private EdDSA key down into its constituent components
  138.      *
  139.      * @return array
  140.      */
  141.     private static function loadEdDSA(array $key)
  142.     {
  143.         $components = [];
  144.  
  145.         if (isset($key['privateKey'])) {
  146.             $components['curve'] = $key['privateKeyAlgorithm']['algorithm'] == 'id-Ed25519' ? new Ed25519() : new Ed448();
  147.  
  148.             // 0x04 == octet string
  149.             // 0x20 == length (32 bytes)
  150.             if (substr($key['privateKey'], 0, 2) != "\x04\x20") {
  151.                 throw new \RuntimeException('The first two bytes of the private key field should be 0x0420');
  152.             }
  153.             $arr = $components['curve']->extractSecret(substr($key['privateKey'], 2));
  154.             $components['dA'] = $arr['dA'];
  155.             $components['secret'] = $arr['secret'];
  156.         }
  157.  
  158.         if (isset($key['publicKey'])) {
  159.             if (!isset($components['curve'])) {
  160.                 $components['curve'] = $key['publicKeyAlgorithm']['algorithm'] == 'id-Ed25519' ? new Ed25519() : new Ed448();
  161.             }
  162.  
  163.             $components['QA'] = self::extractPoint($key['publicKey'], $components['curve']);
  164.         }
  165.  
  166.         if (isset($key['privateKey']) && !isset($components['QA'])) {
  167.             $components['QA'] = $components['curve']->multiplyPoint($components['curve']->getBasePoint(), $components['dA']);
  168.         }
  169.  
  170.         return $components;
  171.     }
  172.  
  173.     /**
  174.      * Convert an EC public key to the appropriate format
  175.      *
  176.      * @param \phpseclib3\Crypt\EC\BaseCurves\Base $curve
  177.      * @param \phpseclib3\Math\Common\FiniteField\Integer[] $publicKey
  178.      * @param array $options optional
  179.      * @return string
  180.      */
  181.     public static function savePublicKey(BaseCurve $curve, array $publicKey, array $options = [])
  182.     {
  183.         self::initialize_static_variables();
  184.  
  185.         if ($curve instanceof MontgomeryCurve) {
  186.             throw new UnsupportedCurveException('Montgomery Curves are not supported');
  187.         }
  188.  
  189.         if ($curve instanceof TwistedEdwardsCurve) {
  190.             return self::wrapPublicKey(
  191.                 $curve->encodePoint($publicKey),
  192.                 null,
  193.                 $curve instanceof Ed25519 ? 'id-Ed25519' : 'id-Ed448'
  194.             );
  195.         }
  196.  
  197.         $params = new ASN1\Element(self::encodeParameters($curve, false, $options));
  198.  
  199.         $key = "\4" . $publicKey[0]->toBytes() . $publicKey[1]->toBytes();
  200.  
  201.         return self::wrapPublicKey($key, $params, 'id-ecPublicKey');
  202.     }
  203.  
  204.     /**
  205.      * Convert a private key to the appropriate format.
  206.      *
  207.      * @param \phpseclib3\Math\BigInteger $privateKey
  208.      * @param \phpseclib3\Crypt\EC\BaseCurves\Base $curve
  209.      * @param \phpseclib3\Math\Common\FiniteField\Integer[] $publicKey
  210.      * @param string $secret optional
  211.      * @param string $password optional
  212.      * @param array $options optional
  213.      * @return string
  214.      */
  215.     public static function savePrivateKey(BigInteger $privateKey, BaseCurve $curve, array $publicKey, $secret = null, $password = '', array $options = [])
  216.     {
  217.         self::initialize_static_variables();
  218.  
  219.         if ($curve instanceof MontgomeryCurve) {
  220.             throw new UnsupportedCurveException('Montgomery Curves are not supported');
  221.         }
  222.  
  223.         if ($curve instanceof TwistedEdwardsCurve) {
  224.             return self::wrapPrivateKey(
  225.                 "\x04\x20" . $secret,
  226.                 [],
  227.                 null,
  228.                 $password,
  229.                 $curve instanceof Ed25519 ? 'id-Ed25519' : 'id-Ed448'
  230.             );
  231.         }
  232.  
  233.         $publicKey = "\4" . $publicKey[0]->toBytes() . $publicKey[1]->toBytes();
  234.  
  235.         $params = new ASN1\Element(self::encodeParameters($curve, false, $options));
  236.  
  237.         $key = [
  238.             'version' => 'ecPrivkeyVer1',
  239.             'privateKey' => $privateKey->toBytes(),
  240.             //'parameters' => $params,
  241.             'publicKey' => "\0" . $publicKey
  242.         ];
  243.  
  244.         $key = ASN1::encodeDER($key, Maps\ECPrivateKey::MAP);
  245.  
  246.         return self::wrapPrivateKey($key, [], $params, $password, 'id-ecPublicKey', '', $options);
  247.     }
  248. }
  249.