예제 #1
0
 /**
  * @param string $content
  * @param Binary $address
  * @param string $signature
  * @return bool
  * @throws \Exception
  */
 public function verify($content, Binary $address, $signature)
 {
     if (!strpos($signature, self::$SIGNATURE_GLUE)) {
         throw new \Exception('Invalid signature.');
     }
     list($r, $s) = explode(self::$SIGNATURE_GLUE, $signature);
     $math = MathAdapterFactory::getAdapter();
     $serializer = new DerPublicKeySerializer($math);
     $inflatedPublicKey = $this->deserialize($address->getData(), $serializer);
     $hash = $this->hash($content);
     $signer = new Signer($math);
     return $signer->verify($inflatedPublicKey, new Signature($r, $s), $hash);
 }
예제 #2
0
 /**
  *
  * @dataProvider getAdapters
  */
 public function testSecp256r1EquivalenceToNistP192(MathAdapterInterface $adapter)
 {
     $secpFactory = EccFactory::getSecgCurves($adapter);
     $nistFactory = EccFactory::getNistCurves($adapter);
     $signer = new Signer($adapter);
     $secret = $adapter->hexDec('DC51D3866A15BACDE33D96F992FCA99DA7E6EF0934E7097559C27F1614C88A7F');
     $secpKey = $secpFactory->generator256r1()->getPrivateKeyFrom($secret);
     $nistKey = $nistFactory->generator256()->getPrivateKeyFrom($secret);
     $randomK = RandomGeneratorFactory::getRandomGenerator()->generate($secpKey->getPoint()->getOrder());
     $message = RandomGeneratorFactory::getRandomGenerator()->generate($secpKey->getPoint()->getOrder());
     $sigSecp = $signer->sign($secpKey, $message, $randomK);
     $sigNist = $signer->sign($nistKey, $message, $randomK);
     $this->assertEquals($sigNist->getR(), $sigSecp->getR());
     $this->assertEquals($sigNist->getS(), $sigSecp->getS());
 }
예제 #3
0
 /**
  * @test
  *
  * @covers \Lcobucci\JWT\Signer\Ecdsa\EccAdapter::createSigningHash
  * @covers \Lcobucci\JWT\Signer\Ecdsa\EccAdapter::generatorPoint
  *
  * @uses \Lcobucci\JWT\Signer\Ecdsa\EccAdapter::__construct
  */
 public function createSigningHashShouldReturnTheSignerResult()
 {
     $signingHash = gmp_init(1, 10);
     $generatorPoint = $this->createMock(GeneratorPoint::class);
     $this->nistCurve->expects($this->once())->method('generator256')->willReturn($generatorPoint);
     $this->signer->expects($this->once())->method('hashData')->with($generatorPoint, 'sha256', 'testing')->willReturn($signingHash);
     $adapter = $this->createAdapter();
     self::assertSame($signingHash, $adapter->createSigningHash('testing', 'sha256'));
 }
예제 #4
0
 /**
  * @test
  *
  * @uses Lcobucci\JWT\Signer\Ecdsa::__construct
  * @uses Lcobucci\JWT\Signer\Key
  *
  * @covers Lcobucci\JWT\Signer\Ecdsa::doVerify
  * @covers Lcobucci\JWT\Signer\Ecdsa::createSigningHash
  * @covers Lcobucci\JWT\Signer\Ecdsa::extractSignature
  */
 public function doVerifyShouldDelegateToEcdsaSignerUsingPublicKey()
 {
     $signer = $this->getSigner();
     $key = new Key('testing');
     $publicKey = $this->getMock(PublicKeyInterface::class);
     $this->parser->expects($this->once())->method('getPublicKey')->with($key)->willReturn($publicKey);
     $this->adapter->expects($this->exactly(3))->method('hexDec')->willReturn('123');
     $this->signer->expects($this->once())->method('verify')->with($publicKey, $this->isInstanceOf(Signature::class), $this->isType('string'))->willReturn(true);
     $this->assertTrue($signer->doVerify('testing', 'testing2', $key));
 }
예제 #5
0
 /**
  * {@inheritdoc}
  */
 public function doVerify(string $expected, string $payload, Key $key) : bool
 {
     return $this->signer->verify($this->parser->getPublicKey($key), $this->extractSignature($expected), $this->createSigningHash($payload));
 }
예제 #6
0
 /**
  * @dataProvider getHmacTestSet
  * @param GeneratorPoint $G
  * @param integer $size
  * @param string $privKey
  * @param string $algo
  * @param string $message
  * @param string $eK expected K hex
  * @param string $eR expected R hex
  * @param string $eS expected S hex
  */
 public function testHmacSignatures(GeneratorPoint $G, $size, $privKey, $algo, $message, $eK, $eR, $eS)
 {
     //echo "Try {$test->curve} / {$test->algorithm} / '{$test->message}'\n";
     $math = $G->getAdapter();
     // Initialize private key and message hash (decimal)
     $privateKey = $G->getPrivateKeyFrom($math->hexDec($privKey));
     $hashHex = hash($algo, $message);
     $messageHash = $math->hexDec($hashHex);
     // Derive K
     $drbg = RandomGeneratorFactory::getHmacRandomGenerator($privateKey, $messageHash, $algo);
     $k = $drbg->generate($G->getOrder());
     $this->assertEquals($k, $math->hexdec($eK), 'k');
     $hexSize = strlen($hashHex);
     $hashBits = $math->baseConvert($messageHash, 10, 2);
     if (strlen($hashBits) < $hexSize * 4) {
         $hashBits = str_pad($hashBits, $hexSize * 4, '0', STR_PAD_LEFT);
     }
     $messageHash = $math->baseConvert(substr($hashBits, 0, NumberSize::bnNumBits($math, $G->getOrder())), 2, 10);
     $signer = new Signer($math);
     $sig = $signer->sign($privateKey, $messageHash, $k);
     // Should be consistent
     $this->assertTrue($signer->verify($privateKey->getPublicKey(), $sig, $messageHash));
     // R and S should be correct
     $sR = $math->hexDec($eR);
     $sS = $math->hexDec($eS);
     $this->assertSame($sR, $sig->getR(), "r {$sR} == " . $sig->getR());
     $this->assertSame($sS, $sig->getS(), "s {$sR} == " . $sig->getS());
 }
예제 #7
0
 /**
  * @dataProvider getAdaptersWithRand
  */
 public function testSignatureValidityWithGeneratedKeys(MathAdapterInterface $math, RandomNumberGeneratorInterface $rng)
 {
     $generator = EccFactory::getNistCurves($math)->generator192();
     $signer = new Signer($math);
     $privateKey = $generator->createPrivateKey();
     $publicKey = $privateKey->getPublicKey();
     $randomK = $rng->generate($privateKey->getPoint()->getOrder());
     $hash = $rng->generate($generator->getOrder());
     $signature = $signer->sign($privateKey, $hash, $randomK);
     $this->assertTrue($signer->verify($publicKey, $signature, $hash), 'Correctly validates valid hash.');
     $this->assertFalse($signer->verify($publicKey, $signature, $math->sub($hash, 1)), 'Correctly rejects tampered hash.');
 }
예제 #8
0
 /**
  * Sign
  *
  * This function accepts the same parameters as signrawtransaction.
  * $raw_transaction is a hex encoded string for an unsigned/partially
  * signed transaction. $inputs is an array, containing the txid/vout/
  * scriptPubKey/redeemscript. $priv_keys contains WIF keys.
  *
  * The function looks at each TxIn and tries to sign, if the hash160
  * belongs to a key specified in the wallet.
  *
  * @param   array  $wallet
  * @param   string $raw_transaction
  * @param   string $inputs
  * @param   string $magic_byte
  * @param   string $magic_p2sh_byte
  * @return  array
  */
 public static function sign($wallet, $raw_transaction, $inputs, $magic_byte = null, $magic_p2sh_byte = null)
 {
     $math = EccFactory::getAdapter();
     $generator = EccFactory::getSecgCurves($math)->generator256k1();
     $magic_byte = BitcoinLib::magicByte($magic_byte);
     $magic_p2sh_byte = BitcoinLib::magicP2SHByte($magic_p2sh_byte);
     // Generate digests of inputs to sign.
     $message_hash = self::_create_txin_signature_hash($raw_transaction, $inputs);
     $inputs_arr = (array) json_decode($inputs);
     // Generate an association of expected hash160's and related information.
     $decode = self::decode($raw_transaction);
     $req_sigs = 0;
     $sign_count = 0;
     foreach ($decode['vin'] as $vin => $input) {
         $scriptPubKey = self::_decode_scriptPubKey($inputs_arr[$vin]->scriptPubKey);
         $tx_info = self::_get_transaction_type($scriptPubKey, $magic_byte, $magic_p2sh_byte);
         if (isset($wallet[$tx_info['hash160']])) {
             $key_info = $wallet[$tx_info['hash160']];
             $message_hash_dec = $math->hexDec($message_hash[$vin]);
             if ($key_info['type'] == 'scripthash') {
                 $signatures = self::extract_input_signatures_p2sh($input, $message_hash[$vin], $key_info);
                 $sign_count += count($signatures);
                 // Create Signature
                 foreach ($key_info['keys'] as $key) {
                     $key_dec = $math->hexDec($key['private_key']);
                     $k = $math->hexDec((string) bin2hex(mcrypt_create_iv(32, \MCRYPT_DEV_URANDOM)));
                     $signer = new Signer($math);
                     $_private_key = $generator->getPrivateKeyFrom($key_dec);
                     $sign = $signer->sign($_private_key, $message_hash_dec, $k);
                     if ($sign !== false) {
                         $sign_count++;
                         $signatures[$key['public_key']] = self::encode_signature($sign);
                     }
                 }
                 $decode['vin'][$vin]['scriptSig']['hex'] = self::_apply_sig_scripthash_multisig($signatures, $key_info);
                 // Increase required # signature counter.
                 $req_sigs += $key_info['required_signature_count'];
             }
             if ($key_info['type'] == 'pubkeyhash') {
                 $key_dec = $math->hexDec($key_info['private_key']);
                 $signer = new Signer($math);
                 $_private_key = $generator->getPrivateKeyFrom($key_dec);
                 $sign = $signer->sign($_private_key, $message_hash_dec, $math->hexDec((string) bin2hex(mcrypt_create_iv(32, \MCRYPT_DEV_URANDOM))));
                 if ($sign !== false) {
                     $sign_count++;
                     $decode['vin'][$vin]['scriptSig']['hex'] = self::_apply_sig_pubkeyhash(self::encode_signature($sign), $key_info['public_key']);
                 }
                 $req_sigs++;
             }
         } else {
             $req_sigs++;
         }
     }
     $new_raw = self::encode($decode);
     // If the transaction isn't fully signed, return false.
     // If it's fully signed, perform signature verification, return true if valid, or invalid if signatures are incorrect.
     $complete = $req_sigs - $sign_count <= 0 ? self::validate_signed_transaction($new_raw, $inputs, $magic_byte, $magic_p2sh_byte) == true ? 'true' : 'false' : 'false';
     return array('hex' => $new_raw, 'complete' => $complete, 'sign_count' => $sign_count, 'req_sigs' => $req_sigs);
 }
 /**
  * @dataProvider getDeterministicSign2Data
  */
 public function testDeterministicSign2($curve, $size, $algo, $privKey, $message, $eK, $eR, $eS)
 {
     //echo "Try {$test->curve} / {$test->algorithm} / '{$test->message}'\n";
     $G = CurveFactory::getGeneratorByName($curve);
     // Initialize private key and message hash (decimal)
     $privateKey = $G->getPrivateKeyFrom($this->math->hexDec($privKey));
     $hashHex = hash($algo, $message);
     $messageHash = $this->math->hexDec($hashHex);
     // Derive K
     $drbg = RandomGeneratorFactory::getHmacRandomGenerator($privateKey, $messageHash, $algo);
     $k = $drbg->generate($G->getOrder());
     $this->assertEquals($this->math->hexdec($eK), $k, 'k');
     $hexSize = strlen($hashHex);
     $hashBits = $this->math->baseConvert($messageHash, 10, 2);
     if (strlen($hashBits) < $hexSize * 4) {
         $hashBits = str_pad($hashBits, $hexSize * 4, '0', STR_PAD_LEFT);
     }
     $messageHash = $this->math->baseConvert(substr($hashBits, 0, $size), 2, 10);
     $signer = new Signer($this->math);
     $sig = $signer->sign($privateKey, $messageHash, $k);
     // R and S should be correct
     $sR = $this->math->hexDec($eR);
     $sS = $this->math->hexDec($eS);
     $this->assertTrue($signer->verify($privateKey->getPublicKey(), $sig, $messageHash));
     $this->assertSame($sR, $sig->getR(), 'r');
     $this->assertSame($sS, $sig->getS(), 's');
 }
예제 #10
0
 /**
  * based on php-bitcoin-signature-routines implementation (which is based on bitcoinjs-lib's implementation)
  * which is SEC 1: Elliptic Curve Cryptography, section 4.1.6, "Public Key Recovery Operation"
  * http://www.secg.org/sec1-v2.pdf
  *
  * @param                $r
  * @param                $s
  * @param                $e
  * @param                $recoveryFlags
  * @param GeneratorPoint $G
  * @return bool|PublicKey
  */
 private static function recoverPubKey($r, $s, $e, $recoveryFlags, GeneratorPoint $G)
 {
     $math = EccFactory::getAdapter();
     $isYEven = ($recoveryFlags & 1) != 0;
     $isSecondKey = ($recoveryFlags & 2) != 0;
     $curve = $G->getCurve();
     $signature = new Signature($r, $s);
     // Precalculate (p + 1) / 4 where p is the field order
     $p_over_four = $math->div($math->add($curve->getPrime(), 1), 4);
     // 1.1 Compute x
     if (!$isSecondKey) {
         $x = $r;
     } else {
         $x = $math->add($r, $G->getOrder());
     }
     // 1.3 Convert x to point
     $alpha = $math->mod($math->add($math->add($math->pow($x, 3), $math->mul($curve->getA(), $x)), $curve->getB()), $curve->getPrime());
     $beta = $math->powmod($alpha, $p_over_four, $curve->getPrime());
     // If beta is even, but y isn't or vice versa, then convert it,
     // otherwise we're done and y == beta.
     if (($math->mod($beta, 2) == 0) == $isYEven) {
         $y = $math->sub($curve->getPrime(), $beta);
     } else {
         $y = $beta;
     }
     // 1.4 Check that nR is at infinity (implicitly done in constructor)
     $R = $G->getCurve()->getPoint($x, $y);
     $point_negate = function (PointInterface $p) use($math, $G) {
         return $G->getCurve()->getPoint($p->getX(), $math->mul($p->getY(), -1));
     };
     // 1.6.1 Compute a candidate public key Q = r^-1 (sR - eG)
     $rInv = $math->inverseMod($r, $G->getOrder());
     $eGNeg = $point_negate($G->mul($e));
     $Q = $R->mul($s)->add($eGNeg)->mul($rInv);
     // 1.6.2 Test Q as a public key
     $signer = new Signer($math);
     $Qk = new PublicKey($math, $G, $Q);
     if ($signer->verify($Qk, $signature, $e)) {
         return $Qk;
     }
     return false;
 }