/** * Encrypts the data * @param string $data file name * @return string * @throws \InvalidArgumentException * @see hash_hmac_file() */ public function encrypt($data) { if (!is_string($data)) { throw new \InvalidArgumentException('data'); } return hash_hmac_file($this->getAlgorithm(), $data, $this->getKey(), $this->getRawOutput()); }
public static function fromFile($filename, $key = null, $algorithm = 'sha256') { if ($key === null) { return md5_file($filename); } else { return hash_hmac_file($algorithm, $filename, $key); } }
public function testHashStream() { $h = new HashHMAC(new Hash('md5'), self::KEY, 64); $expect = hash_hmac_file('md5', __FILE__, self::KEY); $f = fopen(__FILE__, 'r'); $actual = $h->updateStream($f)->sum(); $this->assertEquals($expect, $actual); }
function DeleteUpload($path, $userid) { if (!file_exists($path . '.hash')) { return; } $hash = file_get_contents($path . '.hash'); if ($hash === hash_hmac_file('sha256', $path, $userid . SALT)) { @unlink($path); @unlink($path . '.hash'); } }
public static function video_tag($source, array $attributes = NULL) { if (strpos('//', $source) === FALSE && isset($source[0]) && $source[0] !== '/') { $version = ''; $format = 'mp4'; if (preg_match('#^(?<source>.+)\\.(?<format>\\w+)$#', $source, $matches)) { $source = $matches['source']; $format = $matches['format']; } if (Kohana::$config->load('assets.versionizable') === TRUE) { $file_name = Assets::get_file($source, $format); if ($file_name && is_file($file_name)) { $version = '-' . hash_hmac_file('md5', $file_name, Kohana::$config->load('assets.versionizable.hmac_password')); } } $source = '/assets/' . $source . $version . '.' . $format; $mime = File::mime_by_ext($format); } else { $mime = File::mime($source); } return '<video' . HTML::attributes($attributes) . '><source src="' . $source . '" type="' . $mime . '" /><a href="' . $source . '">' . $source . '</a></video>'; }
/** * newFile * * handle uploading of new file, file goes to files/[userid]/[hash of filecontent+filename] * * @param id_cnt int content id with which the file is linked * @param id_usr int user id for the user whose pic to modify * @param uploadedFile array has info of file, if left empty will use $_FILES * @return success boolean was the procedure succesful? */ public function newFile($id_cnt, $id_usr, $uploadedFile = "") { if ($uploadedFile == "") { $uploadedFile = $_FILES['content_file_upload']; } $hash = hash_hmac_file('sha1', $uploadedFile['tmp_name'], $id_cnt . $uploadedFile['name']); $dir = "files/" . $id_usr . "/"; if (!file_exists($dir)) { mkdir($dir, 0777, true); } if (!file_exists($dir) || file_exists($dir . $hash)) { return false; } move_uploaded_file($uploadedFile['tmp_name'], $dir . $hash); $file = $this->createRow(); $file->id_cnt_fil = $id_cnt; $file->id_usr_fil = $id_usr; $file->filetype_fil = $uploadedFile['type']; $file->filename_fil = $uploadedFile['name']; $file->hash_fil = $hash; $file->created_fil = new Zend_Db_Expr('NOW()'); $file->modified_fil = new Zend_Db_Expr('NOW()'); $file->save(); }
public function upload_gambar_hash($file, $folder, $type, $filesave, $key) { $today = date("Y-m-d_H:i:s"); $folder_resize = $folder; if (!file_exists($folder)) { mkdir($folder, 0777); } if ($type == 1) { $allowed = array('image/pjpeg', 'image/jpeg', 'image/jpeg', 'image/JPG', 'image/X-PNG', 'image/PNG', 'image/png', 'image/x-png'); } else { if ($type == 2) { $allowed = array('application/msword', 'application/pdf', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); } } $c = $_FILES[$file]['type']; //echo("Masuk $c"); $filename = $_FILES[$file]['name']; $name = explode('.', $filename); //echo in_array($_FILES[$file]['type'], $allowed); if (in_array($_FILES[$file]['type'], $allowed)) { echo ".."; //Where the file must be uploaded to if ($folder) { $folder .= '/'; } //Add a '/' at the end of the folder $uploadfile = $folder . $today . "-" . $filename; $result = "{$uploadfile} .."; //Move the file from the stored location to the new location if (move_uploaded_file($_FILES[$file]['tmp_name'], $uploadfile)) { chmod("{$uploadfile}", 0777); $file1 = $_FILES[$file]['name']; //echo "masukkk 12313"; $sha512 = $uploadfile . "-sha512"; //echo "$sha512"; $handle = fopen($sha512, 'w') or die('Cannot open file: ' . $my_file); $data = hash_hmac_file('sha512', $uploadfile, $key); fwrite($handle, $data); /* if ($type != 2) resize("$file1", 300, 300, $folder_resize, ""); */ $result .= "harusnya masuk {$uploadfile} ...."; } else { if (!$_FILES[$file_id]['size']) { //Check if the file is made unlink($uploadfile); //Delete the Empty file $file_name = ''; $result .= "Empty file found - please use a valid file."; //Show the error message } else { chmod($uploadfile, 0777); //Make it universally writable. } } } return array('result' => $result, "hash" => $data, "filename" => $today . "-" . $filename); }
<?php /* Prototype : string hash_hmac_file ( string algo, string filename, string key [, bool raw_output] ) * Description: Generate a keyed hash value using the HMAC method and the contents of a given file * Source code: ext/hash/hash.c * Alias to functions: */ echo "*** Testing hash() : error conditions ***\n"; $file = dirname(__FILE__) . "hash_file.txt"; $key = 'secret'; echo "\n-- Testing hash_hmac_file() function with less than expected no. of arguments --\n"; var_dump(hash_hmac_file()); var_dump(hash_hmac_file('crc32')); var_dump(hash_hmac_file('crc32', $file)); echo "\n-- Testing hash_hmac_file() function with more than expected no. of arguments --\n"; $extra_arg = 10; hash_hmac_file('crc32', $file, $key, TRUE, $extra_arg); echo "\n-- Testing hash_hmac_file() function with invalid hash algorithm --\n"; hash_hmac_file('foo', $file, $key, TRUE); ?> ===Done===
function HandlePicture($field, $type, &$usepic) { global $userid; if ($type == 0) { $extensions = array(".png", ".jpg", ".jpeg", ".gif"); $maxDim = 200; $maxSize = 600 * 1024; $errorname = __('avatar'); } else { if ($type == 1) { $extensions = array(".png", ".gif"); $maxDim = 16; $maxSize = 100 * 1024; $errorname = __('minipic'); } } $fileName = $_FILES[$field]['name']; $fileSize = $_FILES[$field]['size']; $tempFile = $_FILES[$field]['tmp_name']; list($width, $height, $fileType) = getimagesize($tempFile); if ($type == 0 && ($width > 300 || $height > 300)) { return __("That avatar is definitely too big. The avatar field is meant for an avatar, not a wallpaper."); } $extension = strtolower(strrchr($fileName, ".")); if (!in_array($extension, $extensions)) { return format(__("Invalid extension used for {0}. Allowed: {1}"), $errorname, join($extensions, ", ")); } if ($fileSize > $maxSize && !$allowOversize) { return format(__("File size for {0} is too high. The limit is {1} bytes, the uploaded image is {2} bytes."), $errorname, $maxSize, $fileSize) . "</li>"; } $ext = '.blarg'; switch ($fileType) { case 1: $sourceImage = imagecreatefromgif($tempFile); $ext = '.gif'; break; case 2: $sourceImage = imagecreatefromjpeg($tempFile); $ext = '.jpg'; break; case 3: $sourceImage = imagecreatefrompng($tempFile); $ext = '.png'; break; } $randomcrap = '_' . time(); $targetFile = false; $oversize = $width > $maxDim || $height > $maxDim; if ($type == 0) { $targetFile = 'avatars/' . $userid . $randomcrap . $ext; if (!$oversize) { //Just copy it over. copy($tempFile, DATA_DIR . $targetFile); } else { //Resample that mother! $ratio = $width / $height; if ($ratio > 1) { $targetImage = imagecreatetruecolor($maxDim, floor($maxDim / $ratio)); imagecopyresampled($targetImage, $sourceImage, 0, 0, 0, 0, $maxDim, $maxDim / $ratio, $width, $height); } else { $targetImage = imagecreatetruecolor(floor($maxDim * $ratio), $maxDim); imagecopyresampled($targetImage, $sourceImage, 0, 0, 0, 0, $maxDim * $ratio, $maxDim, $width, $height); } imagepng($targetImage, DATA_DIR . $targetFile); imagedestroy($targetImage); } } elseif ($type == 1) { $targetFile = 'minipics/' . $userid . $randomcrap . $ext; if ($oversize) { //Don't allow minipics over $maxDim for anypony. return format(__("Dimensions of {0} must be at most {1} by {1} pixels."), $errorname, $maxDim); } else { copy($tempFile, DATA_DIR . $targetFile); } } // file created to verify that the avatar was created here file_put_contents(DATA_DIR . $targetFile . '.internal', hash_hmac_file('sha256', DATA_DIR . $targetFile, $userid . SALT)); $usepic = '$root/' . $targetFile; return true; }
<?php require 'lib/common.php'; if (!$loguser['root']) { die('no'); } $needfix = Query("SELECT id,picture,minipic FROM {users} WHERE picture='#INTERNAL#' OR minipic='#INTERNAL#'"); while ($user = Fetch($needfix)) { if ($user['picture'] == '#INTERNAL#') { $filename = 'avatars/' . $user['id']; Query("UPDATE {users} SET picture={0} WHERE id={1}", '$root/' . $filename, $user['id']); file_put_contents(DATA_DIR . $filename . '.internal', hash_hmac_file('sha256', DATA_DIR . $filename, $user['id'] . SALT)); } if ($user['minipic'] == '#INTERNAL#') { $filename = 'minipics/' . $user['id']; Query("UPDATE {users} SET minipic={0} WHERE id={1}", '$root/' . $filename, $user['id']); file_put_contents(DATA_DIR . $filename . '.internal', hash_hmac_file('sha256', DATA_DIR . $filename, $user['id'] . SALT)); } } ?> fixed
/** * @test * @dataProvider fileDigestProvider */ public function getFileHmac($path, $valid) { $file = new FileInfoExtra($path); $key = "fileinfoextra_secret"; $invalid_key = "invalid_secret"; if ($valid) { $this->assertEquals(hash_hmac_file('md5', $path, $key), $file->getFileHmac('md5', $key)); $this->assertNotEquals(hash_hmac_file('md5', $path, $invalid_key), $file->getFileHmac('md5', $key)); $this->assertEquals(hash_hmac_file('sha1', $path, $key), $file->getFileHmac(HashAlgorithm::SHA1, $key)); $this->assertEquals(hash_hmac_file('haval160,4', $path, $key), $file->getFileHmac(HashAlgorithm::HAVAL160_4, $key)); $this->assertNotEquals(hash_hmac_file("sha1", $path, $key, true), $file->getFileHmac(HashAlgorithm::SHA1, $key)); $this->assertEquals(hash_hmac_file("sha1", $path, $key, true), $file->getFileHmac(HashAlgorithm::SHA1, $key, true)); } else { $this->assertFalse($file->getFileHmac('md5', $key)); $this->assertFalse($file->getFileHmac(HashAlgorithm::SHA1, $key)); } }
/** * @param string $algo * @param string $key * @param bool $raw_output * @return string|bool */ public function getFileHmac($algo, $key, $raw_output = false) { if (!$this->exists()) { return false; } if ($this->isDir()) { return false; } return hash_hmac_file($algo, $this->getPathname(), $key, $raw_output); }
/** * static funtion * FL_Hash_HMAC_file * * @params (strring) hashMethod * @params (string) FileName * @params (string) key * @params (boolean) binaer * return hex or digit (binär) */ public static function FL_Hash_HMAC_file($hashMethod, $FileName, $key, $binaer = false) { // data obligatory if (!$data) { return false; } // key obligatory if (!$key) { return false; } // hash method must in lower chars $hashMethod = (string) strtolower($hashMethod); // check if hash method in array // alternate throw Exception if (!in_array($hashMethod, self::$hashAlgo)) { return false; } // if file exists if (file_exists($FileName)) { // Returns a string containing the calculated message digest as lowercase hexits // unless raw_output is set to true in which case the raw binary representation // of the message digest is returned. return hash_hmac_file($hashMethod, $FileName, $key, $binaer); } return false; }
/** * {@inheritdoc} */ public function createFileHash($filePath) { return hash_hmac_file($this->algorithm, $filePath, $this->key); }
protected function execute_pandoc_remote($input, $from, $to) { $transaction_id = base64_encode($this->security->get_random_bytes(32)); $url = $this->db_config->get('file_conversion', 'remote_server_url'); $token = $this->db_config->get('file_conversion', 'remote_server_token'); $hmac_key = base64_decode($this->db_config->get('file_conversion', 'hmac_key')); $digest = hash_hmac_file('sha256', $input, $hmac_key); $finfo = new finfo(FILEINFO_MIME); $cfile = new CURLFile($input, $finfo->file($input), 'to_convert'); $post_data = array('to_convert' => $cfile, 'type' => $from, 'covert_to' => $to, 'digest' => $digest, 'token' => $token, 'transaction_id' => $transaction_id); //Request the file $curl = curl_init(); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); curl_setopt($curl, CURLOPT_URL, $url . 'execute_conversion'); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $file_data = curl_exec($curl); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); $output = APPPATH . 'tmp/' . uniqid() . $this->extension_array[$to]; if ($httpcode === 200) { $fp = fopen($output, 'w'); fwrite($fp, $file_data); fclose($fp); } else { return false; } unlink($input); if (!file_exists($output)) { return false; } //Request HMAC for message authentication $post_data = array('token' => $token, 'transaction_id' => $transaction_id); $curl = curl_init(); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); curl_setopt($curl, CURLOPT_URL, $url . 'get_digest'); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $response_digest = curl_exec($curl); curl_close($curl); $digest = hash_hmac_file('sha256', $output, $hmac_key); return $response_digest === $digest ? $output : false; }
/** * Generate a keyed hash value using the HMAC * method and the contents of a given file. * (PHP 5 >= 5.1.2, PECL hash >= 1.1) * * @param string * @param string * @param string * @param bool * @return string */ public function hmacFile($algorithm, $filename, $key, $raw_output = false) { return hash_hmac_file($algorithm, $filename, $key, $raw_output); }
function test_hash_file() { var_dump(hash_file('md5', __DIR__ . '/test_file.txt')); var_dump(hash_hmac_file("md5", __DIR__ . '/test_file.txt', "secret")); }
/** * From a file, computes a keyed hash string using a specified hashing algorithm combined with the HMAC method and * returns it. * * @param string $dataFp The path to the source file. * @param enum $hashType The hashing algorithm to be used (see [Summary](#summary)). * @param string $key The shared secret key. * @param bool $asBinary **OPTIONAL. Default is** `false`. Tells whether the hash should be returned as a raw * binary data. * * @return CUStringObject The computed hash. */ public static function computeHmacFromFile($dataFp, $hashType, $key, $asBinary = false) { assert('is_cstring($dataFp) && is_enum($hashType) && is_cstring($key) && is_bool($asBinary)', vs(isset($this), get_defined_vars())); $dataFp = CFilePath::frameworkPath($dataFp); $strHashType = self::hashTypeToString($hashType); return hash_hmac_file($strHashType, $dataFp, $key, $asBinary); }
function registerRelease() { global $config, $link, $prefix; // check request validity if (ParseINI::parseValue('oc_enable_update', $config) != 1) { throw new Exception('Update disabled on this server.'); } // mandatory parameters if (!isset($_REQUEST['file'])) { throw new Exception('Missing mandatory parameter "file"'); } if (!isset($_REQUEST['hash'])) { throw new Exception('Missing mandatory parameter "hash"'); } if (!isset($_REQUEST['new_version'])) { throw new Exception('Missing mandatory parameter "new_version"'); } if (!isset($_REQUEST['platform'])) { throw new Exception('Missing mandatory parameter "platform"'); } if (!isset($_REQUEST['hash'])) { throw new Exception('Missing mandatory parameter "hash"'); } // authorization $absolutefile = ParseINI::parseValue('oc_update_path', $config) . $_REQUEST['file']; if (!file_exists($absolutefile)) { throw new Exception('Specified file "' . $absolutefile . '" not found.'); } $filehash = hash_hmac_file('sha256', $absolutefile, ParseINI::parseValue('oc_update_secret', $config)); if ($filehash != $_REQUEST['hash']) { throw new Exception('Authorization failure: Hash incorrect.'); } // checks done, now update DB $old_version = array(); if (isset($_REQUEST['old_version']) && !empty($_REQUEST['old_version'])) { $old_version = explode(',', mysql_real_escape_string($_REQUEST['old_version'], $link)); } $delete_old_files = false; if (isset($_REQUEST['delete_old_files']) && $_REQUEST['delete_old_files'] == 'yes') { $delete_old_files = true; } $new_version = mysql_real_escape_string($_REQUEST['new_version'], $link); $platform = mysql_real_escape_string($_REQUEST['platform'], $link); $file = mysql_real_escape_string($_REQUEST['file'], $link); if (!empty($old_version)) { if ($delete_old_files) { $result = mysql_query('SELECT `file` FROM `' . $prefix . 'update` WHERE `new_version` != \'' . $new_version . '\' AND `old_version` != \'\' AND `platform` = \'' . $platform . '\''); while (($row = mysql_fetch_assoc($result)) != false) { unlink(ParseINI::parseValue('oc_update_path', $config) . $row['file']); } } mysql_query('DELETE FROM `' . $prefix . 'update` WHERE `new_version` != \'' . $new_version . '\' AND `old_version` != \'\' AND `platform` = \'' . $platform . '\''); foreach ($old_version as $version) { mysql_query('INSERT INTO `' . $prefix . 'update` (`old_version`, `new_version`, `platform`, `file`) VALUES (\'' . $version . '\', \'' . $new_version . '\', \'' . $platform . '\', \'' . $file . '\')'); } } else { if ($delete_old_files) { $row = mysql_fetch_assoc(mysql_query('SELECT `file` FROM `' . $prefix . 'update` WHERE `old_version` = \'\' AND `platform` = \'' . $platform . '\'')); unlink(ParseINI::parseValue('oc_update_path', $config) . $row['file']); } mysql_query('DELETE FROM `' . $prefix . 'update` WHERE `old_version` = \'\' AND `platform` = \'' . $platform . '\''); mysql_query('INSERT INTO `' . $prefix . 'update` (`old_version`, `new_version`, `platform`, `file`) VALUES (\'\', \'' . $new_version . '\', \'' . $platform . '\', \'' . $file . '\')'); } }
<?php /* Prototype : string hash_hmac_file ( string algo, string filename, string key [, bool raw_output] ) * Description: Generate a keyed hash value using the HMAC method and the contents of a given file * Source code: ext/hash/hash.c * Alias to functions: */ echo "*** Testing hash() : error conditions ***\n"; $file = dirname(__FILE__) . "hash_file.txt"; $key = 'secret'; echo "\n-- Testing hash_hmac_file() function with less than expected no. of arguments --\n"; var_dump(hash_hmac_file()); var_dump(hash_hmac_file('crc32')); var_dump(hash_hmac_file('crc32', $file)); echo "\n-- Testing hash_hmac_file() function with more than expected no. of arguments --\n"; $extra_arg = 10; hash_hmac_file('crc32', $file, $key, TRUE, $extra_arg); echo "\n-- Testing hash_hmac_file() function with invalid hash algorithm --\n"; hash_hmac_file('foo', $file, $key, TRUE); echo "\n-- Testing hash_hmac_file() function with bad path --\n"; hash_hmac_file('crc32', $file . chr(0) . $file, $key, TRUE); ?> ===Done===
function upload_handler() { if ('POST' !== strtoupper($_SERVER['REQUEST_METHOD'])) { return new Jetpack_Error(405, get_status_header_desc(405), 405); } $user = wp_authenticate('', ''); if (!$user || is_wp_error($user)) { return new Jetpack_Error(403, get_status_header_desc(403), 403); } wp_set_current_user($user->ID); if (!current_user_can('upload_files')) { return new Jetpack_Error('cannot_upload_files', 'User does not have permission to upload files', 403); } if (empty($_FILES)) { return new Jetpack_Error('no_files_uploaded', 'No files were uploaded: nothing to process', 400); } foreach (array_keys($_FILES) as $files_key) { if (!isset($_POST["_jetpack_file_hmac_{$files_key}"])) { return new Jetpack_Error('missing_hmac', 'An HMAC for one or more files is missing', 400); } } $media_keys = array_keys($_FILES['media']); $token = Jetpack_Data::get_access_token(get_current_user_id()); if (!$token || is_wp_error($token)) { return new Jetpack_Error('unknown_token', 'Unknown Jetpack token', 403); } $uploaded_files = array(); $global_post = isset($GLOBALS['post']) ? $GLOBALS['post'] : null; unset($GLOBALS['post']); foreach ($_FILES['media']['name'] as $index => $name) { $file = array(); foreach ($media_keys as $media_key) { $file[$media_key] = $_FILES['media'][$media_key][$index]; } list($hmac_provided, $salt) = explode(':', $_POST['_jetpack_file_hmac_media'][$index]); $hmac_file = hash_hmac_file('sha1', $file['tmp_name'], $salt . $token->secret); if ($hmac_provided !== $hmac_file) { $uploaded_files[$index] = (object) array('error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match'); continue; } $_FILES['.jetpack.upload.'] = $file; $post_id = isset($_POST['post_id'][$index]) ? absint($_POST['post_id'][$index]) : 0; if (!current_user_can('edit_post', $post_id)) { $post_id = 0; } $attachment_id = media_handle_upload('.jetpack.upload.', $post_id, array(), array('action' => 'jetpack_upload_file')); if (!$attachment_id) { $uploaded_files[$index] = (object) array('error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site'); } elseif (is_wp_error($attachment_id)) { $uploaded_files[$index] = (object) array('error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message()); } else { $attachment = get_post($attachment_id); $uploaded_files[$index] = (object) array('id' => (string) $attachment_id, 'file' => $attachment->post_title, 'url' => wp_get_attachment_url($attachment_id), 'type' => $attachment->post_mime_type, 'meta' => wp_get_attachment_metadata($attachment_id)); } } if (!is_null($global_post)) { $GLOBALS['post'] = $global_post; } return $uploaded_files; }
<?php hash_file("something"); hash_file("salsa10"); hash_file("salsa20"); hash_file('salsa10'); hash_file('salsa20'); hash_hmac_file("salsa10"); hash_hmac("salsa20"); hash_init("salsa20"); hash("salsa10"); hash("salsa10", "2nd param", 3, false); hash("1st param", "salsa10"); hash_hmac;