[ Index ]

PHP Cross Reference of DokuWiki

title

Body

[close]

/vendor/phpseclib/phpseclib/phpseclib/Crypt/DH/Formats/Keys/ -> PKCS1.php (source)

   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   * @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  
  22  namespace phpseclib3\Crypt\DH\Formats\Keys;
  23  
  24  use phpseclib3\Crypt\Common\Formats\Keys\PKCS1 as Progenitor;
  25  use phpseclib3\File\ASN1;
  26  use phpseclib3\File\ASN1\Maps;
  27  use phpseclib3\Math\BigInteger;
  28  
  29  /**
  30   * "PKCS1" Formatted DH Key Handler
  31   *
  32   * @author  Jim Wigginton <terrafrost@php.net>
  33   */
  34  abstract class PKCS1 extends Progenitor
  35  {
  36      /**
  37       * Break a public or private key down into its constituent components
  38       *
  39       * @param string $key
  40       * @param string $password optional
  41       * @return array
  42       */
  43      public static function load($key, $password = '')
  44      {
  45          $key = parent::load($key, $password);
  46  
  47          $decoded = ASN1::decodeBER($key);
  48          if (!$decoded) {
  49              throw new \RuntimeException('Unable to decode BER');
  50          }
  51  
  52          $components = ASN1::asn1map($decoded[0], Maps\DHParameter::MAP);
  53          if (!is_array($components)) {
  54              throw new \RuntimeException('Unable to perform ASN1 mapping on parameters');
  55          }
  56  
  57          return $components;
  58      }
  59  
  60      /**
  61       * Convert EC parameters to the appropriate format
  62       *
  63       * @return string
  64       */
  65      public static function saveParameters(BigInteger $prime, BigInteger $base, array $options = [])
  66      {
  67          $params = [
  68              'prime' => $prime,
  69              'base' => $base
  70          ];
  71          $params = ASN1::encodeDER($params, Maps\DHParameter::MAP);
  72  
  73          return "-----BEGIN DH PARAMETERS-----\r\n" .
  74                 chunk_split(base64_encode($params), 64) .
  75                 "-----END DH PARAMETERS-----\r\n";
  76      }
  77  }