Example #1
0
 /**
  * @param $base64
  * @return array
  */
 public function unserialize($base64)
 {
     $binary = base64_decode($base64, true);
     if ($binary === false) {
         throw new \InvalidArgumentException('Invalid base64');
     }
     $values = [];
     $pos = 0;
     $end = strlen($binary);
     for ($i = 0; $i < 3; $i++) {
         if ($end - $pos < 4) {
             throw new \RuntimeException('Length marker too short');
         }
         $length = unpack("N", substr($binary, $pos, 4))[1];
         $pos += 4;
         if ($end - $pos < $length) {
             throw new \RuntimeException('Not enough data');
         }
         $value = substr($binary, $pos, $length);
         $pos += $length;
         $values[$i] = $value;
     }
     $curveName = $values[1];
     $pointHex = unpack("H*", $values[2])[1];
     $curve = Curves::curve($curveName);
     $generator = Curves::generator($curveName);
     $point = $this->pointSerializer->unserialize($curve, $pointHex);
     $publicKey = new PublicKey($this->math, $generator, $point);
     return [$curve, $publicKey];
 }
 /**
  * @dataProvider getVectors
  * @param string $curveName
  * @param string|int $multiplier
  * @param string $expectedPub
  */
 public function testSerialize($curveName, $multiplier, $expectedPub)
 {
     /** @var GeneratorPoint $generator */
     $generator = Curves::generator($curveName);
     $privateKey = $generator->getPrivateKeyFrom(gmp_init($multiplier, 10));
     $public = $privateKey->getPublicKey();
     $adapter = EccFactory::getAdapter();
     $serializer = new SshPublicKeySerializer($adapter, new UncompressedPointSerializer($adapter));
     $serialized = $serializer->serialize($curveName, $public);
     $this->assertEquals($expectedPub, $serialized);
     list($curve, $publicKey) = $serializer->unserialize($serialized);
     $this->assertTrue($public->getPoint()->equals($publicKey->getPoint()));
 }
Example #3
0
 /**
  * @expectedException \InvalidArgumentException
  * @expectedExceptionMessage Unknown or unsupported generator
  */
 public function testRejectsInvalidGenerator()
 {
     Curves::generator('not-a-curve');
 }
 /**
  * @expectedException \RuntimeException
  */
 public function testSerializeFailsToEncrypt()
 {
     /** @var GeneratorPoint $generator */
     $generator = Curves::generator('nistp256');
     $privateKey = $generator->getPrivateKeyFrom(gmp_init('1'));
     $method = 'not-a-method';
     $iv = random_bytes(16);
     $cryptKey = new EncryptedPrivateKey($privateKey, $method, $iv);
     $adapter = EccFactory::getAdapter();
     $serializer = new EncryptedPrivateKeySerializer(new DerPrivateKeySerializer($adapter));
     $serializer->serialize($cryptKey, 'password');
 }