/** * @param GeneratorPoint $G * @param $hash * @return int|string */ public function truncateHash(GeneratorPoint $G, $hash) { $hexSize = strlen($this->adapter->decHex($hash)); $hashBits = $this->adapter->baseConvert($hash, 10, 2); if (strlen($hashBits) < $hexSize * 4) { $hashBits = str_pad($hashBits, $hexSize * 4, '0', STR_PAD_LEFT); } $messageHash = $this->adapter->baseConvert(substr($hashBits, 0, NumberSize::bnNumBits($this->adapter, $G->getOrder())), 2, 10); return $messageHash; }
/** * @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'); }
/** * @param $a * @param $b * @param $cond */ public function cswapValue(&$a, &$b, $cond) { $size = max(strlen($this->adapter->baseConvert($a, 10, 2)), strlen($this->adapter->baseConvert($b, 10, 2))); $mask = 1 - intval($cond); $mask = str_pad('', $size, $mask, STR_PAD_LEFT); $mask = $this->adapter->baseConvert($mask, 2, 10); $tA = $this->adapter->bitwiseAnd($a, $mask); $tB = $this->adapter->bitwiseAnd($b, $mask); $a = $this->adapter->bitwiseXor($this->adapter->bitwiseXor($a, $b), $tB); $b = $this->adapter->bitwiseXor($this->adapter->bitwiseXor($a, $b), $tA); $a = $this->adapter->bitwiseXor($this->adapter->bitwiseXor($a, $b), $tB); }