public function testCreate()
 {
     $privateKey = CurveFactory::getGeneratorByName('nistp256')->getPrivateKeyFrom(gmp_init(100));
     $iv = random_bytes(16);
     $method = 'AES-128-CBC';
     $key = new EncryptedPrivateKey($privateKey, $method, $iv);
     $this->assertEquals($iv, $key->getIv());
     $this->assertEquals($method, $key->getMethod());
     $this->assertSame($privateKey, $key->getKey());
 }
 /**
  * @param EncryptedPrivateKey $key
  * @param string $password
  * @return string
  */
 public function serialize(EncryptedPrivateKey $key, $password)
 {
     $privateKey = $key->getKey();
     $iv = $key->getIv();
     $method = $key->getMethod();
     $plaintext = $this->derSerializer->serialize($privateKey);
     $key = md5($password . substr($iv, 0, 8), true);
     $ciphertext = openssl_encrypt($plaintext, $method, $key, OPENSSL_RAW_DATA, $iv);
     if (false === $ciphertext) {
         throw new \RuntimeException('Failed to encrypt key');
     }
     return "-----BEGIN EC PRIVATE KEY-----" . "\n" . "Proc-Type: 4,ENCRYPTED" . "\n" . "DEK-Info: " . strtoupper($method) . "," . strtoupper(unpack("H*", $iv)[1]) . "\n\n" . implode("\n", str_split(base64_encode($ciphertext), 64)) . "\n" . "-----END EC PRIVATE KEY-----";
 }
 public function testSerializeEncFail()
 {
     $iv = random_bytes(16);
     $method = 'AES-128-CBC';
     $password = false;
     /** @var GeneratorPoint $generator */
     $generator = Curves::generator('nistp256');
     $privateKey = $generator->getPrivateKeyFrom(gmp_init(1923123));
     $cryptKey = new EncryptedPrivateKey($privateKey, $method, $iv);
     $this->assertSame($privateKey, $cryptKey->getKey());
     $this->assertEquals($method, $cryptKey->getMethod());
     $this->assertEquals($iv, $cryptKey->getIv());
     $adapter = EccFactory::getAdapter();
     $serializer = new EncryptedPrivateKeySerializer(new DerPrivateKeySerializer($adapter));
     $serializer->serialize($cryptKey, $password);
 }
Beispiel #4
0
 /**
  * @param EncryptedPrivateKey $that
  * @return bool
  */
 public function equals(EncryptedPrivateKey $that)
 {
     return $this->getMethod() === $that->getMethod() && $this->getIv() === $that->getIv() && BinaryString::constantTimeCompare(gmp_strval($this->getKey()->getSecret(), 10), gmp_strval($that->getKey()->getSecret(), 10));
 }