function confirmUser($username, $password) { global $conn; /* Add slashes if necessary (for query) */ if (!get_magic_quotes_gpc()) { $username = addslashes($username); } /* Verify that user is in database */ $q = "select password from " . DB_PREFIX . "users where username = '******' limit 1"; $result = mysql_query($q, $conn); if (!$result || mysql_numrows($result) < 1) { return 1; // Indicates username failure } /* Retrieve password from result, strip slashes */ $dbarray = mysql_fetch_array($result); // combine password in database with key $dbarray['password'] = hmac($_SESSION['key'], stripslashes($dbarray['password'])); $password = stripslashes($password); /* Validate that password is correct */ if ($password == $dbarray['password']) { return 0; // Success! Username and password confirmed } else { return 2; // Indicates password failure } }
private function _sign($data) { if (is_null($this->_macKey)) { throw new Exception("EMPTY_MACKEY"); } return hmac($this->_macKey, $data); }
private function _verifySign($domain, $text, $sign) { include_once KFL_DIR . '/Libs/Cache.class.php'; $filename = $domain . ".txt"; $cache = new Cache(86400 * 300, 0); $cache->setCacheStore("file"); // or memcache $cache->setCacheDir(APP_TEMP_DIR); $cache->setCacheFile($filename); if ($cache->isCached()) { $client = unserialize($cache->fetch()); } else { require_once 'ClientModel.class.php'; $ClientModel = new ClientModel(); $client = $ClientModel->getClientByName($domain); if ($client) { $cache->save(serialize($client)); } else { return false; } } $this->_private_key = $client['private_key']; if (hmac($this->_private_key, $text, 'sha1') == $sign) { return true; } else { return false; } }
function gda_add_hash($key, $text) { if ($key == "") { return "NOHASH\n" . $text; } else { return hmac($key, $text) . "\n" . $text; } }
function InsertFP ($loginid, $x_tran_key, $amount, $sequence, $currency = "") { $tstamp = time (); $fingerprint = hmac ($x_tran_key, $loginid . "^" . $sequence . "^" . $tstamp . "^" . $amount . "^" . $currency); echo ('<input type="hidden" name="x_fp_sequence" value="' . $sequence . '">' ); echo ('<input type="hidden" name="x_fp_timestamp" value="' . $tstamp . '">' ); echo ('<input type="hidden" name="x_fp_hash" value="' . $fingerprint . '">' ); return (0); }
function decrypt($key, $data) { $decodedData = base64_decode($data); // TODO: Check that data is at least bigger than HMAC + IV length error_log("key in Decrypt is: " . $key); $hmac = substr($decodedData, 0, 32); error_log("hmac in Decrypt is: " . $hmac); $iv = substr($decodedData, 32, 16); error_log("iv in Decrypt is: " . $iv); $data = substr($decodedData, 48); error_log("data in Decrypt is: " . $data); if ($hmac != hmac($key, $iv . $data)) { // TODO: Handle HMAC validation failure return 0; } //echo "no error"; return openssl_decrypt($data, 'aes-256-cbc', hashKey($key), true, $iv); }
function checkLogin() { /* Check if user has been remembered */ if (isset($_COOKIE['c_name']) && isset($_COOKIE['c_pass'])) { $_SESSION['username'] = $_COOKIE['c_name']; $_SESSION['password'] = hmac($_SESSION['key'], $_COOKIE['c_pass']); } /* Username and password have been set */ if (isset($_SESSION['username']) && isset($_SESSION['password'])) { /* Confirm that username and password are valid */ if (confirmUser($_SESSION['username'], $_SESSION['password']) != 0) { /* Variables are incorrect, user not logged in */ unset($_SESSION['username']); unset($_SESSION['password']); // reset cookies if (isset($_COOKIE['c_name'])) { setcookie("c_name", "", time() - 60 * 60 * 24 * 100, "/"); } if (isset($_COOKIE['c_pass'])) { setcookie("c_pass", "", time() - 60 * 60 * 24 * 100, "/"); } return false; } // log user data if (!isset($_SESSION['logged'])) { $_SESSION['logged'] = true; global $conn; /* Add slashes if necessary (for query) */ $username = $_SESSION['username']; $ip = $_SERVER['REMOTE_ADDR']; if (!get_magic_quotes_gpc()) { $username = addslashes($username); $ip = addslashes($ip); } $q = "UPDATE " . DB_PREFIX . "users SET ip = '{$ip}', lastdate = " . time() . " WHERE username = '******'"; mysql_query($q, $conn); } return true; } else { return false; } }
die('Этот заказ уже оплачен'); } else { $url = $okay->config->root_url . '/order/' . $order->url; header('location:' . $url); exit; } } //////////////////////////////////// // Проверка контрольной подписи //////////////////////////////////// if ($_REQUEST['check'] == "1") { $param = $_REQUEST['ext_transact'] . $_REQUEST['num_shop'] . $_REQUEST['keyt_shop'] . $_REQUEST['identified'] . $_REQUEST['sum'] . $_REQUEST['comment']; $sign = hmac($settings['skeys'], $param); } else { $param = $_REQUEST['transact'] . $_REQUEST['status'] . $_REQUEST['result'] . $_REQUEST['ext_transact'] . $_REQUEST['num_shop'] . $_REQUEST['keyt_shop'] . '1' . $_REQUEST['sum'] . $_REQUEST['comment']; $sign = hmac($settings['skeys'], $param); } if ($sign != $_REQUEST['sign']) { if ($_REQUEST['check'] == "1") { die("Контрольная подпись не верна"); } else { $url = $okay->config->root_url . '/order/' . $order->url; header('location:' . $url); exit; } } //////////////////////////////////// // Проверка суммы платежа //////////////////////////////////// // Сумма заказа у нас в магазине $order_amount = $okay->money->convert($order->total_price, $method->currency_id, false);
function do_userform($formatter, $options) { global $DBInfo; $user =& $DBInfo->user; # get cookie $id = !empty($options['login_id']) ? $options['login_id'] : ''; $use_any = 0; if (!empty($DBInfo->use_textbrowsers)) { if (is_string($DBInfo->use_textbrowsers)) { $use_any = preg_match('/' . $DBInfo->use_textbrowsers . '/', $_SERVER['HTTP_USER_AGENT']) ? 1 : 0; } else { $use_any = preg_match('/Lynx|w3m|links/', $_SERVER['HTTP_USER_AGENT']) ? 1 : 0; } } $options['msg'] = ''; # e-mail conformation if (!empty($options['ticket']) and $id and $id != 'Anonymous') { $userdb =& $DBInfo->udb; $suspended = false; if ($userdb->_exists($id)) { $user = $userdb->getUser($id); } else { if ($userdb->_exists($id, 1)) { // suspended user $suspended = true; $user = $userdb->getUser($id, 1); } } if ($user->id == $id) { if ($user->info['eticket'] == $options['ticket']) { list($dummy, $email) = explode('.', $options['ticket'], 2); $user->info['email'] = $email; $user->info['eticket'] = ''; if ($suspended) { if (empty($DBInfo->register_confirm_admin)) { $userdb->activateUser($id); $userdb->saveUser($user); } else { $userdb->saveUser($user, array('suspended' => 1)); } } else { $userdb->saveUser($user); } $title = _("Successfully confirmed"); $options['msg'] = _("Your e-mail address is confirmed successfully"); if (!empty($DBInfo->register_confirm_admin)) { $options['msg'] .= "<br />" . _("Your need to wait until your ID activated by admin"); } } else { if ($user->info['nticket'] == $options['ticket']) { $title = _("Successfully confirmed"); $user->info['nticket'] = ''; $user->info['password'] = $user->info['npassword']; $user->info['npassword'] = ''; $userdb->saveUser($user); $options['msg'] = _("Your new password is confirmed successfully"); } else { $title = _("Confirmation missmatched !"); $options['msg'] = _("Please try again to register your e-mail address"); } } } else { if ($suspended) { $title = _("Please wait until your ID is confirmed by admin!"); } else { $title = _("ID does not exist !"); } $options['msg'] = _("Please try again to register your e-mail address"); } $formatter->send_header("", $options); $formatter->send_title($title, "", $options); $formatter->send_footer("", $options); return ''; } $title = ''; if ($user->id == "Anonymous" and !empty($options['emailreset'])) { setcookie('MONI_VERIFIED_EMAIL', '', time() - 3600, get_scriptname()); $options['msg'] .= '<br />' . _("Verification E-mail removed."); $options['verifyemail'] = ''; $user->verified_email = ''; } else { if ($user->id == "Anonymous" and !empty($options['login']) and !empty($options['verify_email'])) { $email = base64_decode($options['login']); $ticket = base64_encode(getTicket($_SERVER['REMOTE_ADDR'], $email, 10)); if ($ticket == $options['verify_email']) { $options['msg'] .= '<br />' . _("Your email address is successfully verified."); $user->verified_email = $email; setcookie('MONI_VERIFIED_EMAIL', $email, time() + 60 * 60 * 24 * 30, get_scriptname()); } else { $options['msg'] .= '<br />' . _("Verification missmatched."); } } else { if ($user->id == "Anonymous" and $options['verify'] == _("Verify E-mail address") and !empty($DBInfo->anonymous_friendly) and !empty($options['verifyemail'])) { if (preg_match('/^[a-z][a-z0-9_\\-\\.]+@[a-z][a-z0-9_\\-]+(\\.[a-z0-9_]+)+$/i', $options['verifyemail'])) { if (($ret = verify_email($options['verifyemail'])) < 0) { $ret = -$ret; $options['msg'] .= '<br />' . 'ERROR Code: ' . $ret; $options['msg'] .= '<br/>' . _("Invalid email address or can't verify it."); } else { if (!empty($DBInfo->verify_email)) { if ($DBInfo->verify_email == 1) { $options['msg'] .= '<br/>' . _("Your email address is successfully verified."); setcookie('MONI_VERIFIED_EMAIL', $options['verifyemail'], time() + 60 * 60 * 24 * 30, get_scriptname()); } else { $opts = array(); $opts['subject'] = "[{$DBInfo->sitename}] " . _("Verify Email address"); $opts['email'] = $options['verifyemail']; $opts['id'] = 'nobody'; $ticket = base64_encode(getTicket($_SERVER['REMOTE_ADDR'], $opts['email'], 10)); $enc = base64_encode($opts['email']); $body = qualifiedUrl($formatter->link_url('UserPreferences', "?action=userform&login={$enc}&verify_email={$ticket}")); $body = _("Please confirm your e-mail address") . "\n" . $body . "\n"; $ret = wiki_sendmail($body, $opts); $options['msg'] .= '<br/>' . _("E-mail verification mail sent"); } } } } else { $options['msg'] .= '<br/>' . _("Your email address is not valid"); } } else { if ($user->id == "Anonymous" and !empty($options['login_id']) and isset($options['password']) and !isset($options['passwordagain'])) { if (method_exists($user, 'login')) { $user->login($formatter, $options); $params = array(); $params['value'] = $options['page']; do_goto($formatter, $params); return; } # login $userdb = $DBInfo->udb; if ($userdb->_exists($id)) { $user = $userdb->getUser($id); $login_ok = 0; if (!empty($DBInfo->use_safelogin)) { if (isset($options['challenge']) and $options['_chall'] == $options['challenge']) { #print '<pre>'; #print $options['password'].'<br />'; #print hmac($options['challenge'],$user->info['password']); #print '</pre>'; if (hmac($options['challenge'], $user->info['password']) == $options['password']) { $login_ok = 1; } } else { # with no javascript browsers $md5pw = md5($options['password']); if ($md5pw == $user->info['password']) { $login_ok = 1; } } } if ($login_ok or $user->checkPasswd($options['password']) === true) { $options['msg'] = sprintf(_("Successfully login as '%s'"), $id); $options['id'] = $user->id; if ($user->id == 'Anonymous') { // special case. login success but ID is not acceptable $options['msg'] = _("Invalid user ID. Please register again"); } else { $formatter->header($user->setCookie()); if (!isset($user->info['login_success'])) { $user->info['login_success'] = 0; } if (!isset($user->info['login_fail'])) { $user->info['login_fail'] = 0; } $user->info['login_success']++; $user->info['last_login'] = gmdate("Y/m/d H:i:s", time()); $user->info['login_fail'] = 0; // reset login $user->info['remote'] = $_SERVER['REMOTE_ADDR']; $userdb->saveUser($user); $use_refresh = 1; } $DBInfo->user = $user; } else { $title = sprintf(_("Invalid password !")); if (!isset($user->info['login_fail'])) { $user->info['login_fail'] = 0; } $user->info['login_fail']++; $user->info['remote'] = $_SERVER['REMOTE_ADDR']; $userdb->saveUser($user); $user->setID('Anonymous'); } } else { if (isset($options['login_id'][0])) { if ($userdb->_exists($id, 1)) { // suspended user $title = sprintf(_("\"%s\" is waiting for activated by admin !"), $options['login_id']); } else { $title = sprintf(_("\"%s\" does not exist on this wiki !"), $options['login_id']); } $options['login_id'] = ''; } else { $title = _("Make new ID on this wiki"); } $form = macro_UserPreferences($formatter, '', $options); } } else { if (!empty($options['logout'])) { # logout header($user->unsetCookie(), false); if (session_name() != '') { $path = get_scriptname(); // for moniwiki internal header('Set-Cookie: ' . session_name() . '=' . $user->id . '; expires=Tuesday, 01-Jan-1999 12:00:00 GMT; Path=' . $path, false); // for some user plugins $params = session_get_cookie_params(); header('Set-Cookie: ' . session_name() . '=' . $user->id . '; expires=Tuesday, 01-Jan-1999 12:00:00 GMT; Path=' . $params['path'], false); } // call logout method if (method_exists($user, 'logout')) { $user->logout($formatter, $options); } else { $options['msg'] = _("Cookie deleted !"); } $user->id = 'Anonymous'; $DBInfo->user = $user; $use_refresh = 1; } else { if (!empty($DBInfo->use_sendmail) and $options['login'] == _("E-mail new password") and $user->id == "Anonymous" and !empty($options['email']) and !empty($options['login_id'])) { # email new password $title = ''; if (!$use_any and $DBInfo->use_ticket) { if ($options['__seed'] and $options['check']) { $mycheck = getTicket($options['__seed'], $_SERVER['REMOTE_ADDR'], 4); if ($mycheck == $options['check']) { $ok_ticket = 1; } else { $title = _("Invalid ticket !"); } } else { $title = _("You need a ticket !"); } } else { $ok_ticket = 1; } $userdb =& $DBInfo->udb; if ($userdb->_exists($id)) { $user = $userdb->getUser($id); } if ($ok_ticket and $user->id != "Anonymous") { if ($options['email'] == $user->info['email'] and $user->info['eticket'] == '') { #make new password $mypass = base64_encode(getTicket(time(), $_SERVER['REMOTE_ADDR'], 10)); $mypass = substr($mypass, 0, 8); $options['password'] = $mypass; $old_passwd = $user->info['password']; if ($DBInfo->use_safelogin) { $ret = $user->setPasswd(md5($mypass), md5($mypass), 1); } else { $ret = $user->setPasswd($mypass, $mypass); } $new_passwd = $user->info['password']; $user->info['password'] = $old_passwd; $user->info['npassword'] = $new_passwd; #make ticket $ticket = md5(time() . $user->id . $options['email']); $user->info['nticket'] = $ticket . "." . $options['email']; // save join agreement if (!empty($DBInfo->use_agreement) and !empty($options['joinagreement'])) { $user->info['join_agreement'] = 'agree'; if (!empty($DBInfo->agreement_version)) { $user->info['join_agreement_version'] = $DBInfo->agreement_version; } } $userdb->saveUser($user); # XXX $opts['subject'] = "[{$DBInfo->sitename}] " . _("New password confirmation"); $opts['email'] = $options['email']; $opts['id'] = 'nobody'; $body = qualifiedUrl($formatter->link_url('', "?action=userform&login_id={$user->id}&ticket={$ticket}.{$options['email']}")); $body = _("Please confirm your new password") . "\n" . $body . "\n"; $body .= sprintf(_("Your new password is %s"), $mypass) . "\n\n"; $body .= _("Please change your password later") . "\n"; $ret = wiki_sendmail($body, $opts); if (is_array($ret)) { $title = _("Fail to e-mail notification !"); $options['msg'] = $ret['msg']; } else { $title = _("New password is sent to your e-mail !"); $options['msg'] = _("Please check your e-mail"); } } else { if ($options['email'] != $user->info['email']) { $title = _("Fail to e-mail notification !"); $options['msg'] = _("E-mail mismatch !"); } else { $title = _("Invalid request"); $options['msg'] = _("Please confirm your e-mail address first !"); } } } else { if (!$ok_ticket) { $title = _("Invalid ticket !"); } else { $title = _("ID and e-mail mismatch !"); } $options['msg'] = _("Please try again or make a new profile"); } $formatter->send_header("", $options); $formatter->send_title($title, "", $options); $formatter->send_footer("", $options); return; } else { if ($user->id == "Anonymous" and !empty($options['login_id']) and ($options['password'] and $options['passwordagain'] or $DBInfo->use_safelogin and $options['email'])) { # create profile $title = ''; if (!$use_any and !empty($DBInfo->use_ticket)) { if ($options['__seed'] and $options['check']) { $mycheck = getTicket($options['__seed'], $_SERVER['REMOTE_ADDR'], 4); if ($mycheck == $options['check']) { $ok_ticket = 1; } else { $title = _("Invalid ticket !"); } } else { $title = _("You need a ticket !"); } } else { $ok_ticket = 1; } $id = $user->getID($options['login_id']); if (preg_match('/^[a-z][a-z0-9_\\-\\.]+@[a-z][a-z0-9_\\-]+(\\.[a-z0-9_]+)+$/i', $id)) { if (($ret = verify_email($id)) < 0) { $ret = -$ret; $options['msg'] .= '<br />' . 'ERROR Code: ' . $ret; $options['msg'] .= '<br/>' . _("Invalid email address or can't verify it."); } else { $options['email'] = $id; $user->setID($id); } } else { if (!preg_match("/\\//", $id)) { $user->setID($id); } } // protect http:// style id if (!empty($DBInfo->use_agreement) and empty($options['joinagreement'])) { $title = _("Please check join agreement."); } else { if ($ok_ticket and $user->id != "Anonymous") { if (!empty($DBInfo->use_safelogin)) { $mypass = base64_encode(getTicket(time(), $_SERVER['REMOTE_ADDR'], 10)); $mypass = substr($mypass, 0, 8); $options['password'] = $mypass; $ret = $user->setPasswd(md5($mypass), md5($mypass), 1); } else { $ret = $user->setPasswd($options['password'], $options['passwordagain']); } if (!empty($DBInfo->password_length) and strlen($options['password']) < $DBInfo->password_length) { $ret = 0; } if ($ret <= 0) { if ($ret == 0) { $title = _("too short password!"); } else { if ($ret == -1) { $title = _("mismatch password!"); } else { if ($ret == -2) { $title = _("not acceptable character found in the password!"); } } } } else { if ($ret < 8 and empty($DBInfo->use_safelogin)) { $options['msg'] = _("Your password is too simple to use as a password !"); } $udb = $DBInfo->udb; if ($options['email']) { if (preg_match('/^[a-z][a-z0-9_\\-\\.]+@[a-z][a-z0-9_\\-]+(\\.[a-z0-9_]+)+$/i', $options['email'])) { if (($ret = verify_email($options['email'])) < 0) { $options['email'] = ''; // reset email address $ret = -$ret; $options['msg'] .= '<br />' . 'ERROR Code: ' . $ret; $options['msg'] .= '<br/>' . _("Can't verify E-mail address! Please check your email address."); } } else { $options['msg'] .= '<br/>' . _("Your email address is not valid"); } } if ($udb->isNotUser($user)) { if (!empty($DBInfo->no_register)) { $options['msg'] = _("Fail to register"); $options['err'] = _("You are not allowed to register on this wiki"); $options['err'] .= "\n" . _("Please contact WikiMasters"); do_invalid($formatter, $options); return; } $title = sprintf(_("Successfully added as '%s'"), _html_escape($user->id)); $options['id'] = $user->id; $ticket = md5(time() . $user->id . $options['email']); $user->info['eticket'] = $ticket . "." . $options['email']; if (!empty($DBInfo->use_safelogin)) { $options['msg'] = sprintf(_("Successfully added as '%s'"), $user->id); $options['msg'] .= '<br />' . _("Please check your mailbox"); } $args = array(); if ($options['email'] == $id or !empty($DBInfo->register_confirm_email)) { $args = array('suspended' => 1); } if (!empty($DBInfo->register_confirm_admin)) { $args = array('suspended' => 1); } if (!empty($DBInfo->register_confirm_admin)) { if (!empty($options['msg'])) { $options['msg'] .= '<br />'; } $options['msg'] .= _("Your need to wait until your ID activated by admin"); } // save join agreement if (!empty($DBInfo->use_agreement) and !empty($options['joinagreement'])) { $user->info['join_agreement'] = 'agree'; if (!empty($DBInfo->agreement_version)) { $user->info['join_agreement_version'] = $DBInfo->agreement_version; } } if (empty($DBInfo->use_safelogin) && empty($args['suspended'])) { $formatter->header($user->setCookie()); } $ret = $udb->addUser($user, $args); # XXX if (!empty($options['email']) and preg_match('/^[a-z][a-z0-9_\\-\\.]+@[a-z][a-z0-9_\\-]+(\\.[a-z0-9_]+)+$/i', $options['email'])) { $options['subject'] = "[{$DBInfo->sitename}] " . _("E-mail confirmation"); $body = ''; if (!empty($DBInfo->email_register_header) and file_exists($DBInfo->email_register_header)) { $body = file_get_contents($DBInfo->email_register_header); $body = str_replace(array('@sitename@'), array($DBInfo->sitename), $body); } $body .= _("Please confirm your email address") . "\n\n"; $body .= qualifiedUrl($formatter->link_url('', "?action=userform&login_id={$user->id}&ticket={$ticket}.{$options['email']}")); $body .= "\n"; if (!empty($DBInfo->use_safelogin)) { $body .= "\n" . sprintf(_("Your initial password is %s"), $mypass) . "\n\n"; $body .= _("Please change your password later") . "\n"; } $ret = wiki_sendmail($body, $options); if (is_array($ret)) { $options['msg'] .= $ret['msg']; } else { $options['msg'] .= '<br/>' . _("Confirmation E-mail sent"); } } } else { # already exist user $user = $udb->getUser($user->id); if ($user->checkPasswd($options['password']) === true) { $options['msg'] .= sprintf(_("Successfully login as '%s'"), $id); $options['id'] = $user->id; $formatter->header($user->setCookie()); $udb->saveUser($user); # XXX } else { $title = _("Invalid password !"); } } } } else { if (empty($title)) { $title = _("Invalid username !"); } } } } else { if ($user->id != "Anonymous") { # save profile $udb =& $DBInfo->udb; $userinfo = $udb->getUser($user->id); if (!empty($options['password']) and !empty($options['passwordagain'])) { $chall = 0; if (!empty($DBInfo->use_safelogin)) { if (isset($options['_chall'])) { $chall = $options['challenge']; } else { $chall = rand(100000); $options['password'] = hmac($chall, $options['password']); } } //echo 'chall=',$chall,' ',$options['password']; if ($userinfo->checkPasswd($options['password'], $chall) === true) { if ($DBInfo->use_safelogin) { $mypass = md5($options['passwordagain']); // XXX $ret = $userinfo->setPasswd($mypass, $mypass, 1); } else { $ret = $userinfo->setPasswd($options['passwordagain']); } if ($ret <= 0) { if ($ret == 0) { $title = _("too short password!"); } else { if ($ret == -1) { $title = _("mismatch password !"); } else { if ($ret == -2) { $title = _("not acceptable character found in the password!"); } } } $options['msg'] = _("Password is not changed !"); } else { $title = _("Password is changed !"); if ($ret < 8) { $options['msg'] = _("Password is too simple to use as a password !"); } } } else { $title = _("Invalid password !"); $options['msg'] = _("Password is not changed !"); } } if (isset($options['user_css'])) { $userinfo->info['css_url'] = $options['user_css']; } if (isset($options['timezone'])) { list($hour, $min) = explode(':', $options['timezone']); $min = $min * 60; $min = $hour < 0 ? -1 * $min : $min; $tz_offset = $hour * 3600 + $min; $userinfo->info['tz_offset'] = $tz_offset; } if (!empty($DBInfo->use_agreement) and !empty($options['joinagreement'])) { $userinfo->info['join_agreement'] = 'agree'; if (!empty($DBInfo->agreement_version)) { $userinfo->info['join_agreement_version'] = $DBInfo->agreement_version; } } $button_check_email_again = !empty($options['button_check_email_again']) ? 1 : 0; if ($button_check_email_again and !empty($userinfo->info['eticket'])) { list($dummy, $email) = explode('.', $userinfo->info['eticket'], 2); if (!empty($email)) { $options['email'] = $email; } } if (!empty($options['email']) and $options['email'] != $userinfo->info['email']) { if (preg_match('/^[a-z][a-z0-9_\\-\\.]+@[a-z][a-z0-9_\\-]+(\\.[a-z0-9_]+)+$/i', $options['email'])) { if (($ret = verify_email($options['email'])) < 0) { $ret = -$ret; $options['msg'] .= '<br />' . 'ERROR Code: ' . $ret; $options['msg'] .= '<br />' . _("Invalid email address or can't verify it."); } else { $ticket = md5(time() . $userinfo->info['id'] . $options['email']); $userinfo->info['eticket'] = $ticket . "." . $options['email']; $options['subject'] = "[{$DBInfo->sitename}] " . _("E-mail confirmation"); $body = qualifiedUrl($formatter->link_url('', "?action=userform&login_id={$user->id}&ticket={$ticket}.{$options['email']}")); $body = _("Please confirm your email address") . "\n" . $body; $ret = wiki_sendmail($body, $options); if (is_array($ret)) { $options['msg'] = $ret['msg']; } else { $options['msg'] = _("E-mail confirmation mail sent"); } } } else { $options['msg'] = _("Your email address is not valid"); } } if (!empty($userinfo->info['idtype']) and $userinfo->info['idtype'] == 'openid' and isset($options['nick']) and $options['nick'] != $userinfo->info['nick']) { $nick = $userinfo->getID($options['nick']); // nickname check XXX if (!$udb->_exists($nick)) { $userinfo->info['nick'] = $nick; } else { $options['msg'] = _("Your Nickname already used as ID in this wiki"); } } $udb->saveUser($userinfo); #$options['css_url']=$options['user_css']; if (!isset($options['msg'])) { $options['msg'] = _("Profiles are saved successfully !"); } } else { if ($user->id == "Anonymous" and isset($options['openid_url'])) { # login with openid include_once 'lib/openid.php'; session_start(); $process_url = qualifiedUrl($formatter->link_url("UserPreferences", "?action=userform")); $trust_root = qualifiedUrl($formatter->link_url("")); $openid = new SimpleOpenID(); $openid->SetIdentity($options['openid_url']); $openid->SetTrustRoot($trust_root); $openid->SetRequiredFields(array('nickname', 'email', 'fullname')); $openid->SetOptionalFields(array('language', 'timezone')); if ($openid->GetOpenIDServer()) { $openid->SetApprovedURL($process_url); // Send Response from OpenID server to this script $openid->Redirect(); // This will redirect user to OpenID Server return; } else { $error = $openid->GetError(); #echo "ERROR CODE: " . $error['code'] . "<br>"; #echo "ERROR DESCRIPTION: " . $error['description'] . "<br>"; $options["msg"] = sprintf(_("Authentication request was failed: %s"), $error['description']); } } else { if (!empty($options['openid_mode']) and $options['openid_mode'] == 'id_res') { // OpenID result include_once 'lib/openid.php'; if (!preg_match('/utf-?8/i', $DBInfo->charset)) { $options['openid_sreg_nickname'] = iconv('utf-8', $DBInfo->charset, $options['openid_sreg_nickname']); $options['openid_sreg_fullname'] = iconv('utf-8', $DBInfo->charset, $options['openid_sreg_fullname']); } $openid = new SimpleOpenID(); $openid->SetIdentity($options['openid_identity']); $openid_validation_result = $openid->ValidateWithServer(); if ($openid_validation_result == true) { // OK HERE KEY IS VALID $userdb =& $DBInfo->udb; // XXX $user->setID($options['openid_identity']); // XXX if (!empty($options['openid_language'])) { $user->info['language'] = strtolower($options['openid_sreg_language']); } //$user->info['tz_offset']=$options['openid_timezone']; if ($userdb->_exists($options['openid_identity'])) { $user = $userdb->getUser($options['openid_identity']); $user->info['idtype'] = 'openid'; $options['msg'] .= sprintf(_("Successfully login as '%s' via OpenID."), $options['openid_identity']); $formatter->header($user->setCookie()); $userdb->saveUser($user); // always save } else { if (!empty($DBInfo->no_register) and $DBInfo->no_register == 1) { $options['msg'] = _("Fail to register"); $options['err'] = _("You are not allowed to register on this wiki"); $options['err'] .= "\n" . _("Please contact WikiMasters"); do_invalid($formatter, $options); return; } if ($options['openid_sreg_nickname']) { $nick = $user->getID($options['openid_sreg_nickname']); if (!$userdb->_exists($nick)) { $user->info['nick'] = $nick; } else { $options['msg'] = sprintf(_("Your Nickname %s already used as ID in this Wiki."), $nick); } } $user->info['email'] = $options['openid_sreg_email']; $user->info['idtype'] = 'openid'; $userdb->addUser($user); $formatter->header($user->setCookie()); $userdb->saveUser($user); $options["msg"] .= sprintf(_("OpenID Authentication successful and saved as %s."), $options['openid_identity']); } $options['id'] = $user->id; } else { if ($openid->IsError() == true) { // ON THE WAY, WE GOT SOME ERROR $error = $openid->GetError(); $options["msg"] = sprintf(_("Authentication request was failed: %s"), $error['description']); } else { // Signature Verification Failed $options["msg"] = _("Invalid OpenID Authentication request"); echo "INVALID AUTHORIZATION"; } } } else { if (!empty($DBInfo->use_agreement) and $options['login'] == _("Make profile")) { $options['agreement'] = 1; $form = macro_UserPreferences($formatter, '', $options); } else { $options["msg"] = _("Invalid request"); } } } } } } } } } } } $myrefresh = ''; if (!empty($DBInfo->use_refresh) and !empty($use_refresh)) { $sec = $DBInfo->use_refresh - 1; if (!empty($options['return_url'])) { $lnk = $options['return_url']; } else { $lnk = $formatter->link_url($formatter->page->urlname, '?action=show'); } $myrefresh = 'Refresh: ' . $sec . '; url=' . qualifiedURL($lnk); } $formatter->send_header($myrefresh, $options); $formatter->send_title($title, "", $options); if (!$title && (empty($DBInfo->control_read) or $DBInfo->security->is_allowed('read', $options))) { $lnk = $formatter->link_to('?action=show'); if (empty($form)) { echo sprintf(_("return to %s"), $lnk); } else { echo $form; } } else { if (!empty($form)) { print $form; } # else $formatter->send_page("Goto UserPreferences"); } $formatter->send_footer("", $options); }
function sdb_request($action, $params = array()) { global $adminer, $connection; list($host, $params['AWSAccessKeyId'], $secret) = $adminer->credentials(); $params['Action'] = $action; $params['Timestamp'] = gmdate('Y-m-d\\TH:i:s+00:00'); $params['Version'] = '2009-04-15'; $params['SignatureVersion'] = 2; $params['SignatureMethod'] = 'HmacSHA1'; ksort($params); $query = ''; foreach ($params as $key => $val) { $query .= '&' . rawurlencode($key) . '=' . rawurlencode($val); } $query = str_replace('%7E', '~', substr($query, 1)); $query .= "&Signature=" . urlencode(base64_encode(hmac('sha1', "POST\n" . preg_replace('~^https?://~', '', $host) . "\n/\n{$query}", $secret, true))); @ini_set('track_errors', 1); // @ - may be disabled $file = @file_get_contents(preg_match('~^https?://~', $host) ? $host : "http://{$host}", false, stream_context_create(array('http' => array('method' => 'POST', 'content' => $query, 'ignore_errors' => 1)))); if (!$file) { $connection->error = $php_errormsg; return false; } libxml_use_internal_errors(true); $xml = simplexml_load_string($file); if (!$xml) { $error = libxml_get_last_error(); $connection->error = $error->message; return false; } if ($xml->Errors) { $error = $xml->Errors->Error; $connection->error = "{$error->Message} ({$error->Code})"; return false; } $connection->error = ''; $tag = $action . "Result"; return $xml->{$tag} ? $xml->{$tag} : true; }
<input type=hidden name=x_show_form value="PAYMENT_FORM"> <input type=hidden name=x_relay_response value="TRUE"> <input type=hidden name=x_login value="<?php print $authorize_login; ?> "> <input type=hidden name=x_fp_sequence value="<?php print $r->id; ?> "> <input type=hidden name=x_fp_timestamp value="<?php print $x_time; ?> "> <input type=hidden name=x_fp_hash value="<?php print hmac($authorize_secret, $authorize_login . "^" . $r->id . "^" . $x_time . "^" . sprintf("%01.2f", $money_authorize) . "^"); ?> "> <input type=hidden name=x_receipt_link_url value="<?php print GetSetting("payment_url"); ?> "> <input type=hidden name=x_relay_url value="<?php print $full_www_path . "online_authorize.php"; ?> "> <input type=hidden name=x_description value="<?php print $company_name; ?> : bill <?php print $sid;
public function build_signature($request, $consumer, $token) { $base_string = $request->get_signature_base_string(); $request->base_string = $base_string; $key_parts = array(!empty($consumer->secret) ? $consumer->secret : '', $token ? $token->secret : ""); $key_parts = OAuthUtil::urlencode_rfc3986($key_parts); $key = implode('&', $key_parts); if (!function_exists('hash_hmac')) { return base64_encode(hmac($key, $base_string)); } else { return base64_encode(hash_hmac('sha1', $base_string, $key, true)); } }
private function checkid($wait) { if (empty($_REQUEST['openid_return_to'])) { return $this->error400('return_to'); } $return_to = $_REQUEST['openid_return_to']; if (empty($_REQUEST['openid_identity'])) { return $this->error_get($return_to, 'identity'); } $identity = $_REQUEST['openid_identity']; if ($identity != litepublisher::$site->url . $this->url) { return $this->error_get($return_to, 'identity'); } $trust_root = !empty($_REQUEST['openid_trust_root']) ? $_REQUEST['openid_trust_root'] : $return_to; if ($trust_root != $return_to) { if (!$this->urldescends($return_to, $trust_root)) { return $this->error500('Invalidtrust'); } } $assoc_handle = !empty($_REQUEST['openid_assoc_handle']) ? $_REQUEST['openid_assoc_handle'] : null; $sreg_required = !empty($_REQUEST['openid_sreg_required']) ? $_REQUEST['openid_sreg_required'] : ''; $sreg_optional = !empty($_REQUEST['openid_sreg_optional']) ? $_REQUEST['openid_sreg_optional'] : ''; //join fields $sreg_required .= ',' . $sreg_optional; $auth = tauthdigest::i(); if (litepublisher::$options->cookieenabled) { if (!litepublisher::$options->user) { return litepublisher::$urlmap->redir('/admin/login/'); } } elseif (!$auth->Auth()) { return $auth->headers(); } if (litepublisher::$options->group != 'admin') { return 404; } $q = strpos($return_to, '?') ? '&' : '?'; $cancel_url = $return_to . $q . 'openid.mode=cancel'; if ($wait && (!in_array($trust_root, $this->trusted) || $this->confirm)) { //вывести форму и проверит результат формы if (empty($_POST['submit'])) { if (!empty($_REQUEST['openid_assoc_handle']) && isset($this->keys[$_REQUEST['openid_assoc_handle']])) { $this->keys[$_REQUEST['openid_assoc_handle']]['request'] = $_REQUEST; $this->save(); } $html = tadminhtml::i(); $html->section = 'openidserver'; $lang = tlocal::i('openidserver'); $args = targs::i(); $args->trust_root = $trust_root; $args->assoc_handle = $assoc_handle; $form = $html->trustform($args); return tsimplecontent::html($form); } else { switch ($_POST['accept']) { case 'yes': break; case 'yesall': $this->trusted[] = $trust_root; $this->save(); break; default: return $this->redir($cancel_url); } } } $keys = array('mode' => 'id_res', 'identity' => litepublisher::$site->url . $this->url, 'return_to' => $return_to); if (!($shared_secret = $this->GetSecret($assoc_handle))) { if ($assoc_handle != null) { $keys['invalidate_handle'] = $assoc_handle; if (isset($this->keys[$assoc_handle])) { unset($this->keys[$assoc_handle]); } } $this->NewKeys($assoc_handle, $shared_secret, $lifetime); } $keys['assoc_handle'] = $assoc_handle; foreach (explode(',', $sreg_required) as $key) { if (!isset($_REQUEST[$key])) { continue; } $skey = 'sreg.' . $key; if ($value = $this->GetReg($key)) { $keys[$skey] = $value; } } $tokens = ''; foreach ($keys as $key => $value) { $tokens .= "{$key}:{$value}\n"; } $keys['signed'] = implode(',', array_keys($keys)); $keys['sig'] = base64_encode(hmac($shared_secret, $tokens)); return $this->RedirKeys($return_to, $keys); }
function checkPasswd($passwd, $chall = 0) { if (strlen($passwd) < 3) { return false; } if ($chall) { if (hmac($chall, $this->info['password']) == $passwd) { return true; } } else { if (crypt($passwd, $this->info['password']) == $this->info['password']) { return true; } } return false; }
private function _createSign($text) { return hmac($this->_private_key, $text, 'sha1'); }
$contractName = $_REQUEST["contractName"]; $contractName = decodeUtf8($contractName); $invoiceTitle = $_REQUEST["invoiceTitle"]; $invoiceTitle = decodeUtf8($invoiceTitle); $mobile = $_REQUEST["mobile"]; $orderId = $_REQUEST["orderId"]; $payDate = $_REQUEST["payDate"]; $reserved = $_REQUEST["reserved"]; $reserved = decodeUtf8($reserved); $status = $_REQUEST["status"]; $amtItem = $_REQUEST["amtItem"]; $signData = $merchantId . $payNo . $requestId . $returnCode . $message . $sigTyp . $type . $version . $amount . $banks . $contractName . $invoiceTitle . $mobile . $orderId . $payDate . $reserved . $status; // if($version == "1.0.1") $signData = $merchantId . $payNo . $requestId . $returnCode . $message . $sigTyp . $type . $version . $amount . $banks . $contractName . $invoiceTitle . $mobile . $orderId . $payDate . $reserved . $status . $amtItem; $hash = hmac("", $signData); $newhmac = hmac($signKey, $hash); RecordLog("YGM", "###hmac" . $hmac . "###"); RecordLog("YGM", "###newhmac" . $newhmac . "###"); @(list($_, $order_id, $city_id, $_) = explode('-', $orderId, 4)); if (Table::Fetch('pay', $orderId)) { die('SUCCESS'); } $v_amount = $amount / 100; if ($_ == 'charge') { if ($newhmac == $hmac) { @(list($_, $user_id, $create_time, $_) = explode('-', $orderId, 4)); ZFlow::CreateFromCharge($v_amount, $user_id, $create_time, 'cmpay'); // 记录日志 RecordMyLog("流水号:" . $payNo); RecordMyLog("支付金额:" . $amount); RecordMyLog("金额明细:" . $amtItem);
/** * 响应操作 */ function respond() { $payment = get_payment('yeepay_abchina'); $merchant_id = $payment['yp_account']; // 获取商户编号 $merchant_key = $payment['yp_key']; // 获取秘钥 $message_type = trim($_REQUEST['r0_Cmd']); $succeed = trim($_REQUEST['r1_Code']); // 获取交易结果,1成功,-1失败 $trxId = trim($_REQUEST['r2_TrxId']); $amount = trim($_REQUEST['r3_Amt']); // 获取订单金额 $cur = trim($_REQUEST['r4_Cur']); // 获取订单货币单位 $product_id = trim($_REQUEST['r5_Pid']); // 获取产品ID $orderid = trim($_REQUEST['r6_Order']); // 获取订单ID $userId = trim($_REQUEST['r7_Uid']); // 获取产品ID $merchant_param = trim($_REQUEST['r8_MP']); // 获取商户私有参数 $bType = trim($_REQUEST['r9_BType']); // 获取订单ID $mac = trim($_REQUEST['hmac']); // 获取安全加密串 ///生成加密串,注意顺序 $ScrtStr = $merchant_id . $message_type . $succeed . $trxId . $amount . $cur . $product_id . $orderid . $userId . $merchant_param . $bType; $mymac = hmac($ScrtStr, $merchant_key); $v_result = false; if (strtoupper($mac) == strtoupper($mymac)) { if ($succeed == '1') { ///支付成功 $v_result = true; order_paid($orderid); } } return $v_result; }
/** * Testing for setup * @global array $profile */ function test_mode() { global $profile, $p, $g; if ($profile['allow_test'] != true) { error_403(); } @ini_set('max_execution_time', 180); $test_expire = time() + 120; $test_ss_enc = 'W7hvmld2yEYdDb0fHfSkKhQX+PM='; $test_ss = base64_decode($test_ss_enc); $test_token = "alpha:bravo\ncharlie:delta\necho:foxtrot"; $test_server_private = '11263846781670293092494395517924811173145217135753406847875706165886322533899689335716152496005807017390233667003995430954419468996805220211293016296351031812246187748601293733816011832462964410766956326501185504714561648498549481477143603650090931135412673422192550825523386522507656442905243832471167330268'; $test_client_public = base64_decode('AL63zqI5a5p8HdXZF5hFu8p+P9GOb816HcHuvNOhqrgkKdA3fO4XEzmldlb37nv3+xqMBgWj6gxT7vfuFerEZLBvuWyVvR7IOGZmx0BAByoq3fxYd3Fpe2Coxngs015vK37otmH8e83YyyGo5Qua/NAf13yz1PVuJ5Ctk7E+YdVc'); $res = array(); // bcmath $res['bcmath'] = extension_loaded('bcmath') ? 'pass' : 'warn - not loaded'; // gmp if ($profile['allow_gmp']) { $res['gmp'] = extension_loaded('gmp') ? 'pass' : 'warn - not loaded'; } else { $res['gmp'] = 'pass - n/a'; } // get_temp_dir $res['logfile'] = is_writable($profile['logfile']) ? 'pass' : "warn - log is not writable"; // session & new_assoc user_session(); list($test_assoc, $test_new_ss) = new_assoc($test_expire); $res['session'] = $test_assoc != session_id() ? 'pass' : 'fail'; // secret @session_unregister('shared_secret'); list($check, $check2) = secret($test_assoc); $res['secret'] = $check == $test_new_ss ? 'pass' : 'fail'; // expire $res['expire'] = $check2 <= $test_expire ? 'pass' : 'fail'; // base64 $res['base64'] = base64_encode($test_ss) == $test_ss_enc ? 'pass' : 'fail'; // hmac $test_sig = base64_decode('/VXgHvZAOdoz/OTa5+XJXzSGhjs='); $check = hmac($test_ss, $test_token); $res['hmac'] = $check == $test_sig ? 'pass' : sprintf("fail - '%s'", base64_encode($check)); if ($profile['use_bigmath']) { // bigmath powmod $test_server_public = '102773334773637418574009974502372885384288396853657336911033649141556441102566075470916498748591002884433213640712303846640842555822818660704173387461364443541327856226098159843042567251113889701110175072389560896826887426539315893475252988846151505416694218615764823146765717947374855806613410142231092856731'; $check = bmpowmod($g, $test_server_private, $p); $res['bmpowmod-1'] = $check == $test_server_public ? 'pass' : sprintf("fail - '%s'", $check); // long $test_client_long = '133926731803116519408547886573524294471756220428015419404483437186057383311250738749035616354107518232016420809434801736658109316293127101479053449990587221774635063166689561125137927607200322073086097478667514042144489248048756916881344442393090205172004842481037581607299263456852036730858519133859409417564'; $res['long'] = long($test_client_public) == $test_client_long ? 'pass' : 'fail'; // bigmath powmod 2 $test_client_share = '19333275433742428703546496981182797556056709274486796259858099992516081822015362253491867310832140733686713353304595602619444380387600756677924791671971324290032515367930532292542300647858206600215875069588627551090223949962823532134061941805446571307168890255137575975911397744471376862555181588554632928402'; $check = bmpowmod($test_client_long, $test_server_private, $p); $res['bmpowmod-2'] = $check == $test_client_share ? 'pass' : sprintf("fail - '%s'", $check); // bin $test_client_mac_s1 = base64_decode('G4gQQkYM6QmAzhKbVKSBahFesPL0nL3F2MREVwEtnVRRYI0ifl9zmPklwTcvURt3QTiGBd+9Dn3ESLk5qka6IO5xnILcIoBT8nnGVPiOZvTygfuzKp4tQ2mXuIATJoa7oXRGmBWtlSdFapH5Zt6NJj4B83XF/jzZiRwdYuK4HJI='); $check = bin($test_client_share); $res['bin'] = $check == $test_client_mac_s1 ? 'pass' : sprintf("fail - '%s'", base64_encode($check)); } else { $res['bigmath'] = 'fail - big math functions are not available.'; } // sha1_20 $test_client_mac_s1 = base64_decode('G4gQQkYM6QmAzhKbVKSBahFesPL0nL3F2MREVwEtnVRRYI0ifl9zmPklwTcvURt3QTiGBd+9Dn3ESLk5qka6IO5xnILcIoBT8nnGVPiOZvTygfuzKp4tQ2mXuIATJoa7oXRGmBWtlSdFapH5Zt6NJj4B83XF/jzZiRwdYuK4HJI='); $test_client_mac_s2 = base64_decode('0Mb2t9d/HvAZyuhbARJPYdx3+v4='); $check = sha1_20($test_client_mac_s1); $res['sha1_20'] = $check == $test_client_mac_s2 ? 'pass' : sprintf("fail - '%s'", base64_encode($check)); // x_or $test_client_mac_s3 = base64_decode('i36ZLYAJ1rYEx1VEHObrS8hgAg0='); $check = x_or($test_client_mac_s2, $test_ss); $res['x_or'] = $check == $test_client_mac_s3 ? 'pass' : sprintf("fail - '%s'", base64_encode($check)); $out = "<table border=1 cellpadding=4>\n"; foreach ($res as $test => $stat) { $code = substr($stat, 0, 4); $color = $code == 'pass' ? '#9f9' : ($code == 'warn' ? '#ff9' : '#f99'); $out .= sprintf("<tr><th>%s</th><td style='background:%s'>%s</td></tr>\n", $test, $color, $stat); } $out .= "</table>"; wrap_html($out); }
{ // RFC 2104 HMAC implementation for php. // Creates an md5 HMAC. // Eliminates the need to install mhash to compute a HMAC // Hacked by Lance Rushing $b = 64; // byte length for md5 if (strlen($key) > $b) { $key = pack("H*", md5($key)); } $key = str_pad($key, $b, chr(0x0)); $ipad = str_pad('', $b, chr(0x36)); $opad = str_pad('', $b, chr(0x5c)); $k_ipad = $key ^ $ipad; $k_opad = $key ^ $opad; return md5($k_opad . pack("H*", md5($k_ipad . $data))); } $hasError = false; $msg = "OK"; $uid = $_REQUEST['uid']; $data = $_REQUEST['data']; $sign = $_REQUEST['sign']; $seq = $_REQUEST['seq']; $cookie = $_REQUEST['cookie']; $check = hmac($uid, $data); if ($check != $sign) { $hasError = true; $msg = "FAILED"; } $rank = "not yet known"; echo "oygSubmitScoreJSONComplete({ \"envelope\": {\"success\":" . ($hasError ? "false" : "true") . ", \"seq\":" . $seq . ", \"cookie\":" . $cookie . ", \"msg\":\"" . $msg . "\"}, \"data\": {\"rank\": \"" . $rank . "\"}});";
function hmac_md5($key, $data) { return hmac('md5', $key, $data); }
function valid_authentication($buffer) { global $MAX_DELTA; $retval = TRUE; $sockname = sprintf('#%d (%s:%d)', $this->cid, $this->remote_address, $this->remote_port); $a = explode("\t", $buffer); if (sizeof($a) < 5 || $a[0] != 'A') { logger("{$sockname}: authentication failed"); $retval = FALSE; } else { $orig = $this->headers['origin']; $shop = $this->headers['request_uri']; $this->nick = $a[1]; $this->name = $a[2]; $this->date = $a[3]; $sig1 = $a[4]; $hmac_key = get_org_property($orig); $hmac_msg = $orig . $shop . $this->name . $this->nick . $this->date; $sig2 = hmac($hmac_key, $hmac_msg); if ($sig1 != $sig2) { logger("{$sockname}: invalid signature; access denied"); $retval = FALSE; } else { $m = array(); $pattern = '/(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})/'; if (preg_match($pattern, $this->date, $m)) { $delta = time() - gmmktime($m[4], $m[5], $m[6], $m[2], $m[3], $m[1]); if ($MAX_DELTA < abs($delta)) { logger("{$sockname}: signature not (yet) valid (anymore): delta = " . $delta); $retval = FALSE; } else { logger(sprintf("%s: valid signature; delta = %ds", $sockname, $delta), WLOG_DEBUG); } } else { logger(sprintf("%s: invalid date pattern '%s'; bailing out", $sockname, $this->date)); $retval = FALSE; } } } if (!$retval) { $payload = pack('n', 1008) . 'Unauthorised'; $response = ''; $this->server->frame_encode(0x88, $payload, $response); $this->send($response); $this->state = 2; } return $retval; }
} $key = str_pad($key, $blocksize, chr(0)); $ipad = str_repeat(chr(0x36), $blocksize); $opad = str_repeat(chr(0x5c), $blocksize); return $hash(($key ^ $opad) . pack('H*', $hash(($key ^ $ipad) . $data))); } //-------------------------------------------------------------------------------------------------- // Get request headers $h = print_r($_SERVER, true); // Get body of POST request $p = $HTTP_RAW_POST_DATA; // Check for Google Digest header if ($_SERVER['HTTP_GOOGLE_CODE_PROJECT_HOSTING_HOOK_HMAC']) { // Check digests match $remote_digest = $_SERVER['HTTP_GOOGLE_CODE_PROJECT_HOSTING_HOOK_HMAC']; $digest = hmac($config['secret_key'], $p); if ($digest != $remote_digest) { die("digests don't match"); } // Debugging to capture output /* $gfilename = 'tmp/g.txt'; $gfile = @fopen($gfilename, "w+") or die("could't open file --\"" . $gfilename . "\""); fwrite($gfile, $h . $p . $digest); fclose($gfile); */ // Get contents of POST body $obj = json_decode($p); $url = 'http://twitter.com/statuses/update.json'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url);
function getCallbackHmacString($sCmd, $sErrorCode, $sTrxId, $orderId, $amount, $cur, $productId, $userId, $MP, $bType) { // echo "<hr>"; // $args = func_get_args(); // print_r($args); global $keyValue; global $merchantId; // echo "密钥和商家ID: ".$keyValue.' | '.$merchantId; #取得加密前的字符串 $sbOld = ""; #加入商家ID $sbOld = $sbOld . $merchantId; #加入消息类型 $sbOld = $sbOld . $sCmd; #加入业务返回码 $sbOld = $sbOld . $sErrorCode; #加入交易ID $sbOld = $sbOld . $sTrxId; #加入交易金额 $sbOld = $sbOld . $amount; #加入货币单位 $sbOld = $sbOld . $cur; #加入产品Id $sbOld = $sbOld . $productId; #加入订单ID $sbOld = $sbOld . $orderId; #加入用户ID $sbOld = $sbOld . $userId; #加入商家扩展信息 $sbOld = $sbOld . $MP; #加入交易结果返回类型 $sbOld = $sbOld . $bType; return hmac($keyValue, $sbOld); }
/** show the (visually almost) empty page and load or continue with the JS popup window * * this routine is responsible for showing an 'empty' page and maybe for generating * a JS popup window (if $first==TRUE). The 'empty' page contains only a form with * single textarea. However, this textarea is not displayed (display:none) so the * casual user sees nothing (but obviously without CSS it is a different matter). * This textarea is used by the CREW code to store the edited document before * submitting the form. Since there are no buttons of any kind, it is completely * up to the JS code to generate the necessary DOM elements that are required to * successfully save the document. * * If $first is TRUE, we have to setup the popup window. This is quite complicated * because generate the necessary JS-code at runtime using JS. One of the reasons * is that I want to set the correct translations in the popup window. There may * be an easier way. * * The Websocket protocol is used to talk to the Websocket server which is configured * for this site. This setting can be manipulated using the Module Manager. In order * to authenticate ourselves against the websocket server we use the following mechanism. * There are a few important variables used in authenticating: * * - $origin: this is the website's hostname as seen by the user's browser * - $request_uri: a string that uniquely identifies the node within the origin * - $full_name: the full name of the current user (ie. $USER->full_name) * - $username: the (short) name/userid of the curent user (ie. $USER->username) * - $request_date: the current time (GMT) in the format "yyyy-mm-dd hh:mm:ss". * * and also * * - $secret_key: a secret shared with the Websocket server * - $location: the URL of the Websocket server * * The authentication works as follows. The variables $origin, $request_uri, $full_name, * $username and $request_date are concatenated in a $message. Then the $message and * the $secret_key are used to calculate a hashed message authentication code (HMAC) * according to RFC2104 (see function {@see hmac()} in waslib.php). * * When connecting to the Websocket server the parameters $request_uri, $full_name, * $username and $request_date are sent, together with the HMAC. The server then * calculates the HMAC too and if it matches the HMAC that was sent, access is * granted. * * Note that the variable $origin is only used here to calculate the HMAC; it is * not sent to the Websocket server like the other parameters. Instead we use the * Origin as seen by the user's web browser. Obviously the two should match or else * authentication fails. This way we check the browser's idea of where the web page * is located. Also note that we made the current date/time part of the HMAC. That * is done to prevent replay-attacks (the other variables are quasi-static between * CREW editing sessions). It is up to the Websocket server to determine if the * timestamp is (still) valid or not. This depends on a certain clock synchronisation * between the webserver and the Websocket server. * * Also note that the shared secret never leaves the webserver, only the hashed * message is sent from webserver to Websocket server. However, the secret has to * be the same on both ends. * * @param object &$theme collects the (html) output * @param int $module_id identifies the crew module (need that for getting module properties) * @param bool $first if TRUE we generate code to generate a popup * @return bool TRUE on success+output generated via $theme, FALSE otherwise */ function crew_view_show_edit(&$theme, $module_id, $first = FALSE) { global $USER, $WAS_SCRIPT_NAME, $CFG; // 1A -- fetch the latest version of the document (we always need that)... $node_id = intval($theme->node_record['node_id']); if (($record = crew_view_get_workshop_data($node_id)) === FALSE) { $theme->add_message(t('error_retrieving_workshop_data', 'm_crew')); return FALSE; } // 1B -- and tell the user the date/time/user of latest update in content area $params = array('{USERNAME}' => is_null($record['username']) ? $record['muser_id'] : $record['username'], '{FULL_NAME}' => is_null($record['full_name']) ? $record['muser_id'] : $record['full_name'], '{DATIM}' => $record['mtime']); $attr = array('class' => 'crew_datim'); $theme->add_content(html_tag('p', $attr, t('last_updated_by', 'm_crew', $params))); // 1C -- prepare a hidden textarea with the current document text /* <noscript>requires javascript</noscript> * <div> * <form> * <textarea>$document</textarea> * </form> * </div> */ $theme->add_content(html_tag('noscript', '', t('crew_requires_js_and_ws', 'm_crew'))); $attr = array('id' => 'crew_start_edit', 'style' => 'display: none;'); $theme->add_content(html_tag('div', $attr)); $href = was_node_url($theme->node_record); $attr = array('id' => 'frmEdit'); $theme->add_content(html_form($href, 'post', $attr)); $attr = array('id' => 'txtText', 'rows' => 10, 'cols' => 80, 'name' => 'text'); $theme->add_content(html_tag('textarea', $attr, htmlspecialchars($record['document']))); $theme->add_content(html_form_close()); $theme->add_content(html_tag_close('div')); // At this point we're done IF this was a repeat call. // If it was the first call we need to do some more, like popping up the edit window if (!$first) { return TRUE; } // Still here, so this is the first time // 2 -- prepare all information for popup // 2A -- which skin? $dialogdef = crew_view_dialogdef(); if (!dialog_validate($dialogdef)) { // somehow an error; default to first skin $value = '0'; } else { $value = $dialogdef['skin']['value']; } $skin = $dialogdef['skin']['options'][$value]['css']; // 2B -- which location,origin,secret (from module_properties) $table = 'modules_properties'; $fields = array('name', 'value'); $where = array('module_id' => $module_id); $order = array('sort_order'); $keyfield = 'name'; if (($properties = db_select_all_records($table, $fields, $where, $order, $keyfield)) === FALSE) { logger(sprintf('%s(): module properties error: %s', __FUNCTION__, db_errormessage())); $theme->add_message(t('error_retrieving_workshop_data', 'm_crew')); return FALSE; } $org = $properties['origin']['value']; $loc = $properties['location']['value']; $secret = $properties['secret']['value']; // 2C -- prepare variables for and perform hmac calculation $workshop = trim($record['header']); if (empty($workshop)) { $workshop = trim($node_record['link_text']); } $uri = sprintf('%s/%d/%s', $WAS_SCRIPT_NAME, $node_id, friendly_bookmark($workshop)); $name = $USER->full_name; $nick = $USER->username; $datim = gmstrftime('%Y-%m-%d %T'); $hmac_key = $secret; $hmac_msg = $org . $uri . $name . $nick . $datim; $sig = hmac($hmac_key, $hmac_msg); $progcrew = $CFG->progwww_short . '/modules/crew'; $css = $progcrew . '/' . $skin; if ($CFG->debug || !file_exists($CFG->progdir . '/modules/crew/crew.min.js')) { $js = $progcrew . '/crew.js'; } else { $js = $progcrew . '/crew.min.js'; } $theme->add_content(html_tag('script')); $theme->add_content(crew_screen($loc, $nick, $name, $uri, $workshop, $org, $datim, $sig, $css, $js, $progcrew)); $theme->add_content(html_tag_close('script')); return TRUE; }
function MD5sign($okey, $odata) { $signdata = hmac("", $odata); return hmac($okey, $signdata); }
$recv = $sTotalString["MSG"]; $recvArray = parseRecv($recv); //校验签名 $r_hmac = $recvArray["hmac"]; $r_merchantId = $recvArray["merchantId"]; $r_payNo = $recvArray["payNo"]; $r_requestId = $recvArray["requestId"]; $r_returnCode = $recvArray["returnCode"]; $r_message = $recvArray["message"]; $r_signType = $recvArray["signType"]; $r_type = $recvArray["type"]; $r_version = $recvArray["version"]; $sessionId = $recvArray["SESSIONID"]; $r_source = $r_merchantId . $r_payNo . $r_requestId . $r_returnCode . $r_message . $r_signType . $r_type . $r_version . $sessionId; $r_hash = hmac("", $r_source); $r_newhmac = hmac($signKey, $r_hash); //echo $r_returnCode; //echo "<br />"; //echo $r_message ; //exit; if ($r_hmac != $r_newhmac) { echo "验证签名失败!"; die; } else { $newUrl = $GLOBALS["tokenRedirectUrl"]; ?> <!DOCTYPE HTML PUBLIC "-W3CDTD HTML 4.01 TransitionalEN"> <html> <head> </head> <body onload="Javascript:document.f1.submit();">
/** * Fetches and parses XML from Amazon for the given query. * @param string $query Query string containing variables to search Amazon for. Valid variables: $isbn, $title, $author * @return array Array containing each book's information. */ function query_amazon( $query ) { require_once dirname(__FILE__) . '/sha256.inc.php'; if (!function_exists('hmac')) { function hmac($key, $data, $hashfunc='sha256') { $blocksize=64; if (strlen($key) > $blocksize) $key=pack('H*', $hashfunc($key)); $key=str_pad($key, $blocksize, chr(0x00)); $ipad=str_repeat(chr(0x36), $blocksize); $opad=str_repeat(chr(0x5c), $blocksize); $hmac = pack('H*', $hashfunc(($key^$opad) . pack('H*', $hashfunc(($key^$ipad) . $data)))); return $hmac; } } global $item, $items; $options = get_option('nowReadingOptions'); $using_isbn = false; parse_str($query); if ( empty($isbn) && empty($title) && empty($author) ) return false; if ( !empty($isbn) ) $using_isbn = true; // Our query needs different vars depending on whether or not we're searching by ISBN, so build it here. if ( $using_isbn ) { $isbn = preg_replace('#([^0-9x]+)#i', '', $isbn); $query = "isbn:$isbn"; } else { $query=''; if ( !empty($title) ) $query = 'title:' . urlencode($title); if ( !empty($author) ) $query .= 'author:' . urlencode($author); } // these items MUST be set in the Options screen $AWSAccessKeyId = trim($options['AWSAccessKeyId']); $SecretAccessKey = trim($options['SecretAccessKey']); # // some paramters $method = "GET"; $host = "ecs.amazonaws".$options['domain']; $uri = "/onca/xml"; // additional parameters $params["Service"] = "AWSECommerceService"; // GMT timestamp $params["Timestamp"] = gmdate("Y-m-d\TH:i:s\Z"); // API version $params["Version"] = "2009-03-31"; $params["AssociateTag"] = urlencode($options['associate']); $params["Power"] = $query; $params["Operation"] = "ItemSearch"; $params["SearchIndex"] = "Books"; $params["ResponseGroup"] = "Request,Large,Images,AlternateVersions"; $params["AWSAccessKeyId"] = $AWSAccessKeyId; // Sort paramters ksort($params); // re-build the request $request = array(); foreach ($params as $parameter=>$value) { $parameter = str_replace("_", ".", $parameter); $parameter = str_replace("%7E", "~", rawurlencode($parameter)); $value = str_replace("%7E", "~", rawurlencode($value)); $request[] = $parameter . "=" . $value; } $request = implode("&", $request); $signatureString = $method . chr(10) . $host . chr(10) . $uri . chr(10) . $request; $signature = urlencode(base64_encode(hmac($SecretAccessKey, $signatureString))); $request = "http://" . $host . $uri . "?" . $request . "&Signature=" . $signature; // Fetch the XML using either Snoopy or cURL, depending on our options. if ( $options['httpLib'] == 'curl' ) { if ( !function_exists('curl_init') ) { return new WP_Error('curl-not-installed', __('cURL is not installed correctly.', NRTD)); } else { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $request); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERAGENT, 'Now Reading ' . NOW_READING_VERSION); curl_setopt($ch, CURLOPT_HEADER, 0); if ( !empty($options['proxyHost']) ) { $proxy = $options['proxyHost']; if ( !empty($options['proxyPort']) ) { $proxy .= ":{$options['proxyPort']}"; } curl_setopt($ch, CURLOPT_PROXY, $proxy); } $xmlString = curl_exec($ch); curl_close($ch); } } else { require_once ABSPATH . WPINC . '/class-snoopy.php'; $snoopy = new snoopy; $snoopy->agent = 'Now Reading Redux' . NOW_READING_VERSION; if ( !empty($options['proxyHost']) ) $snoopy->proxy_host = $options['proxyHost']; if ( !empty($options['proxyHost']) && !empty($options['proxyPort']) ) $snoopy->proxy_port = $options['proxyPort']; $snoopy->fetch($request); $xmlString = $snoopy->results; } if ( empty($xmlString) ) { do_action('nr_search_error', $query); echo ' <div id="message" class="error fade"> <p><strong>' . __("Oops!") . '</strong></p> <p>' . sprintf(__("For some reason, I couldn't search for your book on amazon%s.", NRTD), $options['domain']) . '</p> <p>' . __("Amazon's Web Services may be down, or there may be a problem with your server configuration.") . '</p> '; if ( $options['httpLib'] ) echo '<p>' . __("Try changing your HTTP Library setting to <strong>cURL</strong>.", NRTD) . '</p>'; echo ' </div> '; return false; } require_once 'xml/IsterXmlSimpleXMLImpl.php'; $impl = new IsterXmlSimpleXMLImpl; $xml = $impl->load_string($xmlString); if ( $options['debugMode'] ) robm_dump("Amazon Search XML:", htmlentities(str_replace(">", ">\n", $xmlString))); $items = $xml->ItemSearchResponse->Items->children(); if (count($items) == 0) { return false; } $results = array(); foreach ($items as $item) { $attr = $item->ItemAttributes; if (!$attr) { continue; } $asin = $item->ASIN->CDATA(); if (empty($asin)) { continue; } // Get full meta-data given the current ISBN. Used to get all editions. $metaData = getMetadataFromIsbn($asin, $AWSAccessKeyId, $SecretAccessKey, urlencode($options['associate'])); if ($options['debugMode']) { robm_dump("Amazon Lookup XML:", htmlentities(str_replace(">", ">\n", $metaData))); } $metaDataParser = new IsterXmlSimpleXMLImpl; $metaDataXml = $metaDataParser->load_string($metaData); if (isset($metadata->ItemLookupResponse->Items->Request->Errors)) { continue;//$metadata->ItemLookupResponse->Items->Request->Errors; } $editions = $metaDataXml->ItemLookupResponse->Items->children(); if (count($editions) == 0) { continue; } // For each edition, add an entry. foreach ($editions as $edition) { if (!isset($edition->ASIN)) { continue; } $asin = $edition->ASIN->CDATA(); if (empty($asin)) { continue; } $title = $edition->ItemAttributes->Title->CDATA(); if (empty($title)) { continue; } $author = ''; if (is_array($edition->ItemAttributes->Author)) { foreach ($edition->ItemAttributes->Author as $a) { if (is_object($a)) { $author .= $a->CDATA() . ', '; } } $author = substr($author, 0, -2); } else { if (is_object($edition->ItemAttributes->Author)) { $author = $edition->ItemAttributes->Author->CDATA(); } } if (empty($author)) { $author = apply_filters('default_book_author', 'Unknown'); } $size = "{$options['imageSize']}Image"; if (empty($item->$size)) { continue; } $image = $item->$size->URL->CDATA(); if (empty($image)) { $image = get_option('siteurl') . '/wp-content/plugins/now-reading-redux/no-image.png'; } $binding = ''; if (isset($edition->ItemAttributes->Binding)) { $binding = $edition->ItemAttributes->Binding->CDATA(); } $ed = ''; if (isset($edition->ItemAttributes->Edition)) { $ed = $edition->ItemAttributes->Edition->CDATA(); } $date = ''; if (isset($edition->ItemAttributes->PublicationDate)) { $date = $edition->ItemAttributes->PublicationDate->CDATA(); } $publisher = ''; if (isset($edition->ItemAttributes->Publisher)) { $publisher = $edition->ItemAttributes->Publisher->CDATA(); } if ($options['debugMode']) { robm_dump("book:", $author, $title, $binding, $ed, $date, $publisher, $asin); } $results[] = apply_filters('raw_amazon_results', compact('author', 'title', 'binding', 'ed', 'date', 'publisher', 'image', 'asin')); } } $results = apply_filters('returned_books', $results); return $results; }
function check_handle($bh) { $handle = base64_decode($bh); # IV + HMAC + expiry if (!$handle || strlen($handle) < 8 + HASH_LEN + 4) return false; $handle = xtea_decrypt(SIGKEY, $handle); $data = substr($handle, HASH_LEN); if (hmac(SIGKEY, $data) != substr($handle, 0, HASH_LEN)) return false; list(, $expiry) = unpack("l", $data); if ($expiry < time()) return false; return substr($data, 4); }
function pobierz_miesiac($klucz, $url, $nazwaUsera, $nazwaKlucza, $curlHandle) { $hashWiadomosci = hmac($klucz, $url . $nazwaUsera . $nazwaKlucza); $typ = "json"; $headers = array('Accept: application/' . $typ, 'Content-type: application/' . $typ . '; charset=UTF-8', 'Authentication: IAPIS user='******', hmac-sha1=' . $hashWiadomosci); curl_setopt($curlHandle, CURLOPT_TIMEOUT, 300); curl_setopt($curlHandle, CURLOPT_CONNECTTIMEOUT, 100); curl_setopt($curlHandle, CURLOPT_URL, $url); curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers); curl_setopt($curlHandle, CURLOPT_HTTPGET, true); curl_setopt($curlHandle, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($curlHandle, CURLOPT_SSL_VERIFYPEER, 0); $rsp = curl_exec($curlHandle); $tab = json_decode($rsp, true); if ($tab['response']['Kod'] == 0) { return array('miesiac' => $tab['response']['MiesiacKsiegowy'], 'rok' => $tab['response']['RokKsiegowy']); } throw new Exception("Wystąpił problem z połączeniem z ifrmą. Przyczyna: " . $tab['response']['Informacja']); }
private function _sign($data, $key) { $key = substr($key, 32, 40); return hmac($key, $data); }