/** * Add an autoRun entry. * * @param array $run * @param string $workspace * @string file * @return bool * @throws \Error */ protected function addautoRun(array $run, string $workspace, string $file) : bool { static $db_tpl = null; if ($db_tpl === null) { $db_tpl = \file_get_contents(\dirname(HANGAR_ROOT) . DIRECTORY_SEPARATOR . 'res' . DIRECTORY_SEPARATOR . 'index.php.tmp'); } $hash = Util::hash($file); switch ($run['type']) { case 'php': \file_put_contents($workspace . DIRECTORY_SEPARATOR . 'autoRun' . DIRECTORY_SEPARATOR . $hash . '.php', Base64::decode($run['data'])); \file_put_contents($workspace . DIRECTORY_SEPARATOR . 'autoRun.php', 'require_once __DIR__ . DIRECTORY_SEPARATOR . "autoRun" . DIRECTORY_SEPARATOR . "' . $hash . '.php";' . "\n", FILE_APPEND); return true; case 'mysql': case 'pgsql': $exec = \str_replace(['@_QUERY_@', '@_DRIVER_@'], [\str_replace('"', '\\"', Base64::decode($run['data'])), $run['type']], $db_tpl); // Save the template file: \file_put_contents($workspace . DIRECTORY_SEPARATOR . 'autoRun' . DIRECTORY_SEPARATOR . $hash . '.php', $exec); // Add the autoRun script to the autoRun list: \file_put_contents($workspace . DIRECTORY_SEPARATOR . 'autoRun.php', 'require_once __DIR__ . DIRECTORY_SEPARATOR . "autoRun" . DIRECTORY_SEPARATOR . $hash . ".php";' . "\n", FILE_APPEND); return true; default: throw new \Error('Unknown type: ' . $run['type']); } }
public function testDecode() { $this->assertEquals('f', Base64::decode('Zg==')); $this->assertEquals('fo', Base64::decode('Zm8=')); $this->assertEquals('foo', Base64::decode('Zm9v')); $this->assertEquals('foob', Base64::decode('Zm9vYg==')); $this->assertEquals('fooba', Base64::decode('Zm9vYmE=')); $this->assertEquals('foobar', Base64::decode('Zm9vYmFy')); }
// print "Zero byte padded length: " . strlen($zp) . "<br/>\n"; print "Zero byte unpadded length: " . strlen($zup) . "<br/><br/>\n"; /** * Test Base16 (hex) encoding. */ $b16enc = Base16::encode($input); $b16dec = Base16::decode($b16enc); // print "Base16 encoded in UTF-8: " . $b16enc . "<br/>"; print "Base16 decoded in UTF-8: " . $b16dec . "<br/><br/>\n"; /** * Test Base64 encoding. */ $b64enc = Base64::encode($input); $b64dec = Base64::decode($b64enc); // print "Base64 encoded in UTF-8: " . $b64enc . "<br/>"; print "Base64 decoded in UTF-8: " . $b64dec . "<br/><br/>\n"; /** * Test creating GUID's. */ print "Created GUID 1: " . GUID::create() . "<br/>"; print "Created GUID 2: " . GUID::create() . "<br/>"; print "Created GUID 3: " . GUID::create() . "<br/><br/>\n"; /** * Test ROT13 encoding. */ $rot13enc = ROT13::encode($input); $rot13dec = ROT13::decode($rot13enc); //
<?php include 'base64.php'; $bs64 = new Base64(); var_dump($bs64->decode("dGVzdA==")); var_dump($bs64->encode("test"));
/** * Create an InternetAddress object from a string * * Recognizes: * <pre> * Timm Friebe <*****@*****.**> * friebe@example.com (Timm Friebe) * "Timm Friebe" <*****@*****.**> * friebe@example.com * <*****@*****.**> * =?iso-8859-1?Q?Timm_Friebe?= <*****@*****.**> * </pre> * * @param string str * @return peer.mail.InternetAddress address object * @throws lang.FormatException in case the string could not be parsed into an address */ public static function fromString($str) { static $matches = array('/^=\\?([^\\?])+\\?([QB])\\?([^\\?]+)\\?= <([^ @]+@[0-9a-z.-]+)>$/i' => 3, '/^<?([^ @]+@[0-9a-z.-]+)>?$/i' => 0, '/^"([^"]+)" <([^ @]+@[0-9a-z.-]+)>$/i' => 2, '/^([^<]+) <([^ @]+@[0-9a-z.-]+)>$/i' => 2, '/^([^ @]+@[0-9a-z.-]+) \\(([^\\)]+)\\)$/i' => 1); $str = trim(chop($str)); foreach ($matches as $match => $def) { if (!preg_match($match, $str, $_)) { continue; } switch ($def) { case 0: $mail = $_[1]; $personal = ''; break; case 1: $mail = $_[1]; $personal = $_[2]; break; case 2: $mail = $_[2]; $personal = $_[1]; break; case 3: $mail = $_[4]; switch (strtoupper($_[2])) { case 'Q': $personal = QuotedPrintable::decode($_[3]); break; case 'B': $personal = Base64::decode($_[3]); break; } break; } break; } // Was it unparsable? if (!isset($mail)) { throw new FormatException('String "' . $str . '" could not be parsed'); } return new InternetAddress($mail, $personal); }
<?php include_once 'config.php'; include_once 'base64.php'; error_reporting(E_ALL); $base64 = new Base64(); //alfa - параметр зашифрованной строки if (!isset($_REQUEST['alfa'])) { exit; } //--- получение параметров из строки $alfa = $_REQUEST['alfa']; $params = $base64->decode($alfa, $CRYPT_KEY, true); parse_str($params); //--- проверка параметров if (!isset($login) || !isset($password) || !isset($symbol)) { $str_result = "error=" . ERR_WRONG_REQUEST; $str_result .= "&error_desc=2"; $str_result .= "&end=" . time(); $str_result = $base64->encode($str_result, $CRYPT_KEY, true); echo 'omega=' . $str_result; exit; } //--- выборка user из USERS $query = "SELECT `id`, `exp_time` FROM `" . $DB_TABLE_USERS . "` WHERE `login`='{$login}' AND `password`='{$password}'"; $result = mysql_query($query); $errno = mysql_errno(); //--- ошибка в запросе if ($errno > 0) { $str_result = "error=" . (ERR_MYSQL_ERROR_FIRST + $errno); $str_result .= "&error_desc=" . mysql_error();
/** * @fn get_credentials * @short Returns a set of credentials previously stored into a cookie with Base64 encoding. */ protected function get_credentials() { $parts = array('', '', ''); if (($encoded = Cookie::get('_vc')) !== NULL) { $credentials = Base64::decode($encoded); $parts = explode('%%', $credentials); } return array_combine(array('realname', 'email', 'url'), $parts); }
/** * Validate a request based on $this->session and $this->post data * * @return bool */ public function validateRequest() : bool { if (!isset($this->session[$this->sessionIndex])) { // We don't even have a session array initialized $this->session[$this->sessionIndex] = []; return false; } if (!isset($this->post[$this->formIndex]) || !isset($this->post[$this->formToken])) { // User must transmit a complete index/token pair return false; } // Let's pull the POST data $index = $this->post[$this->formIndex]; $token = $this->post[$this->formToken]; if (!isset($this->session[$this->sessionIndex][$index])) { // CSRF Token not found return false; } if (!\is_string($index) || !\is_string($token)) { return false; } // Grab the value stored at $index $stored = $this->session[$this->sessionIndex][$index]; // We don't need this anymore unset($this->session[$this->sessionIndex][$index]); // Which form action="" is this token locked to? $lockTo = $this->server['REQUEST_URI']; if (\preg_match('#/$#', $lockTo)) { // Trailing slashes are to be ignored $lockTo = Binary::safeSubstr($lockTo, 0, Binary::safeStrlen($lockTo) - 1); } if (!\hash_equals($lockTo, $stored['lockTo'])) { // Form target did not match the request this token is locked to! return false; } // This is the expected token value if ($this->hmac_ip === false) { // We just stored it wholesale $expected = $stored['token']; } else { // We mixed in the client IP address to generate the output $expected = Base64::encode(\hash_hmac($this->hashAlgo, isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '127.0.0.1', Base64::decode($stored['token']), true)); } return \hash_equals($token, $expected); }
public function testDecode() { $this->assertSame(self::$value, $this->defaultEncoding->decode('ZsO4w7hiYXJiYXo')); $this->assertSame(self::$value, $this->nonDefaultEncoding->decode('ZsO4w7hiYXJiYXo=')); }
function afterFind($type, &$data) { if (!empty($data) and is_array($data)) { $fresh_models = false; $_items = array_values($data); if ($data === $_items and !empty($_items[0][$this->alias])) { //this is a modeled data array $fresh_models = true; $this->_get_params_fields(); } $models_list = array_merge(array($this->alias), array_keys($this->hasOne), array_keys($this->belongsTo)); foreach ($data as $k => $record) { if ($fresh_models) { $models_list = array_keys($record); } foreach ($models_list as $model) { if (!empty($data[$k][$model])) { if (isset($data[$k][$model]['extras'])) { $extras = new Base64($data[$k][$model]['extras']); $data[$k][$model]['extras'] = $extras->decode(); } foreach ($this->params_fields as $params_field) { if (isset($data[$k][$model][$params_field])) { $params = new Parameter($data[$k][$model][$params_field]); $data[$k][$model][$params_field] = $params->toArray(); } } if (!in_array($model, array('TagItem', 'Tag')) and !empty($this->hasMany['TagItem']) and isset($data[$k]['Tag'])) { $tags = !is_null(Arr::getVal($data[$k]['Tag'], array('[n]', 'title'))) ? Arr::getVal($data[$k]['Tag'], array('[n]', 'title')) : array(); $data[$k][$model]['tags'] = implode(',', $tags); } } } } } }
/** * @fn function valid_key($key, $username, $cleartext) * @short Singular license validator */ public static function valid_key($key, $username = '', &$cleartext = NULL) { $valid = FALSE; if (strlen($key) > 0 && strlen($username) > 0) { // Convert from ISO-8859-1 to UTF-8 $username = iconv("iso-8859-1", "utf-8", $username); // Calculate SHA-1 hash $hash = sha1($username); // $raw_key = Base64::decode($key); $pub_key_path = dirname(__FILE__) . "/../openssl/singular_public_key.pem"; if (file_exists($pub_key_path)) { $fp = fopen($pub_key_path, "r"); $pub_key = fread($fp, filesize($pub_key_path)); fclose($fp); if (($res = openssl_get_publickey($pub_key)) !== FALSE) { /* * NOTE: Here you use the returned resource value */ openssl_public_decrypt($raw_key, $cleartext, $res); $cleartext_parts = explode(';', $cleartext); $valid = $cleartext_parts[0] == $hash; } } } return $valid; }
/** * RFC 4648 Base32 decoding * * @param $str * @return string */ public static function base64Decode(string $str) : string { return Base64::decode($str); }
/** * Decode header if necessary * * @param string $header * @return string */ protected function decode($header) { if (preg_match('/^=\\?([^\\?]+)\\?([QB])\\?([^\\?]+)\\?=$/', $header, $matches)) { if ('Q' === $matches[2]) { return iconv($matches[1], xp::ENCODING, QuotedPrintable::decode($matches[3])); } else { if ('B' === $matches[2]) { return Base64::decode($matches[3]); } else { throw new FormatException('Cannot decode header "' . $header . '"'); } } } return $header; }
/** * Replace the existing long-term authentication cookie * * @param string $token * @param int $userId * @return mixed */ public function rotateToken(string $token, int $userId = 0) { try { $decoded = Base64::decode($token); } catch (\RangeException $ex) { return false; } if ($decoded === false) { return false; } elseif (Binary::safeStrlen($decoded) !== self::LONG_TERM_AUTH_BYTES) { return false; } $sel = Binary::safeSubstr($decoded, 0, self::SELECTOR_BYTES); \Sodium\memzero($decoded); // Delete the old token $this->db->delete($this->tableConfig['table']['longterm'], [$this->tableConfig['fields']['longterm']['selector'] => Base64::encode($sel)]); // Let's get a new token return $this->createAuthToken($userId); }