* @copyright 2015 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib3\Crypt\RSA\Formats\Keys; use phpseclib3\Common\Functions\Strings; use phpseclib3\Crypt\Common\Formats\Keys\PKCS8 as Progenitor; use phpseclib3\File\ASN1; use phpseclib3\Math\BigInteger; /** * PKCS#8 Formatted RSA Key Handler * * @package RSA * @author Jim Wigginton * @access public */ abstract class PKCS8 extends Progenitor { /** * OID Name * * @var string * @access private */ const OID_NAME = 'rsaEncryption'; /** * OID Value * * @var string * @access private */ const OID_VALUE = '1.2.840.113549.1.1.1'; /** * Child OIDs loaded * * @var bool * @access private */ protected static $childOIDsLoaded = false; /** * Break a public or private key down into its constituent components * * @access public * @param string $key * @param string $password optional * @return array */ public static function load($key, $password = '') { if (!Strings::is_stringable($key)) { throw new \UnexpectedValueException('Key should be a string - not a ' . gettype($key)); } if (strpos($key, 'PUBLIC') !== false) { $components = ['isPublicKey' => true]; } elseif (strpos($key, 'PRIVATE') !== false) { $components = ['isPublicKey' => false]; } else { $components = []; } $key = parent::load($key, $password); if (isset($key['privateKey'])) { if (!isset($components['isPublicKey'])) { $components['isPublicKey'] = false; } $type = 'private'; } else { if (!isset($components['isPublicKey'])) { $components['isPublicKey'] = true; } $type = 'public'; } $result = $components + PKCS1::load($key[$type . 'Key']); if (isset($key['meta'])) { $result['meta'] = $key['meta']; } return $result; } /** * Convert a private key to the appropriate format. * * @access public * @param \phpseclib3\Math\BigInteger $n * @param \phpseclib3\Math\BigInteger $e * @param \phpseclib3\Math\BigInteger $d * @param array $primes * @param array $exponents * @param array $coefficients * @param string $password optional * @param array $options optional * @return string */ public static function savePrivateKey(BigInteger $n, BigInteger $e, BigInteger $d, array $primes, array $exponents, array $coefficients, $password = '', array $options = []) { $key = PKCS1::savePrivateKey($n, $e, $d, $primes, $exponents, $coefficients); $key = ASN1::extractBER($key); return self::wrapPrivateKey($key, [], null, $password, null, '', $options); } /** * Convert a public key to the appropriate format * * @access public * @param \phpseclib3\Math\BigInteger $n * @param \phpseclib3\Math\BigInteger $e * @param array $options optional * @return string */ public static function savePublicKey(BigInteger $n, BigInteger $e, array $options = []) { $key = PKCS1::savePublicKey($n, $e); $key = ASN1::extractBER($key); return self::wrapPublicKey($key, null); } }