function beforeSave(&$data, &$params, $mode) { foreach ($this->params_fields as $params_field) { if (isset($data[$params_field]) and is_array($data[$params_field])) { $p_obj = new Parameter($data[$params_field]); $data[$params_field] = $p_obj->toString(); } } if (isset($data['extras']) and is_array($data['extras'])) { $base_string = new Base64($data['extras']); $data['extras'] = $base_string->encode(); } if (array_key_exists('alias', $data) and empty($data['alias']) and !empty($data['title'])) { $count = 1; $test = $alias = Str::slug($data['title']); redo: $exists = $this->find('first', array('fields' => array($this->pkey), 'conditions' => array('alias' => $test))); if (!empty($exists)) { $count++; $test = $alias . $count; goto redo; } $data['alias'] = $test; } if ($mode == 'create' and in_array('user_id', $this->table_fields) and !isset($data['user_id'])) { $user = Base::getUser(); $data['user_id'] = $user['id']; } }
public function testEncode() { $this->assertEquals('', Base64::encode('')); $this->assertEquals('Zg==', Base64::encode('f')); $this->assertEquals('Zm8=', Base64::encode('fo')); $this->assertEquals('Zm9v', Base64::encode('foo')); $this->assertEquals('Zm9vYg==', Base64::encode('foob')); $this->assertEquals('Zm9vYmE=', Base64::encode('fooba')); $this->assertEquals('Zm9vYmFy', Base64::encode('foobar')); for ($i = 0; $i < 16; $i++) { $data = hash('md5', $i, true); $this->assertEquals(base64_encode($data), Base64::encode($data)); } }
/** * Generate, store, and return the index and token * * @param string $lockTo What URI endpoint this is valid for * @return string[] */ protected function generateToken(string $lockTo) : array { $index = Base64::encode(\random_bytes(18)); $token = Base64::encode(\random_bytes(33)); $this->session[$this->sessionIndex][$index] = ['created' => \intval(\date('YmdHis')), 'uri' => isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : $this->server['SCRIPT_NAME'], 'token' => $token]; if (\preg_match('#/$#', $lockTo)) { $lockTo = Binary::safeSubstr($lockTo, 0, Binary::safeStrlen($lockTo) - 1); } $this->session[$this->sessionIndex][$index]['lockTo'] = $lockTo; $this->recycleTokens(); return [$index, $token]; }
public function testEncode() { $this->assertSame('ZsO4w7hiYXJiYXo', $this->defaultEncoding->encode(self::$value)); $this->assertSame('ZsO4w7hiYXJiYXo=', $this->nonDefaultEncoding->encode(self::$value)); }
/** * Parse a signed JSON response * * @param Response $response * @param SignaturePublicKey $publicKey * @return mixed * @throws SignatureFailed * @throws TransferException */ public function parseSignedJSON(Response $response, SignaturePublicKey $publicKey) { $code = $response->getStatusCode(); if ($code >= 200 && $code < 300) { $body = (string) $response->getBody(); $firstNewLine = \strpos($body, "\n"); // There should be a newline immediately after the base64urlsafe-encoded signature if ($firstNewLine !== self::ENCODED_SIGNATURE_LENGTH) { throw new SignatureFailed(\sprintf("First newline found at position %s, expected %d.\n%s", \print_r($firstNewLine, true), \print_r(self::ENCODED_SIGNATURE_LENGTH, true), Base64::encode($body))); } $sig = Base64UrlSafe::decode(Binary::safeSubstr($body, 0, 88)); $msg = Binary::safeSubstr($body, 89); if (!Asymmetric::verify($msg, $publicKey, $sig, true)) { throw new SignatureFailed(); } return \Airship\parseJSON($msg, true); } throw new TransferException(); }
/** * Creates a random string with the given maximum length * * With the default parameter, the output should contain at least as much randomness as a UUID * * @param int $maxLength the maximum length of the output string (integer multiple of 4) * @return string the new random string */ public static function createRandomString($maxLength = 24) { // calculate how many bytes of randomness we need for the specified string length $bytes = floor(intval($maxLength) / 4) * 3; // get random data $data = openssl_random_pseudo_bytes($bytes); // return the Base64-encoded result return Base64::encode($data, true); }
/** * Add a file to the Blog * * @param &io.File file * @return array url of the file */ public function newMediaObject($file) { return $this->invoke('metaWeblog.newMediaObject', $this->blogid, $this->username, $this->password, array('name' => $file->getFileName(), 'type' => MimeType::getByFilename($file->getFileName()), 'bits' => Base64::encode(FileUtil::getContents($file)))); }
session_start(); require_once "../../config.php"; require_once APP_PATH . "admin/includes/templates/main.tpl.php"; if (!isset($_SESSION['user_id']) || $_SESSION['email'] != SYSTEM_ADMIN_EMAIL) { header('Location: ../login.php'); } if ($_FILES) { require_once APP_PATH . "api/classes/base64.inc.php"; $uploadedFile = $_FILES['encodeFile']['tmp_name']; $uploadedFileSize = filesize($uploadedFile); $encoded = "<div style='margin-top: 30px; text-align: center;'>"; if ($uploadedFileSize) { if ($uploadedFileSize <= 1048576) { $base64 = new Base64(); $encoded .= "<span class='fileHeading'>" . $_FILES['encodeFile']['name'] . " (" . $uploadedFileSize . ") bytes</span><br /><textarea readonly='readonly' onfocus='this.select(); return false;' onclick='this.select(); return false;'>" . $base64->encode($uploadedFile) . "</textarea>"; } else { $encoded .= "<span class='error'>File must be no larger than 1MB.</span>"; } } else { $encoded .= "<span class='error'>There was an error encoding the file.</span>"; } $encoded .= "</div>"; } /***********************MAIN*********************/ $template = new MainTemplate(); $data['title'] = APP_NAME . " Admin"; $data['headerTitle'] = APP_NAME . " - Admin"; $data['menu'] = "divBase64Encoder"; $data['content'] = "\n <div style='width: 300px; margin: 20px auto 0 auto; text-align: center;'>\n <form method='post' enctype='multipart/form-data' action=''>\n <span class='fileHeading'>File:</span> <input type='file' name='encodeFile' /><br /><br />\n <input type='submit' value='Encode File' />\n </form>\n </div>\n " . $encoded; $template->render($data);
/** * RFC 4648 Base64 encoding * * @param $str * @return string */ public static function base64Encode(string $str) : string { return Base64::encode($str); }
/** * Hash a string and store its hash in the Content-Security-Policy header * * @param string $str The data we are hashing * @param string $dir The CSP Directive * @param string $algo Which hash algorithm? * @return string $str */ function csp_hash_str(string $str, string $dir = 'script-src', string $algo = 'sha384') : string { $state = State::instance(); if (isset($state->CSP)) { if ($state->CSP instanceof CSPBuilder) { $preHash = \hash($algo, $str, true); $state->CSP->preHash($dir, Base64::encode($preHash), $algo); return $str; } } return $str; }
/** * @fn set_credentials($realname, $email, $website) * @short Stores a set of credentials into a cookie using Base64 encoding. * @param realname The user's real name. * @param email The user's email address. * @param url The user's website URL. */ protected function set_credentials($realname = '', $email = '', $url = '') { $credentials = $realname . '%%' . $email . '%%' . $url; $encoded = Base64::encode($credentials); Cookie::set('_vc', $encoded, Time::next_year()); }
$zup = ZEROS::unpad($zp); // 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);
/** * 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); }
<?php include 'base64.php'; $bs64 = new Base64(); var_dump($bs64->decode("dGVzdA==")); var_dump($bs64->encode("test"));
echo "\n <script type='text/javascript'>\n alert('There was an error uploading the sound.');\n </script>"; return; } if ($uploadedFileSize > $maxUploadSize) { echo "\n <script type='text/javascript'>\n alert('File must be no larger than 1MB.');\n </script>"; return; } $base64 = new Base64(); $outStr = "\n <script type='text/javascript'>\n var parentDoc = window.top.document;\n\n function initPlayerControls() {\n parentDoc.getElementById('cmdPlay" . $channel . "').disabled = false;\n parentDoc.getElementById('cmdClear" . $channel . "').disabled = false;\n parentDoc.getElementById('uploadedFile" . $channel . "').style.display='block';\n parentDoc.getElementById('cmdUpload" . $channel . "').style.display='block';\n parentDoc.getElementById('imgLoader" . $channel . "').style.display='none';\n }"; if ($uploadedExtension == 'ogg') { //CREATE MP3 FROM OGG HERE $wavFile = $downloadDir . genFileName() . '.wav'; $mp3File = $downloadDir . genFileName() . '.mp3'; system('ffmpeg -i ' . $uploadedFile . ' ' . $wavFile); system('lame -h ' . $wavFile . ' ' . $mp3File); $outStr .= "\n parentDoc.getElementById('channelOgg" . $channel . "').innerHTML = '" . $base64->encode($uploadedFile) . "';\n parentDoc.getElementById('channelMp3" . $channel . "').innerHTML = '" . $base64->encode($mp3File) . "';\n initPlayerControls();"; unlink($wavFile); unlink($mp3File); } else { if ($uploadedExtension == 'mp3') { //CREATE OGG FROM MP3 $wavFile = $downloadDir . genFileName() . '.wav'; $oggFile = $downloadDir . genFileName() . '.ogg'; system('ffmpeg -i ' . $uploadedFile . ' ' . $wavFile); system('sox ' . $wavFile . ' ' . $oggFile); $outStr .= "\n parentDoc.getElementById('channelMp3" . $channel . "').innerHTML = '" . $base64->encode($uploadedFile) . "';\n parentDoc.getElementById('channelOgg" . $channel . "').innerHTML = '" . $base64->encode($oggFile) . "';\n initPlayerControls();"; unlink($wavFile); unlink($oggFile); } else { if ($uploadedExtension == 'wav') { //CREATE OGG AND MP3 FROM WAV
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(); $str_result .= "&end=" . time(); $str_result = $base64->encode($str_result, $CRYPT_KEY, true); echo 'omega=' . $str_result; exit;
public function testEncoding() { $random_bytes = \random_bytes(31); // Backwards compatibility: $encoder = Halite::chooseEncoder(false); $this->assertSame(Hex::encode($random_bytes), $encoder($random_bytes)); $encoder = Halite::chooseEncoder(true); $this->assertSame(null, $encoder); // New encoding in version 3: $encoder = Halite::chooseEncoder(Halite::ENCODE_HEX); $this->assertSame(Hex::encode($random_bytes), $encoder($random_bytes)); $encoder = Halite::chooseEncoder(Halite::ENCODE_BASE32); $this->assertSame(Base32::encode($random_bytes), $encoder($random_bytes)); $encoder = Halite::chooseEncoder(Halite::ENCODE_BASE32HEX); $this->assertSame(Base32Hex::encode($random_bytes), $encoder($random_bytes)); $encoder = Halite::chooseEncoder(Halite::ENCODE_BASE64); $this->assertSame(Base64::encode($random_bytes), $encoder($random_bytes)); $encoder = Halite::chooseEncoder(Halite::ENCODE_BASE64URLSAFE); $this->assertSame(Base64UrlSafe::encode($random_bytes), $encoder($random_bytes)); }