/**
  * {@inheritDoc}
  * @see \Mdanter\Ecc\Serializer\PrivateKeySerializerInterface::parse()
  */
 public function parse($formattedKey)
 {
     $formattedKey = str_replace('-----BEGIN EC PRIVATE KEY-----', '', $formattedKey);
     $formattedKey = str_replace('-----END EC PRIVATE KEY-----', '', $formattedKey);
     $data = base64_decode($formattedKey);
     return $this->derSerializer->parse($data);
 }
Example #2
0
 /**
  * @return Binary
  */
 public function generateKey()
 {
     $generator = EccFactory::getNistCurves()->generator256();
     $key = $generator->createPrivateKey();
     $serializer = new DerPrivateKeySerializer();
     $serialized = $serializer->serialize($key);
     return new Binary($serialized);
 }
 /**
  * @param string $data
  * @param string $password
  * @return EncryptedPrivateKey
  */
 public function unserialize($data, $password)
 {
     $comments = [];
     $short = '';
     foreach (explode("\n", $data) as $line) {
         if (strpos($line, ":") !== false) {
             $comment = explode(":", $line);
             if (count($comment) === 2) {
                 $comments[$comment[0]] = trim($comment[1]);
             }
         } else {
             $short .= $line . "\n";
         }
     }
     if (!isset($comments['DEK-Info']) || !isset($comments['Proc-Type'])) {
         throw new \RuntimeException('Missing headers for encryption');
     }
     list($cipher, $iv) = $this->parseDekInfo($comments['DEK-Info']);
     list($proc1, $proc2) = $this->parseProcType($comments['Proc-Type']);
     $short = str_replace('-----BEGIN EC PRIVATE KEY-----', '', $short);
     $short = str_replace('-----END EC PRIVATE KEY-----', '', $short);
     $ciphertext = base64_decode($short);
     $key = md5($password . substr($iv, 0, 8), true);
     $result = openssl_decrypt($ciphertext, $cipher, $key, OPENSSL_RAW_DATA, $iv);
     if ($result === false) {
         throw new \RuntimeException('Decryption failed');
     }
     $privateKey = $this->derSerializer->parse($result);
     return new EncryptedPrivateKey($privateKey, $cipher, $iv);
 }
Example #4
0
 /**
  * {@inheritDoc}
  * @see \Mdanter\Ecc\Serializer\PrivateKeySerializerInterface::serialize()
  */
 public function getPrivateKeyInfo(PrivateKeyInterface $key)
 {
     $keyData = $this->serializer->serialize($key);
     $privateKeyInfo = new Sequence(new Integer(self::VERSION), new Sequence(new ObjectIdentifier(DerPublicKeySerializer::X509_ECDSA_OID), CurveOidMapper::getCurveOid($key->getPoint()->getCurve())), new OctetString(bin2hex($keyData)));
     return $privateKeyInfo;
 }