public function execute() { $userService = ServiceFactory::factory('User'); $username = is_null($this->getParam('email')) ? '' : trim($this->getParam('email')); $enCryptedPassword = is_null($this->getParam('pwd')) ? '' : trim($this->getParam('pwd')); $password = CryptoUtil::Crypto($enCryptedPassword, 'AES-256', KANCART_APP_SECRET, false); $this->language->load('account/register'); if (strlen(utf8_decode($username)) > 96 || !preg_match('/^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,3})$/i', $username)) { $this->setError(KancartResult::ERROR_USER_INVALID_USER_DATA, $this->language->get('error_email')); return; } if (strlen($password) < 4 || strlen($password) > 20) { $this->setError(KancartResult::ERROR_USER_INVALID_USER_DATA, $this->language->get('error_password')); return; } $firstname = is_null($this->getParam('firstname')) ? '' : trim($this->getParam('firstname')); $lastname = is_null($this->getParam('lastname')) ? '' : trim($this->getParam('lastname')); $telephone = is_null($this->getParam('telephone')) ? '' : trim($this->getParam('telephone')); $regisetInfo = array('firstname' => $firstname, 'lastname' => $lastname, 'email' => $username, 'telephone' => $telephone, 'password' => $password); if (!$userService->register($regisetInfo)) { $this->setError(KancartResult::ERROR_USER_INVALID_USER_DATA, $msg); return; } // succed registering $this->setSuccess(); }
public function execute() { $userService = ServiceFactory::factory('User'); $username = is_null($this->getParam('uname')) ? '' : trim($this->getParam('uname')); if (empty($username)) { $this->setError(KancartResult::ERROR_USER_INPUT_PARAMETER, 'User name is empty.'); return; } $encryptedPassword = is_null($this->getParam('pwd')) ? '' : trim($this->getParam('pwd')); $password = CryptoUtil::Crypto($encryptedPassword, 'AES-256', KANCART_APP_SECRET, false); if (!$password) { $this->setError(KancartResult::ERROR_USER_INPUT_PARAMETER, 'Password is empty.'); return; } $loginInfo = array('email' => $username, 'password' => $password); $login = $userService->login($loginInfo); if (is_string($login)) { $this->setError(KancartResult::ERROR_USER_INPUT_PARAMETER, $login); return; } $cacheKey = $this->customer->getCustomerGroupId() . '-' . $this->config->get('config_customer_price'); if ($this->config->get('config_tax')) { $query = $this->db->query("SELECT gz.geo_zone_id FROM " . DB_PREFIX . "geo_zone gz LEFT JOIN " . DB_PREFIX . "zone_to_geo_zone z2gz ON (z2gz.geo_zone_id = gz.geo_zone_id) WHERE (z2gz.country_id = '0' OR z2gz.country_id = '" . (int) $this->customer->country_id . "') AND (z2gz.zone_id = '0' OR z2gz.zone_id = '" . (int) $this->customer->zone_id . "')"); if ($query->num_rows) { $cacheKey .= '-1-' . $query->row['geo_zone_id']; } else { $cacheKey .= '-1-0'; } } else { $cacheKey .= '-0-0'; } $info = array('sessionkey' => md5($username . uniqid(mt_rand(), true)), 'cachekey' => $cacheKey); $this->setSuccess($info); }
public static function Crypto($text, $cipher, $key, $isEncrypt) { switch ($cipher) { case 'DES': $crypt = new Crypt_DES(CRYPT_DES_MODE_CBC); $crypt->setKey($key); $crypt->setIV($key); if ($isEncrypt) { return strtoupper(bin2hex($crypt->encrypt($text))); } else { return $crypt->decrypt(CryptoUtil::hex2bin($text)); } break; case 'AES-256': $crypt = new Crypt_Rijndael(CRYPT_RIJNDAEL_MODE_ECB); $crypt->setKey($key); if ($isEncrypt) { return strtoupper(bin2hex($crypt->encrypt($text))); } else { return $crypt->decrypt(CryptoUtil::hex2bin($text)); } break; default: break; } return "ERROR"; }
public static function authUser($username, $password) { $login = LoginDao::getLoginByUsername($username); if ($login != null && CryptoUtil::encrypt($password) == $login->getEncryptedPassword()) { return $login; } return null; }
/** * SharedMemory constructor *. * @param Key|null $cacheKey * @param AuthenticationKey|null $authKey * @param string $personalization */ public function __construct(Key $cacheKey = null, AuthenticationKey $authKey = null, string $personalization = '') { if (!$cacheKey) { $state = State::instance(); $cacheKey = $state->keyring['cache.hash_key']; } // We need a short hash key: $this->cacheKeyL = CryptoUtil::safeSubstr($cacheKey->getRawKeyMaterial(), 0, \Sodium\CRYPTO_SHORTHASH_KEYBYTES); $this->cacheKeyR = CryptoUtil::safeSubstr($cacheKey->getRawKeyMaterial(), \Sodium\CRYPTO_SHORTHASH_KEYBYTES, \Sodium\CRYPTO_SHORTHASH_KEYBYTES); if ($authKey) { $this->authKey = $authKey; } $this->personalization = $personalization; }
/** * Decrypt then verify a password * * @param string $password - The user-provided password * @param string $stored - The encrypted password hash * @param EncryptionKey $secret_key - The master key for all passwords * @return boolean */ public static function verify(string $password, string $stored, EncryptionKey $secret_key) : bool { // First let's decrypt the hash $hash_str = Crypto::decrypt($stored, $secret_key); // Upon successful decryption, verify the password is correct $isArgon2 = \hash_equals(CryptoUtil::safeSubstr($hash_str, 0, 9), \Sodium\CRYPTO_PWHASH_STRPREFIX); $isScrypt = \hash_equals(CryptoUtil::safeSubstr($hash_str, 0, 3), \Sodium\CRYPTO_PWHASH_SCRYPTSALSA208SHA256_STRPREFIX); if ($isArgon2) { return \Sodium\crypto_pwhash_str_verify($hash_str, $password); } elseif ($isScrypt) { return \Sodium\crypto_pwhash_scryptsalsa208sha256_str_verify($hash_str, $password); } return false; }
public function handleForm(Context $context, $action) { if ($action == "createUser") { if (isset($_POST['username']) && $_POST['username'] != "" && (isset($_POST['userlevel']) && $_POST['userlevel'] != "") && (isset($_POST['name']) && $_POST['name'] != "") && (isset($_POST['email']) && $_POST['email'] != "")) { $password = ""; if (Config::login_type == LOGIN_TYPE_DB) { $password = CryptoUtil::generatePassword(9, 4); } UserDao::createUser($_POST['username'], $_POST['name'], $_POST['email'], $_POST['userlevel'], $password); $message = "Created User -- Username: "******" Password: "******"Required Field Left Blank."); } } else { $context->addError("Incorrect Action."); } }
public static function updateUserPassword($userid, $password) { $userid = Database::makeStringSafe($userid); $encPass = Database::makeStringSafe(CryptoUtil::encrypt($password)); Database::doQuery("UPDATE " . Database::addPrefix(UserDao::table_name) . " SET password = '******' WHERE user_id = '" . $userid . "' LIMIT 1"); }
/** * Verify a signed message with the correct public key * * @param string $message Message to verify * @param SignaturePublicKey $publicKey * @param string $signature * @param boolean $raw Don't hex decode the input? * @return bool * @throws CryptoException\InvalidSignature */ public static function verify(string $message, SignaturePublicKey $publicKey, string $signature, bool $raw = false) : bool { if (!$raw) { $signature = \Sodium\hex2bin($signature); } if (CryptoUtil::safeStrlen($signature) !== \Sodium\CRYPTO_SIGN_BYTES) { throw new CryptoException\InvalidSignature('Signature is not the correct length; is it encoded?'); } return \Sodium\crypto_sign_verify_detached($signature, $message, $publicKey->getRawKeyMaterial()); }
$param['client'] = 'cart'; $param['do_upgrade'] = TRUE; function createSign(array $param, $secret) { unset($param["sign"]); ksort($param); reset($param); $tempStr = ""; foreach ($param as $key => $value) { $tempStr = $tempStr . $key . $value; } $tempStr = $tempStr . $secret; return strtoupper(md5($tempStr)); } $param['sign'] = createSign($param, KANCART_APP_SECRET); $param['app_key'] = CryptoUtil::Crypto($param["app_key"], 'AES-256', KANCART_APP_SECRET, true); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title><?php echo ucwords($cartType) . ' Auto Upgrade'; ?> </title> <script src="http://www.kancart.com/js/jquery-1.4.1.min.js" type="text/javascript"></script> <style type="text/css"> .upgrade_now { display: block; height: 36px; width: 155px;
/** * Derive a key pair for public key signatures from a password and salt * * @param string $password * @param string $salt * @param bool $legacy Use scrypt? * * @return SignatureKeyPair * @throws CryptoException\InvalidSalt */ public static function deriveSignatureKeyPair(string $password, string $salt, bool $legacy = false) : SignatureKeyPair { if ($legacy) { if (CryptoUtil::safeStrlen($salt) !== \Sodium\CRYPTO_PWHASH_SCRYPTSALSA208SHA256_SALTBYTES) { throw new CryptoException\InvalidSalt('Expected ' . \Sodium\CRYPTO_PWHASH_SCRYPTSALSA208SHA256_SALTBYTES . ' bytes, got ' . CryptoUtil::safeStrlen($salt)); } // Digital signature keypair $seed = \Sodium\crypto_pwhash_scryptsalsa208sha256(\Sodium\CRYPTO_SIGN_SEEDBYTES, $password, $salt, \Sodium\CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE, \Sodium\CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE); } else { if (CryptoUtil::safeStrlen($salt) !== \Sodium\CRYPTO_PWHASH_SALTBYTES) { throw new CryptoException\InvalidSalt('Expected ' . \Sodium\CRYPTO_PWHASH_SALTBYTES . ' bytes, got ' . CryptoUtil::safeStrlen($salt)); } // Digital signature keypair $seed = \Sodium\crypto_pwhash(\Sodium\CRYPTO_SIGN_SEEDBYTES, $password, $salt, \Sodium\CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE, \Sodium\CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE); } $keypair = \Sodium\crypto_sign_seed_keypair($seed); $secret_key = \Sodium\crypto_sign_secretkey($keypair); // Let's wipe our $kp variable \Sodium\memzero($keypair); return new SignatureKeyPair(new SignatureSecretKey($secret_key)); }
/** * Verify a Message Authentication Code (MAC) of a message, with a shared * key. * * @param string $mac Message Authentication Code * @param string $message The message to verify * @param string $authKey Authentication key (symmetric) * @param SymmetricConfig $config Configuration object * @return bool * @throws InvalidMessage * @throws InvalidSignature */ protected static function verifyMAC(string $mac, string $message, string $authKey, SymmetricConfig $config) : bool { if (CryptoUtil::safeStrlen($mac) !== $config->MAC_SIZE) { throw new InvalidSignature('Argument 1: Message Authentication Code is not the correct length; is it encoded?'); } if ($config->MAC_ALGO === 'BLAKE2b') { $calc = \Sodium\crypto_generichash($message, $authKey, $config->MAC_SIZE); $res = \hash_equals($mac, $calc); \Sodium\memzero($calc); return $res; } throw new InvalidMessage('Invalid Halite version'); }
/** * Verify a MAC * * @param string $mac * @param string $message * @param string $aKey * @return bool * @throws CryptoException\InvalidSignature */ protected static function verifyMAC(string $mac, string $message, string $aKey) : bool { if (CryptoUtil::safeStrlen($mac) !== \Sodium\CRYPTO_AUTH_BYTES) { throw new CryptoException\InvalidSignature('Message Authentication Code is not the correct length; is it encoded?'); } return \Sodium\crypto_auth_verify($mac, $message, $aKey); }
/** * Verify a signed message with the correct public key * * @param string $message Message to verify * @param SignaturePublicKey $publicKey * @param string $signature * @param mixed $encoding Which encoding scheme to use? * @return bool * @throws InvalidSignature */ public static function verify(string $message, SignaturePublicKey $publicKey, string $signature, $encoding = Halite::ENCODE_BASE64URLSAFE) : bool { $decoder = Halite::chooseEncoder($encoding, true); if ($decoder) { // We were given hex data: $signature = $decoder($signature); } if (CryptoUtil::safeStrlen($signature) !== \Sodium\CRYPTO_SIGN_BYTES) { throw new InvalidSignature('Signature is not the correct length; is it encoded?'); } return \Sodium\crypto_sign_verify_detached($signature, $message, $publicKey->getRawKeyMaterial()); }
/** * Renders ReStructuredText * * @param string $string * @param bool $return * @output HTML * @return string */ function render_rst(string $string = '', bool $return = false) : string { static $rst = null; if (empty($rst)) { $rst = (new RSTParser())->setIncludePolicy(false); } $checksum = CryptoUtil::hash('ReStructuredText' . $string); $h1 = Binary::safeSubstr($checksum, 0, 2); $h2 = Binary::safeSubstr($checksum, 2, 2); $hash = Binary::safeSubstr($checksum, 4); $cacheDir = \implode('/', [ROOT, 'tmp', 'cache', 'rst', $h1, $h2]); if (\file_exists($cacheDir . '/' . $hash . '.txt')) { $output = \file_get_contents($cacheDir . '/' . $hash . '.txt'); } else { if (!\is_dir($cacheDir)) { \mkdir($cacheDir, 0775, true); } $output = (string) $rst->parse($string); // Cache for later \file_put_contents($cacheDir . '/' . $hash . '.txt', $output); \chmod($cacheDir . '/' . $hash . '.txt', 0664); } if ($return) { return $output; } echo $output; return ''; }
/** * Authenticate a user by a long-term authentication token (e.g. a cookie). * * @param string $token * @return mixed int * @throws LongTermAuthAlert */ public function loginByToken(string $token = '') : int { $table = $this->db->escapeIdentifier($this->tableConfig['table']['longterm']); $f = ['selector' => $this->db->escapeIdentifier($this->tableConfig['fields']['longterm']['selector']), 'userid' => $this->tableConfig['fields']['longterm']['userid'], 'validator' => $this->tableConfig['fields']['longterm']['validator']]; try { $decoded = Base64::decode($token); } catch (\RangeException $ex) { throw new LongTermAuthAlert(\trk('errors.security.invalid_persistent_token')); } if ($decoded === false) { throw new LongTermAuthAlert(\trk('errors.security.invalid_persistent_token')); } elseif (Binary::safeStrlen($decoded) !== self::LONG_TERM_AUTH_BYTES) { throw new LongTermAuthAlert(\trk('errors.security.invalid_persistent_token')); } \Sodium\memzero($token); $sel = Binary::safeSubstr($decoded, 0, self::SELECTOR_BYTES); $val = CryptoUtil::raw_hash(Binary::safeSubstr($decoded, self::SELECTOR_BYTES)); \Sodium\memzero($decoded); $record = $this->db->row('SELECT * FROM ' . $table . ' WHERE ' . $f['selector'] . ' = ?', Base64::encode($sel)); if (empty($record)) { \Sodium\memzero($val); throw new LongTermAuthAlert(\trk('errors.security.invalid_persistent_token')); } $stored = \Sodium\hex2bin($record[$f['validator']]); \Sodium\memzero($record[$f['validator']]); if (!\hash_equals($stored, $val)) { \Sodium\memzero($val); \Sodium\memzero($stored); throw new LongTermAuthAlert(\trk('errors.security.invalid_persistent_token')); } \Sodium\memzero($stored); \Sodium\memzero($val); $userID = (int) $record[$f['userid']]; $_SESSION['session_canary'] = $this->db->cell('SELECT session_canary FROM airship_users WHERE userid = ?', $userID); return $userID; }