Exemple #1
0
 /**
  * @param string $sealed encrypted value, base64 encoded
  * @param string $shareKey share key, base64 encoded
  * @param PrivateKey $private
  * @return null|string
  */
 public function unseal($sealed, $shareKey, PrivateKey $private)
 {
     $unsealed = null;
     if (openssl_open($this->decode($sealed), $unsealed, $this->decode($shareKey), $private->getResource())) {
         return $unsealed;
     }
     throw new \RuntimeException('Cannot unseal: ' . openssl_error_string());
 }
Exemple #2
0
 /**
  *
  */
 private function generate()
 {
     if ($this->request === null) {
         $commonName = iconv("UTF-8", "ASCII//TRANSLIT", $this->commonName);
         $privateKeyResource = $this->privateKey->asResource();
         $csr = openssl_csr_new(['CN' => substr($commonName, 0, 64), 'emailAddress' => $this->emailAddress], $privateKeyResource);
         $this->request = $csr;
     }
 }
Exemple #3
0
 /**
  * Used to create a public key from the given string.
  *
  * If a string containing a serialized public key is
  * not give, the framework default one will be used
  *
  * @param string|null $custom_key the public key serialized as a string
  *
  * @throws \InvalidArgumentException the given key isn't a valid serialized key
  * @throws AsymmetricException       the given key is invalid
  */
 public function __construct($custom_key = null)
 {
     $serialized_key = '';
     if (is_null($custom_key)) {
         //create the default private key
         $default_private_key = new PrivateKey();
         //and retrive the public key from the default private key
         $serialized_key = $default_private_key->retrivePublicKey();
     } elseif (is_string($custom_key)) {
         $serialized_key = $custom_key;
     } else {
         throw new \InvalidArgumentException('The serialized public key must be a string');
     }
     //load the public key
     $this->key = openssl_pkey_get_public($serialized_key);
     //check for errors
     if (!$this->isLoaded()) {
         throw new AsymmetricException('The public key could not be loaded', 2);
     }
 }
Exemple #4
0
 /**
  * @depnds testGenerateWithoutException
  */
 public function testIsValid()
 {
     $sinKey = new SinKey();
     $this->assertNotNull($sinKey);
     $this->assertFalse($sinKey->isValid());
     $pubKey = PublicKey::create();
     $this->assertNotNull($pubKey);
     $pubKey->setPrivateKey(PrivateKey::create()->generate());
     $pubKey->generate();
     $sinKey->setPublicKey($pubKey);
     $sinKey->generate();
     $this->assertTrue($sinKey->isValid());
 }
 /**
  * @depends testGenerate
  */
 public function testToString()
 {
     $pubKey = new PublicKey();
     $this->assertNotNull($pubKey);
     $pubKey->setPrivateKey(PrivateKey::create()->generate());
     $this->assertSame('', (string) $pubKey);
     $pubKey->generate(PrivateKey::create()->generate());
     if ('02' . $pubKey->getX() == $pubKey) {
         $compressed = '02' . $pubKey->getX();
     } else {
         $compressed = '03' . $pubKey->getX();
     }
     $this->assertSame($compressed, (string) $pubKey);
     $this->assertEquals(66, strlen((string) $pubKey));
 }
 public static function test_signature_validity($Msg, $Qx, $Qy, $R, $S, $expected, $verbose = false)
 {
     $p192 = NISTcurve::generator_192();
     $curve_192 = NISTcurve::curve_192();
     $pubk = new PublicKey($p192, new Point($curve_192, $Qx, $Qy));
     $got = $pubk->verifies(PrivateKey::digest_integer($Msg), new Signature($R, $S));
     if (bccomp($got, $expected) == 0) {
         if ($verbose) {
             print "Signature tested as expected: received " . var_export($got, true) . ", expected " . var_export($expected, true) . ".<br />";
         }
         flush();
     } else {
         print "*** Signature test failed: received " . var_export($got, true) . ", expected " . var_export($expected, true) . ".<br />";
     }
     flush();
 }
Exemple #7
0
 public function testGetPublicKey()
 {
     $key = new PrivateKey();
     $publicKey = $key->getPublicKey();
     $this->assertInstanceOf('Bitpay\\PublicKey', $publicKey);
 }
 /**
  * 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    array $inputs
  * @param    string $magic_byte
  * @return    array
  */
 public static function sign($wallet, $raw_transaction, $inputs, $magic_byte = '00')
 {
     // 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.
     //$wallet = BitcoinLib::private_keys_to_receive($priv_keys);
     $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);
         if (isset($wallet[$tx_info['hash160']])) {
             $key_info = $wallet[$tx_info['hash160']];
             $generator = \SECcurve::generator_secp256k1();
             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) {
                     $point = new \Point($generator->getCurve(), gmp_init(substr($key['uncompressed_key'], 2, 64), 16), gmp_init(substr($key['uncompressed_key'], 66, 64), 16), $generator->getOrder());
                     $_public_key = new \PublicKey($generator, $point);
                     $_private_key = new \PrivateKey($_public_key, gmp_init($key['private_key'], 16));
                     $sign = $_private_key->sign(gmp_init($message_hash[$vin], 16), gmp_init((string) bin2hex(openssl_random_pseudo_bytes(32)), 16));
                     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') {
                 // Create Signature
                 $point = new \Point($generator->getCurve(), gmp_init(substr($key_info['uncompressed_key'], 2, 64), 16), gmp_init(substr($key_info['uncompressed_key'], 66, 64), 16), $generator->getOrder());
                 $_public_key = new \PublicKey($generator, $point);
                 $_private_key = new \PrivateKey($_public_key, gmp_init($key_info['private_key'], 16));
                 $sign = $_private_key->sign(gmp_init($message_hash[$vin], 16), gmp_init((string) bin2hex(openssl_random_pseudo_bytes(32)), 16));
                 if ($sign !== FALSE) {
                     $sign_count++;
                     $decode['vin'][$vin]['scriptSig']['hex'] = self::_apply_sig_pubkeyhash(self::encode_signature($sign), $key_info['public_key']);
                 }
                 $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) == TRUE ? 'true' : 'false' : 'false';
     return array('hex' => $new_raw, 'complete' => $complete);
 }
Exemple #9
0
 /**
  * @param $concatenated
  * @return PushCertificate
  */
 public static function fromString($concatenated)
 {
     list($signedCertificate, $privateKey) = explode('-' . PHP_EOL . '-', $concatenated);
     return new self(PrivateKey::fromString('-' . $privateKey), new SignedCertificate($signedCertificate . '-' . PHP_EOL));
 }
Exemple #10
0
 /**
  * @group certificate
  *
  * @test
  * @expectedException \SAML2\Exception\InvalidArgumentException
  */
 public function test_create_with_nonstring_password_throws_exception()
 {
     $key = \SAML2\CertificatesMock::getPlainPrivateKey();
     PrivateKey::create($key, 1);
 }
Exemple #11
0
 public function sign_transaction($transaction, $inputs)
 {
     // Initialize
     $bip32 = new bip32();
     // Start transaction
     $transaction[] = '01000000';
     $orig_transaction = $transaction;
     // Add inputs temporarily
     $temp_input = 3;
     foreach ($inputs as $input) {
         // Set transaction variables
         $temp_transaction = $orig_transaction;
         if (count($input['privkeys']) > 1) {
             $temp_transaction[$temp_input] = $this->encode_vint(strlen(hex2bin($input['scriptsig'])));
             $temp_transaction[$temp_input + 1] = $input['scriptsig'];
         } else {
             $temp_transaction[$temp_input] = dechex(strlen(hex2bin($input['scriptsig'])));
             $temp_transaction[$temp_input + 1] = $input['scriptsig'];
         }
         // Initialize
         $generator = SECcurve::generator_secp256k1();
         // Hash structure
         $temp_hex_trans = pack("H*", implode("", $temp_transaction));
         $hash = hash('sha256', hash('sha256', $temp_hex_trans, true));
         // Go through the keys
         $signatures = array();
         $total_sign = 0;
         foreach ($input['privkeys'] as $privkey) {
             // Get public key
             $import = $bip32->import($privkey);
             $pubkey = $bip32->private_to_public($import['key']);
             $cpubkey = $bip32->private_to_public($import['key'], true);
             // Get ready to sign
             $point = new Point($generator->getCurve(), gmp_init(substr($pubkey, 2, 64), 16), gmp_init(substr($pubkey, 66, 64), 16), $generator->getOrder());
             $_public_key = new PublicKey($generator, $point);
             $_private_key = new PrivateKey($_public_key, gmp_init($import['key'], 16));
             // Sign
             $sign = $_private_key->sign(gmp_init($hash, 16), gmp_init((string) bin2hex(openssl_random_pseudo_bytes(32)), 16));
             $signatures[$cpubkey] = $this->_encode_signature($sign);
             $total_sign++;
         }
         // Encode signature
         if (count($input['privkeys']) > 1) {
             $sig = '00';
             foreach ($signatures as $pubkey => $sign) {
                 $sig .= $this->encode_vint(strlen($sign) / 2) . $sign;
             }
             $sig .= '4c' . $this->encode_vint(strlen($input['scriptsig']) / 2) . $input['scriptsig'];
         } else {
             $key = array_keys($signatures)[0];
             $sig = $this->encode_vint(strlen($signatures[$key]) / 2) . $signatures[$key];
             $sig .= $this->encode_vint(strlen($key) / 2) . $key;
         }
         // Add to transaction
         $transaction[$temp_input] = $this->encode_vint(strlen(hex2bin($sig)));
         $transaction[$temp_input + 1] = $sig;
         $temp_input += 4;
     }
     array_pop($transaction);
     // Return
     return implode("", $transaction);
 }
Exemple #12
0
 /**
  * Generate a digital signature for the given message.
  * 
  * The digital signature can be used to authenticate the message because
  * a different message will produce a different digital signature.
  * 
  * You will be using the public key corresponding to the given private key
  * to check the digital signature.
  * 
  * Example usage:
  * <code>
  * $message = "who knows if this message will be modified.....";
  * 
  * //get the default private key
  * $privKey = new PrivateKey();
  * 
  * //generate the digital signature
  * $signature = Cryptography::generateDigitalSignature($privKey, $message);
  * 
  * //transmit the digital signature
  * </code>
  * 
  * @param PrivateKey $key     the priate key to be used to generate the message
  * @param string     $message the message to be signed
  *
  * @return string the generate digital signature
  *
  * @throws \InvalidArgumentException the given message is not a valid string
  * @throws AsymmetricException       the error occurred while generating the message
  */
 public static function generateDigitalSignature(PrivateKey &$key, $message)
 {
     //check the message type
     if (!is_string($message) && strlen($message) <= 0) {
         throw new \InvalidArgumentException('The message to be signed must be a non-empty string');
     }
     //check for the private key
     if (!$key->isLoaded()) {
         throw new AsymmetricException('It is impossible to generate a digital signature with an unloaded key', 11);
     }
     //get the managed version of the native key
     $managedKey = $key();
     //generate the digital signature
     $digitalSignature = null;
     if (!openssl_sign($message, $digitalSignature, $managedKey['key'], 'sha256WithRSAEncryption')) {
         throw new AsymmetricException('It is impossible to generate the digital signature due to an unknown error', 12);
     }
     //return the signature in a binary-safe format
     return base64_encode($digitalSignature);
 }