Example #1
0
 /**
  * Initialize private key from PEM.
  *
  * @param PEM $pem
  * @throws \UnexpectedValueException
  * @return self
  */
 public static function fromPEM(PEM $pem)
 {
     switch ($pem->type()) {
         case PEM::TYPE_RSA_PRIVATE_KEY:
             return RSAPrivateKey::fromDER($pem->data());
         case PEM::TYPE_EC_PRIVATE_KEY:
             return ECPrivateKey::fromDER($pem->data());
         case PEM::TYPE_PRIVATE_KEY:
             return PrivateKeyInfo::fromDER($pem->data())->privateKey();
     }
     throw new \UnexpectedValueException("PEM type " . $pem->type() . " is not a valid private key.");
 }
Example #2
0
 /**
  * Get private key.
  *
  * @throws \RuntimeException
  * @return PrivateKey
  */
 public function privateKey()
 {
     $algo = $this->algorithmIdentifier();
     switch ($algo->oid()) {
         // RSA
         case AlgorithmIdentifier::OID_RSA_ENCRYPTION:
             return RSAPrivateKey::fromDER($this->_privateKeyData);
             // elliptic curve
         // elliptic curve
         case AlgorithmIdentifier::OID_EC_PUBLIC_KEY:
             $pk = ECPrivateKey::fromDER($this->_privateKeyData);
             // if private key doesn't encode named curve, assign from parameters
             if (!$pk->hasNamedCurve()) {
                 if (!$algo instanceof ECPublicKeyAlgorithmIdentifier) {
                     throw new \UnexpectedValueException("Not an EC algorithm.");
                 }
                 $pk = $pk->withNamedCurve($algo->namedCurve());
             }
             return $pk;
     }
     throw new \RuntimeException("Private key " . $algo->oid() . " not supported.");
 }
Example #3
0
 /**
  * Convert EC private key to PEM.
  *
  * @return PEM
  */
 public function toPEM()
 {
     $curve_oid = CurveParameter::nameToOID($this->curveParameter()->value());
     $x = ECConversion::octetsToNumber($this->XCoordinateParameter()->coordinateOctets());
     $y = ECConversion::octetsToNumber($this->YCoordinateParameter()->coordinateOctets());
     $pubkey = ECPublicKey::fromCoordinates($x, $y, $curve_oid);
     $priv = $this->ECCPrivateKeyParameter()->privateKeyOctets();
     $ec = new ECPrivateKey($priv, $curve_oid, $pubkey->ECPoint());
     return $ec->privateKeyInfo()->toPEM();
 }