Example #1
8
 public function verify($password, $hash)
 {
     $key = hash(self::HASH_PRIMITIVE, $password, true);
     $hash = base64_decode($hash);
     $header = substr($hash, 0, self::HEADER_SIZE);
     $iv = substr($hash, self::HEADER_SIZE, self::IV_LENGTH);
     $ciphertext = substr($hash, self::HEADER_SIZE + self::IV_LENGTH);
     $decrypted = openssl_decrypt($ciphertext, self::CIPHER_PRIMITIVE, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
     list(, $version, $rounds, $pointerSize, $dataSize) = unpack('C*', $header);
     $iterationCount = pow(2, $rounds);
     $dataSizeDecoded = pow(2, $dataSize);
     if ($version !== 1) {
         throw new \RuntimeException("Unknown version encountered");
     }
     if (strlen($decrypted) !== self::HASH_LENGTH + $iterationCount * $pointerSize) {
         throw new \RuntimeException("Invalid data payload, was it truncated?");
     }
     $h = hash_init(self::HASH_PRIMITIVE);
     for ($i = 0; $i < $iterationCount; $i++) {
         $pointer = substr($decrypted, $i * $pointerSize, $pointerSize);
         hash_update($h, $this->read($pointer, $dataSizeDecoded));
     }
     $test = hash_final($h, true);
     return hash_equals($test, substr($decrypted, $iterationCount * $pointerSize));
 }
 protected function doBackup($stream, $tables, $gzip = false)
 {
     $db = Am_Di::getInstance()->db;
     $stream_filter = null;
     $hash = null;
     $len = 0;
     if ($gzip) {
         $hash = hash_init('crc32b');
         // gzip file header
         fwrite($stream, $this->getGzHeader());
         if (!($stream_filter = stream_filter_append($stream, "zlib.deflate", STREAM_FILTER_WRITE, self::COMPRESSION_LEVEL))) {
             throw new Am_Exception_InternalError("Could not attach gzencode filter to output stream");
         }
     }
     $this->out($stream, "### aMember Pro " . AM_VERSION . " database backup\n", $len, $hash);
     $this->out($stream, "### Created: " . date('Y-m-d H:i:s') . "\n", $len, $hash);
     foreach ($tables as $table) {
         $this->out($stream, "\n\nDROP TABLE IF EXISTS {$table};\n", $len, $hash);
         $r = $db->selectRow("SHOW CREATE TABLE {$table}");
         $this->out($stream, $r['Create Table'] . ";\n", $len, $hash);
         $q = $db->queryResultOnly("SELECT * FROM {$table}");
         while ($a = $db->fetchRow($q)) {
             $fields = join(',', array_keys($a));
             $values = join(',', array_map(array($db, 'escape'), array_values($a)));
             $this->out($stream, "INSERT INTO {$table} ({$fields}) VALUES ({$values});\n", $len, $hash);
         }
         $db->freeResult($q);
     }
     if ($stream_filter) {
         stream_filter_remove($stream_filter);
         fwrite($stream, $this->getGzFooter($len, $hash));
     }
     return $stream;
 }
Example #3
0
 public static function create_hash($data)
 {
     $hash = Config::get('hash');
     $context = hash_init($hash['hash_algorithm'], HASH_HMAC, $hash['hash_general_key']);
     hash_update($context, $data);
     return hash_final($context);
 }
Example #4
0
 /**
  * Аутентификация пользователя
  *
  * @param   String    $login
  * @param   String    $password
  * @param   Bool      $admin
  * @return  Bool
  */
 protected function _auth($login, $password, $admin, $protocol)
 {
     $packet = $this->packet();
     while (!feof($this->_socket)) {
         $packet->clean();
         $this->read($packet);
         switch ($this->_code) {
             case 192:
                 $digest = $packet->attr[6]['data'];
                 $ctx = hash_init('md5');
                 hash_update($ctx, $digest);
                 hash_update($ctx, $password);
                 $hash = hash_final($ctx, true);
                 $packet->clean();
                 $this->_code = 193;
                 $packet->set_attr_string($login, 2);
                 $packet->set_attr_string($digest, 8);
                 $packet->set_attr_string($hash, 9);
                 $packet->set_attr_int($protocol === 'tls' ? 6 : ($admin ? 4 : 2), 10);
                 $packet->set_attr_int(2, 1);
                 $this->write($packet);
                 break;
             case 194:
                 $attr_protocol = $packet->get_attr_int(10);
                 if ($attr_protocol === 6) {
                     stream_socket_enable_crypto($this->_socket, TRUE, STREAM_CRYPTO_METHOD_TLS_CLIENT);
                 } elseif ($attr_protocol) {
                     stream_socket_enable_crypto($this->_socket, TRUE, STREAM_CRYPTO_METHOD_SSLv3_CLIENT);
                 }
                 return TRUE;
             case 195:
                 return FALSE;
         }
     }
 }
Example #5
0
 public function process(AssetInterface $asset)
 {
     $hash = hash_init('sha1');
     switch ($this->strategy) {
         case self::STRATEGY_MODIFICATION:
             hash_update($hash, $asset->getLastModified());
             break;
         case self::STRATEGY_CONTENT:
             hash_update($hash, $asset->dump());
             break;
     }
     foreach ($asset as $i => $leaf) {
         if ($sourcePath = $leaf->getSourcePath()) {
             hash_update($hash, $sourcePath);
         } else {
             hash_update($hash, $i);
         }
     }
     $hash = substr(hash_final($hash), 0, 7);
     $url = $asset->getTargetPath();
     $oldExt = pathinfo($url, PATHINFO_EXTENSION);
     $newExt = '-' . $hash . '.' . $oldExt;
     if (!$oldExt || 0 < preg_match('/' . preg_quote($newExt, '/') . '$/', $url)) {
         return;
     }
     $asset->setTargetPath(substr($url, 0, (strlen($oldExt) + 1) * -1) . $newExt);
 }
Example #6
0
 public function getBaseMaterial($seedBytes)
 {
     $mac = hash_init('sha256', HASH_HMAC, $this->key);
     hash_update($mac, $seedBytes);
     $data = hash_final($mac, true);
     return $data;
 }
 public function hash()
 {
     $hasher = hash_init('sha256');
     hash_update($hasher, 'identifier');
     hash_update($hasher, $this->val);
     return hash_final($hasher);
 }
Example #8
0
function create_git_object_hash( $p_file ) {
	$t_hash_context = hash_init( 'sha1' );
	hash_update( $t_hash_context, 'blob ' . filesize( $p_file ) . "\x00" );
	hash_update_file( $t_hash_context, $p_file );
	$t_object_hash = hash_final( $t_hash_context );
	return $t_object_hash;
}
Example #9
0
 public static function getHash($algoritmo, $data, $key)
 {
     // $key refuerza la encriptación.
     $hash = hash_init($algoritmo, HASH_HMAC, $key);
     hash_update($hash, $data);
     return hash_final($hash);
 }
Example #10
0
 public function getHashContext()
 {
     if (!isset($this->_hashContext)) {
         $this->_hashContext = hash_init("md5");
     }
     return $this->_hashContext;
 }
 public function testBindWithPlaceholder_Constant()
 {
     $context = hash_init('md2');
     $hash = partial_any('hash_update', $context, …());
     $hash('oh hi');
     $this->assertSame('6f24cbf6005b9bfc0176abbbe309f0d0', hash_final($context));
 }
function test_hash($algo, $init)
{
    echo "\n{$algo}, incremental: ";
    $h = hash_init($algo);
    for ($i = 0; $i < 10; ++$i) {
        hash_update($h, '' . $init * 2 + $i * 17);
    }
    echo '(copying state) ';
    $h2 = hash_copy($h);
    for ($i = 0; $i < 10; ++$i) {
        hash_update($h, '' . $init * 2 + $i * 19);
    }
    var_dump(hash_final($h));
    echo "\n{$algo}, from copied state: ";
    var_dump(hash_final($h2));
    echo "\n{$algo}, HMAC, incremental: ";
    $h = hash_init($algo, HASH_HMAC, 'HMAC key. It can be very long, but in this case it will be rehashed to fit the block size of the hashing algorithm...' . $init * 147);
    for ($i = 0; $i < 10; ++$i) {
        hash_update($h, '' . $init * 4 + $i * 7);
    }
    //echo '(copying state) ';
    //$h2 = hash_copy($h);// causes PHP crashes sometimes, reported as PHP Bug #52240
    for ($i = 0; $i < 10; ++$i) {
        hash_update($h, '' . $init * 3 + $i * 11);
    }
    var_dump(hash_final($h));
    //echo "\n$algo, HMAC, from copied state: ";
    //var_dump(hash_final($h2));// BUG IN PHP, HMAC key is not copied, but only referenced ... hash_final on $h clears the HMAC key in $h2 too...  reported as PHP Bug #52240
    echo "\n{$algo}, at once, short data: ";
    var_dump(hash($algo, 'some string to be hashed ... ' . $init * 123 . ' ...'));
    echo "\n{$algo}, at once, HMAC: ";
    var_dump(hash_hmac($algo, 'some string to be hashed ... ' . $init * 123 . ' ...', 'HMAC key. It can be very long, but in this case it will be rehashed to fit the block size of the hashing algorithm.'));
}
Example #13
0
 /**
  * Compute a full md5 file hash or compute a partial hash if $limit is present.
  * Returns null on failure.
  *
  * @param string  $realPath
  * @param int     $offset in bytes
  * @param int     $limit  in bytes
  * @param boolean $forcePartialHashing
  *
  * @return null|string
  */
 public function computeMd5Hash($realPath, $offset = 0, $limit = 0, $forcePartialHashing = false)
 {
     if ($limit === 0 && $offset === 0 && !$forcePartialHashing) {
         // md5_file is always faster if we don't chunk the file
         $hash = md5_file($realPath);
         return $hash !== false ? $hash : null;
     }
     $ctx = hash_init('md5');
     if (!$ctx) {
         // Fail to initialize file hashing
         return null;
     }
     // Calculate limit from file size and offset
     if ($limit === 0) {
         $limit = filesize($realPath) - $offset;
     }
     $fh = @fopen($realPath, "rb");
     if ($fh === false) {
         // Failed opening file, cleanup hash context
         hash_final($ctx);
         return null;
     }
     fseek($fh, $offset);
     while ($limit > 0) {
         // Limit chunk size to either our remaining chunk or max chunk size
         $chunkSize = $limit < $this->maxChunkByteSize ? $limit : $this->maxChunkByteSize;
         $limit -= $chunkSize;
         $chunk = fread($fh, $chunkSize);
         hash_update($ctx, $chunk);
     }
     fclose($fh);
     return hash_final($ctx);
 }
Example #14
0
 public static function create($algo, $data, $salt)
 {
     $context = hash_init($algo, HASH_HMAC, $salt);
     //$salt => $key
     hash_update($context, $data);
     return hash_final($context);
 }
Example #15
0
function test_hash_init()
{
    $ctx = hash_init("md5");
    hash_update($ctx, "The quick brown fox ");
    hash_update($ctx, "jumped over the lazy dog.");
    var_dump(hash_final($ctx));
}
 function __construct($url, $options = array())
 {
     register_shutdown_function(array(&$this, "__destruct"));
     $ch = curl_init($url);
     $this->temp_name = $this->generateUsefulTempName($url);
     $this->temp_name_h = $this->generateTempName();
     $options = $this->curl_options + $options;
     $this->fp = fopen($this->temp_name, 'w');
     if (!$this->fp) {
         throw new Exception('Tempfile not writeable');
     }
     if ($this->canHash()) {
         $this->hash_context = hash_init('sha1');
         if (!$this->hash_context) {
             throw new Exception('Hash context creation failed');
         }
         $options[CURLOPT_WRITEFUNCTION] = array($this, 'write');
     } else {
         // need to hash in some other way here
         throw new Exception('Hash context unavailable');
         $options[CURLOPT_FILE] = $this->fp;
     }
     $this->fp_h = fopen($this->temp_name_h, 'w+');
     if (!$this->fp_h) {
         throw new Exception('Tempfile not writeable');
     }
     $options[CURLOPT_WRITEHEADER] = $this->fp_h;
     curl_setopt_array($ch, $options);
     $mh = curl_multi_init();
     curl_multi_add_handle($mh, $ch);
     $this->ch = $ch;
     $this->mh = $mh;
 }
 /**
  * Build a response header
  *
  * @param $buffer
  *    data to be used in response header
  * @return
  *    response header
  */
 static function getResponseHeaders($buffer = '', $uniqueOrigin = FALSE)
 {
     list($resource, $host, $origin, $strkey1, $strkey2, $data) = self::getRequestHeaders($buffer);
     if (!self::validOrigin($origin, $uniqueOrigin)) {
         self::console('Refusing connection from origin %s. Allowed origin(s): %s', array($origin, implode(', ', $uniqueOrigin)));
         return FALSE;
     }
     // find numbers
     $pattern = '/[^\\d]*/';
     $replacement = '';
     $numkey1 = preg_replace($pattern, $replacement, $strkey1);
     $numkey2 = preg_replace($pattern, $replacement, $strkey2);
     // find spaces
     $pattern = '/[^ ]*/';
     $replacement = '';
     $spaces1 = strlen(preg_replace($pattern, $replacement, $strkey1));
     $spaces2 = strlen(preg_replace($pattern, $replacement, $strkey2));
     if ($spaces1 == 0 || $spaces2 == 0 || $numkey1 % $spaces1 != 0 || $numkey2 % $spaces2 != 0) {
         WSHelpers::console('Handshake failed');
         return FALSE;
     }
     $ctx = hash_init('md5');
     hash_update($ctx, pack("N", $numkey1 / $spaces1));
     hash_update($ctx, pack("N", $numkey2 / $spaces2));
     hash_update($ctx, $data);
     $hash_data = hash_final($ctx, TRUE);
     return "HTTP/1.1 101 WebSocket Protocol Handshake\r\n" . "Upgrade: WebSocket\r\n" . "Connection: Upgrade\r\n" . "Sec-WebSocket-Origin: " . $origin . "\r\n" . "Sec-WebSocket-Location: ws://" . $host . $resource . "\r\n" . "\r\n" . $hash_data;
 }
Example #18
0
 function challengeCheck($call, $host1, $pass)
 {
     $h = hash_init('md5');
     hash_update($h, CallRegister::$calls[$host1][$call->fields['dcalli']]['challenge']);
     hash_update($h, $pass);
     return hash_final($h) == CallRegister::$calls[$host1][$call->fields['dcalli']]['challenge_response'];
 }
Example #19
0
 /**
  * Constructs a new hash calculator using the given hashing method.
  * @param string The hashingmethod to be used
  */
 public final function __construct($hashingMethod = \System\Security\Hash::HASH_SHA1)
 {
     if (self::isHashAlgorithmInstalled($hashingMethod)) {
         $this->hash = hash_init($hashingMethod);
     } else {
         throw new \InvalidArgumentException('Given hash method is not installed.');
     }
 }
Example #20
0
 /**
  * Get a hash context or create one if needed
  *
  * @return resource
  */
 private function getContext()
 {
     if (!$this->context) {
         $key = isset($this->options['key']) ? $this->options['key'] : null;
         $this->context = hash_init($this->algo, $key ? HASH_HMAC : 0, $key);
     }
     return $this->context;
 }
Example #21
0
 /**
  * @see VerifyInterface::init
  */
 public function init($algorithm, $path)
 {
     $algorithm = strtolower(preg_replace('/[^A-Za-z0-9]+/', '', $algorithm));
     if (false === ($this->context = @hash_init($algorithm))) {
         $this->context = null;
         throw SignatureException::lastError();
     }
 }
Example #22
0
 private function generateChannelSign($secret, $user, $channel, $info = '')
 {
     $ctx = hash_init('sha256', HASH_HMAC, $secret);
     hash_update($ctx, (string) $user);
     hash_update($ctx, (string) $channel);
     hash_update($ctx, (string) $info);
     return hash_final($ctx);
 }
Example #23
0
 /**
  * Generate hash value from string
  * @param merchantID
  * @param settlementmethod - how to settlement (Null or Blank → '00')
  * @param orderID
  * @param amount - Total Amount
  * @return hash value
  */
 public function generate($merchantID, $merchant_hash, $settlementmethod, $orderID, $amount)
 {
     $ctx = hash_init('sha512');
     $str = $merchant_hash . "," . $merchantID . "," . (is_null($settlementmethod) || strlen($settlementmethod) == 0 ? '00' : $settlementmethod) . "," . $orderID . "," . $amount;
     hash_update($ctx, $str);
     $hash = hash_final($ctx, true);
     return bin2hex($hash);
 }
Example #24
0
 /**
  * Generate hash value from string
  * @param merchant_id
  * @param merchant_hash_key
  * @param order_id
  * @return hash value
  */
 public static function generate($merchant_id, $merchant_hash_key, $order_id)
 {
     $ctx = hash_init('sha512');
     $str = $merchant_hash_key . "," . $merchant_id . "," . $order_id;
     hash_update($ctx, $str);
     $hash = hash_final($ctx, true);
     return bin2hex($hash);
 }
Example #25
0
 /**
  * Sign a message with a secure key.
  *
  * @param array $message_list
  *   The message list.
  *
  * @return string
  *   The signature for the message_list.
  */
 public function sign(array $message_list = array())
 {
     $hm = hash_init(static::getSignatureSchemes()[$this->getSignatureScheme()], HASH_HMAC, $this->getSecureKey());
     foreach ($message_list as $item) {
         hash_update($hm, $item);
     }
     return hash_final($hm);
 }
Example #26
0
 /** @return resource */
 function …()
 {
     static $resource;
     if (!$resource) {
         $resource = hash_init('gost');
     }
     return $resource;
 }
Example #27
0
 private function sign(array $message_list)
 {
     $hm = hash_init($this->hashAlgorithm, HASH_HMAC, $this->key);
     foreach ($message_list as $item) {
         hash_update($hm, $item);
     }
     return hash_final($hm);
 }
 private function getHashResource()
 {
     if (!$this->hash) {
         $algorithm = $this->getAlgorithm();
         $this->hash = hash_init($algorithm);
     }
     return $this->hash;
 }
Example #29
0
 public function hash()
 {
     $hasher = hash_init('sha256');
     hash_update($hasher, $this->kind());
     hash_update($hasher, $this->name);
     hash_update($hasher, hashComplex($this->t_args));
     return hash_final($hasher);
 }
 /**
  * @param $resource
  *
  * @return string
  */
 public function hash($resource)
 {
     rewind($resource);
     $context = hash_init($this->algo);
     hash_update_stream($context, $resource);
     fclose($resource);
     return hash_final($context);
 }