function signUrl($unsignedUrl, $secretKey) { $parsedUrl = parse_url($unsignedUrl); $hmac_data = ""; parse_str($parsedUrl["query"], $output); ksort($output, SORT_STRING); $first = true; $sortedQuery = ""; foreach ($output as $key => $value) { if ($first) { $first = false; } else { $sortedQuery .= "&"; } $hmac_data .= $key . $value; $sortedQuery .= $key . "=" . urlencode($value); } $strToSign = $parsedUrl["path"] . "?" . $sortedQuery; //echo "<br> StrToSign: ".$strToSign; //get HMAC signature $hmac = new Crypt_HMAC($secretKey, "sha1"); $hmac_digest = $hmac->hash(trim($strToSign)); $binary_hmac = pack("H40", $hmac_digest); $base64_hmac = base64_encode($binary_hmac); return $unsignedUrl . "&awsSignature=" . urlencode($base64_hmac); }
static function generate_base64_hmac_sha1($secretkey, $strToSign) { $hmac = new Crypt_HMAC($secretkey, "sha1"); $hmac_digest = $hmac->hash(trim($strToSign)); $binary_hmac = pack("H40", $hmac_digest); return base64_encode($binary_hmac); }
public static function CreaUsuario($origen, $app, $usuario, $password, $tabla) { if ($origen->Request->Cookies["user_{$app}"] != null) { $data = $origen->Request->Cookies["user_{$app}"]->Value; $origen->Application->SecurityManager->ValidationKey = $origen->Request->Cookies["hash_{$app}"]->Value; if (($data = $origen->Application->SecurityManager->validateData($data)) !== false) { $data = unserialize($data); if (is_array($data) && count($data) === 3) { list($username, $address, $token) = $data; $sql = "SELECT {$password} FROM {$tabla} WHERE {$usuario} = :usuario"; $command = $origen->dbConexion->createCommand($sql); $command->bindValue(":usuario", $username); $resultado = $command->query(); if ($row = $resultado->read()) { if ($token === $row["{$password}"] && $token !== false && ($address = $origen->Request->UserHostAddress)) { $phphmac = new Crypt_HMAC($_SESSION["aleat"]); $password_c = $phphmac->hash($row["{$password}"]); $authManager = $origen->Application->getModule('auth'); $x = $authManager->login($username, $password_c, 3600); } } } } } }
public function btnAceptar_Clicked($sender, $param) { $authManager = $this->Application->getModule('auth'); if ($this->hidHMAC->Value != "") { $password = $this->hidHMAC->Value; } else { $phphmac = new Crypt_HMAC($this->Session["aleat"]); $password = $phphmac->hash(md5(strtoupper($this->txtAcceso->getText()))); } if ($authManager->login($this->txtUsuario->Text, $password, 3600)) { $this->RedireccionAcceso(); } else { $this->getClientScript()->registerBeginScript("error", "alert('Acceso incorrecto. Verifique su usuario / contraseña.');\n"); } }
/** * Revisa si el par (usuario, password) especificado es válido. * Método requerido por TDbUser. * @param string username * @param string password * @return boolean retorna verdadero si username and password son válidos, falso en cualquier otro caso. */ public function validateUser($username, $password) { $consulta = "SELECT " . $this->pass . " FROM " . $this->tabla . " WHERE " . $this->login . " = :login"; $command = $this->getDbConnection()->createCommand($consulta); $command->bindValue(":login", $username); $resultado = $command->query(); if ($row = $resultado->read()) { $phphmac = new Crypt_HMAC($_SESSION["aleat"]); if ($phphmac->hash($row[$this->pass]) == $password) { return true; } else { return false; } } else { return false; } }
break; default: $lang = 'italian'; break; } require("./lang.".$lang.".php"); $script_transl = $strScript["login_admin.php"]; if (isset($_POST['actionflag'])) { $form['Login']=filter_var(substr($_POST['Login'],0,30),FILTER_SANITIZE_MAGIC_QUOTES); // checkUser(); $result = gaz_dbi_get_row ($gTables['admin'], "Login", $form['Login']); if ($result) { require("../../library/include/HMAC.php"); $crypt = new Crypt_HMAC($result["Password"], 'md5'); $hmacPass = $crypt->hash($_COOKIE[session_name()]); if ($hmacPass == $_POST['Password']) { cleanMemberSession($result["Abilit"], $result["Login"], $result["Password"], $result["Access"], $result['enterprise_id'],$tp); $utspas = mktime(0,0,0, substr($result['datpas'],5,2), substr($result['datpas'],8,2), substr($result['datpas'], 0, 4)); $utsoggi = mktime(0,0,0,date("m"),date("d"),date("Y")) - $config->getValue('giornipass') * 86400; if($utspas < $utsoggi) { $message .= $result["Nome"]." ".$result["Cognome"].$script_transl[2]; if (! isset($_POST['Nuovapass'])) { $_POST['Nuovapass'] = ''; } if (! isset($_POST['Confepass'])) { $_POST['Confepass'] = ''; } if($_POST['Password'] != $_POST['Nuovapass'] and $_POST['Nuovapass'] == $_POST['Confepass'] and strlen($_POST['Nuovapass']) >= $config->getValue('psw_min_length') ) { gaz_dbi_put_row($gTables['admin'], "Login",$form['Login'],"datpas",date("Y-m-d H:i:s")); gaz_dbi_put_row($gTables['admin'], "Login",$form['Login'],"Password",$_POST['Nuovapass']);
function hmacsha1_pear($key,$data) { $Crypt_HMAC = new Crypt_HMAC($key, 'sha1'); return $Crypt_HMAC->hash($data); }
protected function sign($hParams) { $hParams['Version'] = $this->sVersion; $hParams['AWSAccessKeyId'] = $this->sKey; $hParams['Expires'] = date('c', time() + 120); $hParams['SignatureVersion'] = 1; // TODO redo this part $hSignedParams = $hParams; $aKeys = array_keys($hSignedParams); foreach ($aKeys as $i => $key) { $aKeys[$i] = strtolower($key); $hMap[strtolower($key)] = $key; } sort($aKeys); $sString = ''; foreach ($aKeys as $key) { $val = $hSignedParams[$hMap[$key]]; $sString .= $hMap[$key] . $val; } $oCrypt = new Crypt_HMAC($this->sSecret, 'sha1'); $sSignature = $oCrypt->hash($sString); $sSignature = $this->hex2b64($sSignature); $hParams['Signature'] = $sSignature; return $hParams; }
/** * Sign a string with the AWS secret key, return it raw. */ function s3_sign_auth_string($string) { $crypt_hmac = new Crypt_HMAC(AWS_SECRET_KEY, 'sha1'); $hashed = $crypt_hmac->hash($string); $signature = ''; for ($i = 0; $i < strlen($hashed); $i += 2) { $signature .= chr(hexdec(substr($hashed, $i, 2))); } return $signature; }
/** * Creates secured HMAC signature of the message parameters. * * Uses the hash_hmac function if available (PHP needs to be >= 5.1.2). * Otherwise it uses the PEAR/CRYP_HMAC library to sign and crypt the * message. Make sure you have at least one of the options working on your * system. * * @param string $message message to sign * * @access private * * @return string signed sha1 message hash */ private function hmac($mesgparams) { if (function_exists('hash_hmac')) { $hmac = hash_hmac('sha1', utf8_encode($mesgparams), $this->secretKey); $hmac = $this->encodeBase64($hmac); } else { require_once 'Crypt/HMAC.php'; $hashobj = new Crypt_HMAC($this->secretKey, "sha1"); $hmac = $this->encodeBase64($hashobj->hash(utf8_encode($mesgparams))); } return $hmac; }
} else { $confirm_password = mysql_real_escape_string($_REQUEST['crypt_confirm_password']); $new_password = mysql_real_escape_string($_REQUEST['crypt_new_password']); } if ($new_password == $confirm_password) { $username = mysql_real_escape_string($_REQUEST['username']); $auth_sql = "SELECT * FROM `{$config['tables']['users']}` WHERE `username` = '{$username}'"; $result = mysql_query($auth_sql); $user_record = mysql_fetch_assoc($result); if ($_REQUEST['no_js'] == 1) { $old_password = md5(mysql_real_escape_string($_REQUEST['old_password'])); $old_encrypted_pw = $user_record['password']; } else { $old_password = mysql_real_escape_string($_REQUEST['crypt_old_password']); $obj_crypt = new Crypt_HMAC($user_record['password']); $old_encrypted_pw = $obj_crypt->hash($_SESSION['challenge']); } if ($old_encrypted_pw == $old_password) { $change_sql = "UPDATE `{$config['tables']['users']}` SET `password` = '{$new_password}', `password_last_changed`= NOW() WHERE `username` = '{$username}'"; mysql_query($change_sql) or trigger_error(mysql_error()); $message = "Password changed!"; $success = true; } else { $message = "Username or old password is incorrect"; $success = false; } } else { $message = "New passwords do not match."; $success = false; } }
function hash_hmac($algo, $data, $key, $raw_output = false) { if (function_exists('mhash') && $algo == 'md5') { return $raw_output ? mhash(MHASH_MD5, $data, $key) : bin2hex(mhash(MHASH_MD5, $data, $key)); } include_once 'HMAC.php'; $hashobj = new Crypt_HMAC($key, $algo); return $raw_output ? pack('H*', $hashobj->hash($data)) : $hashobj->hash($data); }
<?php /* This test file implements the three test vectors as described in * RFC 2104 (http://rfc.net/rfc2104.html) */ require_once 'Crypt/HMAC.php'; $key = str_repeat(chr(0xb), 16); $crypt = new Crypt_HMAC($key, 'md5'); echo $crypt->hash('Hi There') . "\n"; $key = 'Jefe'; $crypt->setKey($key); echo $crypt->hash('what do ya want for nothing?') . "\n"; $key = str_repeat(chr(0xaa), 16); $data = str_repeat(chr(0xdd), 50); $crypt->setKey($key); echo $crypt->hash($data) . "\n";
function wfGetIMDBData($query = false, $callback = false, $count = 3) { global $wgMemc; require_once "../common/HMAC.php"; $query = urldecode($query); $secret_key = WISE_imdb_secretkey; $access_key = WISE_imdb_accesskey; $method = "Search"; $timestamp = date("c"); $timestamp = substr(strrev($timestamp), strpos($timestamp, "-") + 2); $timestamp = strrev($timestamp) . "Z"; $string = $method . $timestamp; $hmac = new Crypt_HMAC($secret_key, "sha1"); $hmac_digest = $hmac->hash(trim($string)); $binary_hmac = pack("H40", $hmac_digest); $base64_hmac = base64_encode($binary_hmac); $hash = $base64_hmac; $client = new SoapClient(null, array('location' => "http://webservice.imdb.com/doc/2006-12-15/", 'uri' => "http://webservice.imdb.com/doc/2006-12-15/", 'trace' => 1, 'exceptions' => 0)); $output = ""; if ($query) { $strBodyComponent_Session = '<AWSAccessKeyId>' . $access_key . '</AWSAccessKeyId><Timestamp>' . $timestamp . '</Timestamp><Signature>' . $hash . '</Signature><Both>' . $query . '</Both><Action>' . $method . '</Action>'; $params_var = new SoapVar($strBodyComponent_Session, XSD_ANYXML, null, null, null); $response = $client->Search($params_var); $variables = get_object_vars($response); if (isset($variables["faultstring"])) { $output .= "faultstring: " . $variables["faultstring"] . "<br/>"; $output .= "faultcode: " . $variables["faultcode"] . "<br/>"; $details = get_object_vars($variables["detail"]); foreach ($details as $key => $value) { $output .= $key . " : " . $value . "<br/>"; } return $output; } else { $result_obj = array(); if (isset($response["SearchResults"])) { $result_set = $response["SearchResults"]; $result_array = get_object_vars($result_set); if (sizeof($result_array)) { $result_temp = $result_array["Result"]; if (sizeof($result_temp)) { $result = get_object_vars($result_temp[0]); $type = $result["Type"]; $category = $result["Category"]; $result_obj["type"] = $type; $result_obj["category"] = $category; $result_obj["info"] = array(); $val_array = $result[$type . "Result"]; if (get_class($val_array) == "stdClass") { $val_array = get_object_vars($val_array); } if (sizeof($val_array)) { $result_item = $val_array; if (isset($result_item[0])) { $result_item = $result_item[0]; } foreach ($result_item as $key => $value) { if (get_class($value) == "stdClass") { $resobj_value_array = get_object_vars($value); foreach ($resobj_value_array as $result_key => $result_value) { $output .= " " . $result_key . " : " . (get_class($result_value) == "stdClass" ? get_class($result_value) : $result_value) . "<br/>"; $result_obj["info"][$result_key] = $result_value; } } else { $output .= $key . " : " . $value . "<br/>"; $result_obj["info"][$key] = $value; } } } } } } if ($type == "Title") { $method = "LookupTitle"; //$resp_groups = "Tagline,PlotSummary"; $resp_groups = ""; $string = $method . $timestamp; $hmac = new Crypt_HMAC($secret_key, "sha1"); $hmac_digest = $hmac->hash(trim($string)); $binary_hmac = pack("H40", $hmac_digest); $base64_hmac = base64_encode($binary_hmac); $hash = $base64_hmac; $strTitleLookup = '<AWSAccessKeyId>' . $access_key . '</AWSAccessKeyId><Timestamp>' . $timestamp . '</Timestamp><Signature>' . $hash . '</Signature><ResourceId>' . $result_obj["info"]["TitleId"] . '</ResourceId><Type>' . $type . '</Type><Action>' . $method . '</Action><ResponseGroups>' . $resp_groups . '</ResponseGroups>'; $params_var = new SoapVar($strTitleLookup, XSD_ANYXML, null, null, null); $title_response = $client->LookupTitle($params_var); if (is_soap_fault($title_response)) { echo $client->__getLastRequest(); //return "blah"; } $variables = get_object_vars($title_response); if (isset($variables["faultstring"])) { $output .= "faultstring: " . $variables["faultstring"] . "<br/>"; $output .= "faultcode: " . $variables["faultcode"] . "<br/>"; $details = get_object_vars($variables["detail"]); foreach ($details as $key => $value) { $output .= $key . " : " . $value . "<br/>"; } return $output; } else { foreach ($variables as $key => $value) { $output .= $key . "<br/>"; } } } $output = ($callback ? $callback . "(" : "") . jsonify($result_obj) . ($callback ? ");" : ""); return $output; } } }
//Instantiate a HMAC object and provide private key //Key also specified in Skin in the Adyen backoffice $Crypt_HMAC = new Crypt_HMAC("YourSecretKey", 'sha1'); //the data that needs to be signed is a concatenated string of the form data (except the order data) //paymentAmount + currencyCode + shipBeforeDate + merchantReference + skinCode + //merchantAccount + sessionValidity + shopperEmail + shopperReference + //allowedMethods + blockedMethods $sign = $amount . $currency . $shipBeforeDate . $merchantref . $skinCode . $merchantAccount . $sessionValidity . $allowedMethods . $blockedMethods; //base64 encoding is necessary because the string needs to be send over the internet and //the hexadecimal result of the HMAC encryption could include escape characters //first get the hex string from the HMAC encryption -> convert back to binary data (and pack / zip) -> base64 encode $merchantsig = base64_encode(pack('H*',$Crypt_HMAC->hash($sign))); $url = "https://test.adyen.com/hpp/select.shtml?merchantReference=".urlencode($merchantref)."&paymentAmount=".urlencode($amount)."¤cyCode=".urlencode($currency)."&shipBeforeDate=".urlencode($shipBeforeDate)."&skinCode=".urlencode($skinCode)."&merchantAccount=".urlencode($merchantAccount)."&shopperLocale=".urlencode($shopperLocale)."&orderData=".urlencode($orderData)."&sessionValidity=".urlencode($sessionValidity)."&shopperEmail=&shopperReference=&recurringContract=&allowedMethods=".urlencode($allowedMethods)."&blockedMethods=".urlencode($blockedMethods)."&skipSelection=".urlencode($skipSelection)."&countryCode=".urlencode($countryCode)."&merchantSig=".urlencode($merchantsig); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <style type="text/css"> body { background-color:#5B423D; width: 100%;