Example #1
1
 public function getInfoByName($filePath)
 {
     $this->MAX_FILE_SIZE_FOR_HASHING = 1024 * 1024;
     $this->absoluteName = $filePath;
     $this->name = str_replace($this->web_root_dir, '.', $filePath);
     $this->ctime = 0;
     $this->mtime = 0;
     $this->owner = '-';
     $this->group = '-';
     $this->access = 0;
     $this->size = -1;
     $this->md5 = '-';
     if (file_exists($filePath)) {
         $this->ctime = filectime($filePath);
         $this->mtime = filemtime($filePath);
         $owner = fileowner($filePath);
         $ownerInfo = function_exists('posix_getpwuid') ? posix_getpwuid($owner) : array('name' => $owner);
         $this->owner = $ownerInfo['name'];
         $group = filegroup($filePath);
         $groupInfo = function_exists('posix_getgrgid') ? posix_getgrgid($group) : array('name' => $group);
         $this->group = $groupInfo['name'];
         $this->access = substr(sprintf('%o', fileperms($filePath)), -4);
         if (is_file($filePath)) {
             $this->size = filesize($filePath);
             if ($this->size <= $this->MAX_FILE_SIZE_FOR_HASHING) {
                 $this->md5 = hash_file('md5', $filePath);
             }
         }
     }
     return true;
 }
 /**
  * Create a new user instance after a valid registration.
  *
  * @param  array $data
  * @return User
  */
 protected function create(array $data)
 {
     if (isset($data['comprador'])) {
         $comprador = $data['comprador'];
     } else {
         $comprador = 0;
     }
     if (isset($data['vendedor'])) {
         $vendedor = $data['vendedor'];
     } else {
         $vendedor = 0;
     }
     if (isset($data['gestor'])) {
         $gestor = $data['gestor'];
     } else {
         $gestor = 0;
     }
     //$request =  Request::all();
     $file = $data['file'];
     $nombre = $file->getClientOriginalName();
     $hash = hash_file('md5', $file);
     \Storage::disk('local')->put("/camara/" . $nombre, \File::get($file));
     Empresa::create(['idEmpresa' => $data['email'], 'nombre' => $data['name'], 'nit' => $data['nit'], 'comprador' => $comprador, 'vendedor' => $vendedor, 'gestor' => $gestor, 'razonSocial' => $data['razonSocial'], 'idEmpresaResiduo' => $data['residuo'], 'telefono' => $data['telefono'], 'direccion' => $data['direccion'], 'camara' => $nombre, 'hash' => $hash]);
     return User::create(['name' => $data['name'], 'email' => $data['email'], 'password' => bcrypt($data['password'])]);
 }
 /**
  * @Route("/suggest-file", name="help_suggestfile")
  * @Method({"POST"})
  * @Template("ChaosTangentFansubEbooksAppBundle:Help:suggest-file.html.twig")
  */
 public function suggestFile(Request $request)
 {
     $form = $this->createForm(new SuggestFileType());
     $form->handleRequest($request);
     if ($form->isValid()) {
         $suggestion = new Suggestion();
         $suggestion->setIp($request->getClientIp())->setType('script');
         // fail early
         $authChecker = $this->get('security.authorization_checker');
         if ($authChecker->isGranted('suggest', $suggestion) === false) {
             // todo clean up upload
             throw new AccessDeniedHttpException('Unable to make series suggestion from that IP address again');
         }
         // todo try/catch
         $suggestFile = $form->getData();
         // set the originally uploaded name
         $suggestFile->uploadedFilename = $suggestFile->file->getClientOriginalName();
         // generate a unique filename
         $filename = (new \DateTime())->format('U') . '-' . hash_file('md5', $suggestFile->file->getPathname());
         $dir = $this->container->getParameter('script_temp_storage');
         // move it and replace the existing file
         $suggestFile->file = $suggestFile->file->move($dir, $filename);
         // update suggestion object
         $suggestion->setData($suggestFile);
         $om = $this->get('doctrine')->getManager();
         $om->persist($suggestion);
         $om->flush();
         return [];
     }
     return ['form' => $form->createView()];
 }
 /**
  * Update a given hash with the sha1 hash of an individual asset
  *
  * @param AssetInterface $asset
  * @param $hash
  */
 protected function hashAsset(AssetInterface $asset, $hash)
 {
     $sourcePath = $asset->getSourcePath();
     $sourceRoot = $asset->getSourceRoot();
     $data = $sourcePath && $sourceRoot && file_exists($sourceRoot . "/" . $sourcePath) ? hash_file('sha1', $sourceRoot . "/" . $sourcePath) : $sourcePath;
     hash_update($hash, $data);
 }
Example #5
0
 /**
  * Builds the archives of the repository.
  *
  * @param array $packages List of packages to dump
  */
 public function dump(array $packages)
 {
     $helper = new ArchiveBuilderHelper($this->output, $this->config['archive']);
     $directory = $helper->getDirectory($this->outputDir);
     $this->output->writeln(sprintf("<info>Creating local downloads in '%s'</info>", $directory));
     $format = isset($this->config['archive']['format']) ? $this->config['archive']['format'] : 'zip';
     $endpoint = isset($this->config['archive']['prefix-url']) ? $this->config['archive']['prefix-url'] : $this->config['homepage'];
     $includeArchiveChecksum = isset($this->config['archive']['checksum']) ? (bool) $this->config['archive']['checksum'] : true;
     $composerConfig = Factory::createConfig();
     $factory = new Factory();
     $io = new ConsoleIO($this->input, $this->output, $this->helperSet);
     $io->loadConfiguration($composerConfig);
     /* @var \Composer\Downloader\DownloadManager $downloadManager */
     $downloadManager = $factory->createDownloadManager($io, $composerConfig);
     /* @var \Composer\Package\Archiver\ArchiveManager $archiveManager */
     $archiveManager = $factory->createArchiveManager($composerConfig, $downloadManager);
     $archiveManager->setOverwriteFiles(false);
     shuffle($packages);
     /* @var \Composer\Package\CompletePackage $package */
     foreach ($packages as $package) {
         if ($helper->isSkippable($package)) {
             continue;
         }
         $this->output->writeln(sprintf("<info>Dumping '%s'.</info>", $package->getName()));
         try {
             if ('pear-library' === $package->getType()) {
                 // PEAR packages are archives already
                 $filesystem = new Filesystem();
                 $packageName = $archiveManager->getPackageFilename($package);
                 $path = realpath($directory) . '/' . $packageName . '.' . pathinfo($package->getDistUrl(), PATHINFO_EXTENSION);
                 if (!file_exists($path)) {
                     $downloadDir = sys_get_temp_dir() . '/composer_archiver/' . $packageName;
                     $filesystem->ensureDirectoryExists($downloadDir);
                     $downloadManager->download($package, $downloadDir, false);
                     $filesystem->ensureDirectoryExists($directory);
                     $filesystem->rename($downloadDir . '/' . pathinfo($package->getDistUrl(), PATHINFO_BASENAME), $path);
                     $filesystem->removeDirectory($downloadDir);
                 }
                 // Set archive format to `file` to tell composer to download it as is
                 $archiveFormat = 'file';
             } else {
                 $path = $archiveManager->archive($package, $format, $directory);
                 $archiveFormat = $format;
             }
             $archive = basename($path);
             $distUrl = sprintf('%s/%s/%s', $endpoint, $this->config['archive']['directory'], $archive);
             $package->setDistType($archiveFormat);
             $package->setDistUrl($distUrl);
             if ($includeArchiveChecksum) {
                 $package->setDistSha1Checksum(hash_file('sha1', $path));
             }
             $package->setDistReference($package->getSourceReference());
         } catch (\Exception $exception) {
             if (!$this->skipErrors) {
                 throw $exception;
             }
             $this->output->writeln(sprintf("<error>Skipping Exception '%s'.</error>", $exception->getMessage()));
         }
     }
 }
Example #6
0
 /**
  * Encrypts the data
  * @param string $data file name
  * @return string
  * @throws \InvalidArgumentException
  * @see hash_file()
  */
 public function encrypt($data)
 {
     if (!is_string($data)) {
         throw new \InvalidArgumentException('data');
     }
     return hash_file($this->getAlgorithm(), $data, $this->getRawOutput());
 }
Example #7
0
 /**
  * Rename uploaded file
  *
  * @param  array  $file files uploaded via HTTP POST
  * @return string $hash sha256 hash of file
  */
 public static function upload($file)
 {
     $path = 'tmp' . time();
     $absolute_path = storage_path("textures/{$path}");
     try {
         if (false === move_uploaded_file($file['tmp_name'], $absolute_path)) {
             throw new \Exception('Failed to remove uploaded files, please check the permission', 1);
         }
     } catch (\Exception $e) {
         Log::warning("Failed to move uploaded file, {$e}");
     } finally {
         if (file_exists($absolute_path)) {
             $hash = hash_file('sha256', $absolute_path);
             if (!Storage::disk('textures')->has($hash)) {
                 Storage::disk('textures')->move($path, $hash);
             } else {
                 // delete the temp file
                 unlink($absolute_path);
             }
             return $hash;
         } else {
             Log::warning("Failed to upload file {$path}");
         }
     }
 }
Example #8
0
 public function upload()
 {
     $request = $this->request;
     if ($request->hasFiles() != true) {
         $this->lackofParmas('files');
     }
     $files = $request->getUploadedFiles();
     $result = array();
     foreach ($files as $key => $file) {
         $hash = hash_file('md5', $file->getTempName());
         $destination = $this->_dir . $hash;
         $array['size'] = $file->getSize();
         $array['mime'] = $file->getRealType();
         $array['hash'] = $hash;
         if (file_exists($destination)) {
             $rs = true;
         } else {
             $rs = $file->moveTo($destination);
         }
         if (file_exists($file->getTempName())) {
             @unlink($file->getTempName());
         }
         if ($rs) {
             $array['result'] = 'success';
         } else {
             $array['result'] = $file->getError();
         }
         $result[$file->getKey()] = $array;
         unset($array);
     }
     $this->ajaxResponse(0, 'success', $result);
 }
Example #9
0
function dircrawl($dir, $hash_array, $extension_exclusions)
{
    $dir = rtrim($dir, "\\/");
    $return = "";
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            if ($file != "." and $file != "..") {
                if (filetype($dir . "\\" . $file) == "dir") {
                    $return .= dircrawl($dir . "\\" . $file, $hash_array, $extension_exclusions);
                } else {
                    if (filetype($dir . "\\" . $file) == "file") {
                        if (!in_array(pathinfo($dir . "\\" . $file, PATHINFO_EXTENSION), $extension_exclusions)) {
                            $hash_output = "";
                            foreach ($hash_array as $hash_type) {
                                $hash_output .= ",\"" . hash_file($hash_type, $dir . "\\" . $file) . "\"";
                            }
                            $return .= "\"" . dirname($dir . "\\" . $file) . "\",\"" . basename($dir . "\\" . $file) . "\",\"" . filesize($dir . "\\" . $file) . "\"" . $hash_output . "\n";
                        }
                    }
                }
            }
        }
    }
    return $return;
}
Example #10
0
 /**
  * {@inheritDoc}
  */
 public function download(PackageInterface $package, $path)
 {
     $url = $package->getDistUrl();
     if (!$url) {
         throw new \InvalidArgumentException('The given package is missing url information');
     }
     $this->filesystem->ensureDirectoryExists($path);
     $fileName = $this->getFileName($package, $path);
     $this->io->write("  - Installing <info>" . $package->getName() . "</info> (<comment>" . VersionParser::formatVersion($package) . "</comment>)");
     $processUrl = $this->processUrl($url);
     try {
         $this->rfs->copy($package->getSourceUrl(), $processUrl, $fileName);
         if (!file_exists($fileName)) {
             throw new \UnexpectedValueException($url . ' could not be saved to ' . $fileName . ', make sure the' . ' directory is writable and you have internet connectivity');
         }
         $checksum = $package->getDistSha1Checksum();
         if ($checksum && hash_file('sha1', $fileName) !== $checksum) {
             throw new \UnexpectedValueException('The checksum verification of the file failed (downloaded from ' . $url . ')');
         }
     } catch (\Exception $e) {
         // clean up
         $this->filesystem->removeDirectory($path);
         throw $e;
     }
 }
Example #11
0
 function test()
 {
     //调用配置文件中的参数
     //import('Common.SampleConf',APP_PATH,'.php');
     //global $BOS_TEST_CONFIG;
     //新建BosClient
     //$client = new BosClient(C('BOS_TEST_CONFIG'));
     //var_dump(C('BOS_TEST_CONFIG'));
     /*$client->createBucket('baiwen');
       $response = $client->listBuckets();
       foreach ($response->buckets as $bucket) {
           print $bucket->name;
       }*/
     // $this->client->putObjectFromString('thxfws', $this->mystring,$this->mystring);
     //$response =$this->client->putObjectFromString($this->bucket, "test/123.txt", '123');
     file_put_contents($this->filename, "test");
     $userMeta = array("private" => "private data");
     $options = array(BosOptions::CONTENT_TYPE => "text/plain", BosOptions::CONTENT_MD5 => base64_encode(hash_file("md5", $this->filename, true)), BosOptions::CONTENT_LENGTH => filesize($this->filename), BosOptions::CONTENT_SHA256 => hash_file("sha256", $this->filename), BosOptions::USER_METADATA => $userMeta);
     $response = $this->client->putObjectFromFile($this->bucket, $this->key, $this->filename, $options);
     /*
             $response = $this->client->getObjectMetadata($this->bucket, 'mytest.txt');
             $arr=get_object_vars($response['lastModified']);
              $utime= strtotime($arr['date']);//转换为时间戳
              $ctime=$utime+8*60*60; 
              $ct_str=date("y-m-d H:i:s",$ctime); //转换为字符串*/
     return $response;
 }
Example #12
0
 /**
  * {@inheritDoc}
  */
 public function download(PackageInterface $package, $path)
 {
     $url = $package->getDistUrl();
     if (!$url) {
         throw new \InvalidArgumentException('The given package is missing url information');
     }
     if (!is_dir($path)) {
         if (file_exists($path)) {
             throw new \UnexpectedValueException($path . ' exists and is not a directory');
         }
         if (!mkdir($path, 0777, true)) {
             throw new \UnexpectedValueException($path . ' does not exist and could not be created');
         }
     }
     $fileName = $this->getFileName($package, $path);
     $this->io->write("  - Package <info>" . $package->getName() . "</info> (<comment>" . $package->getPrettyVersion() . "</comment>)");
     $url = $this->processUrl($url);
     $rfs = new RemoteFilesystem($this->io);
     $rfs->copy($package->getSourceUrl(), $url, $fileName);
     $this->io->write('');
     if (!file_exists($fileName)) {
         throw new \UnexpectedValueException($url . ' could not be saved to ' . $fileName . ', make sure the' . ' directory is writable and you have internet connectivity');
     }
     $checksum = $package->getDistSha1Checksum();
     if ($checksum && hash_file('sha1', $fileName) !== $checksum) {
         throw new \UnexpectedValueException('The checksum verification of the file failed (downloaded from ' . $url . ')');
     }
     $this->io->write('');
 }
 /**
  * Test if an open base dir has been defined.
  * If so, the list of well known root ca bundle locations will get matched against the list of defined basedirs
  * and if none matches, the fallback on the embedded bundle will be activated.
  *
  * @param \Phar $phar The composer phar file.
  *
  * @return void
  */
 public static function setCaFileIfOpenBaseDirInUse(\Phar $phar)
 {
     // No open basedir active - we do not need to check.
     if ('' === ($directories = ini_get('open_basedir'))) {
         return;
     }
     $directories = explode(':', $directories);
     // See list in \Composer\Util\RemoteFilesystem::
     $caBundlePaths = array('/etc/pki/tls/certs/ca-bundle.crt', '/etc/ssl/certs/ca-certificates.crt', '/etc/ssl/ca-bundle.pem', '/usr/local/share/certs/ca-root-nss.crt', '/usr/ssl/certs/ca-bundle.crt', '/opt/local/share/curl/curl-ca-bundle.crt', '/usr/local/share/curl/curl-ca-bundle.crt', '/usr/share/ssl/certs/ca-bundle.crt', '/etc/ssl/cert.pem', '/usr/local/etc/ssl/cert.pem', sys_get_temp_dir());
     // Scan for open base dir intersection of known ca bundle paths.
     foreach ($directories as $directory) {
         foreach ($caBundlePaths as $caBundlePath) {
             if (0 === strncmp($directory, dirname($caBundlePath), strlen($directory))) {
                 return;
             }
         }
     }
     // Fall back to the embedded certificate list otherwise.
     // Note that we can not use the internal mechanism of composer for this, as there sys_get_temp_dir() is used.
     // This will resort to /tmp on most systems which is almost certainly not within the allowed paths.
     if (class_exists('Composer\\CaBundle\\CaBundle')) {
         $file = \Composer\CaBundle\CaBundle::getBundledCaBundlePath();
     } else {
         $file = $phar['res/cacert.pem']->getPathname();
     }
     // Try to unpack cacert.pem and use it.
     $hash = hash_file('sha256', $file);
     $targetPath = rtrim(TL_ROOT . '/system/cache', '\\/') . '/composer-cacert-' . $hash . '.pem';
     if (!file_exists($targetPath) || $hash !== hash_file('sha256', $targetPath)) {
         self::streamCopy($file, $targetPath);
         chmod($targetPath, 0666);
     }
     Messages::addWarning('System certificate bundle not readable, will try to use embedded certificate list.');
     putenv('SSL_CERT_FILE=' . $targetPath);
 }
function getDetails($array, $useHash, $realPath, $dirRoot, $urlPrefix)
{
    foreach ($array as $file) {
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $pathFile = str_replace($realPath, $dirRoot, realPath($file));
        // remove last directory path from arguments. ex : /home/user/doc/file.txt to file.txt
        $realPathFile = str_replace($dirRoot . "/", "", $pathFile);
        // Exclude dir from list
        if (is_dir($file) == false) {
            $files[$realPathFile]['location'] = $realPathFile;
            $files[$realPathFile]['url'] = $urlPrefix . $realPathFile;
            $files[$realPathFile]['type'] = finfo_file($finfo, $file);
            $files[$realPathFile]['size'] = filesize($file);
            $files[$realPathFile]['last_modified'] = date("F d Y H:i:s", filemtime($file));
            if ($useHash == true) {
                $files[$realPathFile]['md5'] = md5_file($file);
                $files[$realPathFile]['crc32'] = hash_file('crc32', $file);
                $files[$realPathFile]['sha1'] = hash_file('sha1', $file);
                $files[$realPathFile]['sha256'] = hash_file('sha256', $file);
                $files[$realPathFile]['sha512'] = hash_file('sha512', $file);
            }
            echo "Processing File " . $realPathFile . " ...\n";
        }
        finfo_close($finfo);
    }
    return array('files' => $files);
}
 public static function getFileHash($file)
 {
     if (!is_file($file)) {
         throw new \Exception(' FAILED: no such file ' . $file, 1);
     }
     return hash_file('crc32b', $file);
 }
Example #16
0
 function layout_version($layout = 'main')
 {
     $get_hash = function ($layout) {
         $hash = '';
         $files = [public_path('assets/css/app.css'), public_path('assets/js/app.js'), resource_path('views/layouts/main.blade.php'), resource_path('views/partials/header.blade.php'), resource_path('views/partials/footer.blade.php')];
         if ($layout != 'main') {
             $files[] = resource_path('views/layouts/' . str_replace('.', DIRECTORY_SEPARATOR, $layout) . '.blade.php');
         }
         foreach ($files as $file) {
             $hash .= hash_file('md5', $file);
         }
         return hash('md5', $hash);
     };
     if (App::environment('local', 'development', 'staging')) {
         if (!($hash = config('version.layout.' . $layout))) {
             $hash = $get_hash($layout);
             config(compact('hash'));
         }
     } else {
         $hash = Cache::remember('version.layout.' . $layout, config('version.cache_duration', 5), function () use($get_hash, $layout) {
             return $get_hash($layout);
         });
     }
     return $hash;
 }
 public function runTest()
 {
     $testResult = false;
     $this->logger->trace('Testing ' . join(DIRECTORY_SEPARATOR, array($this->directory, $this->fileName)));
     $filename = $this->fileName;
     if ($this->directory != null) {
         $filename = join(DIRECTORY_SEPARATOR, array($this->directory, $this->fileName));
     }
     if (file_exists($filename) && is_readable($filename)) {
         $hashOfFile = hash_file(strtolower(str_replace('-', '', $this->checksumAlgorithm)), $filename);
         $this->logger->trace('  Checksum algorithm specified is ' . $this->checksumAlgorithm);
         $this->logger->trace('  The checksum value for the file (' . $this->fileName . ') is [' . $hashOfFile . ']');
         $testResult = true;
         if (strcasecmp($this->checksumValue, $hashOfFile) == 0) {
             $this->logger->info('  The checksum for the file (' . $this->fileName . ') is correct');
             $this->logger->trace('  The checksum value for the file (' . $this->fileName . ') is [' . $hashOfFile . ']');
         } else {
             $this->logger->warn('  The file (' . $this->fileName . ') checksum is not correct. ' . 'Original checksum is (' . $this->checksumValue . '). Computed checksum is (' . $hashOfFile . ')');
         }
     } else {
         $this->logger->warn('  The File [' . $this->fileName . '] is not present and therefore the checksum test fails');
     }
     $this->testProperty->setTestResult($testResult);
     return $testResult;
 }
Example #18
0
function Qiniu_PutFile($upToken, $key, $localFile, $putExtra)
{
    global $QINIU_UP_HOST;
    if ($putExtra === null) {
        $putExtra = new Qiniu_PutExtra();
    }
    $fields = array('token' => $upToken, 'file' => createFile($localFile, $putExtra->MimeType));
    if ($key !== null) {
        $fields['key'] = $key;
    }
    if ($putExtra->CheckCrc) {
        if ($putExtra->CheckCrc === 1) {
            $hash = hash_file('crc32b', $localFile);
            $array = unpack('N', pack('H*', $hash));
            $putExtra->Crc32 = $array[1];
        }
        $fields['crc32'] = sprintf('%u', $putExtra->Crc32);
    }
    if ($putExtra->Params) {
        foreach ($putExtra->Params as $k => $v) {
            $fields[$k] = $v;
        }
    }
    $client = new Qiniu_HttpClient();
    return Qiniu_Client_CallWithForm($client, $QINIU_UP_HOST, $fields, 'multipart/form-data');
}
Example #19
0
function Qiniu_PutFile($upToken, $key, $localFile, $putExtra)
{
    global $QINIU_UP_HOST;
    if ($putExtra === null) {
        $putExtra = new Qiniu_PutExtra();
    }
    if (!empty($putExtra->MimeType)) {
        $localFile .= ';type=' . $putExtra->MimeType;
    }
    $fields = array('token' => $upToken, 'file' => '@' . $localFile);
    if ($key === null) {
        $fname = '?';
    } else {
        $fname = $key;
        $fields['key'] = $key;
    }
    if ($putExtra->CheckCrc) {
        if ($putExtra->CheckCrc === 1) {
            $hash = hash_file('crc32b', $localFile);
            $array = unpack('N', pack('H*', $hash));
            $putExtra->Crc32 = $array[1];
        }
        $fields['crc32'] = sprintf('%u', $putExtra->Crc32);
    }
    $client = new Qiniu_HttpClient();
    return Qiniu_Client_CallWithForm($client, $QINIU_UP_HOST, $fields, 'multipart/form-data');
}
Example #20
0
function pm_version_hash($file)
{
    if (!$file) {
        return false;
    }
    $full_path = get_template_directory() . $file;
    return hash_file('CRC32', $full_path);
}
 /** 
  * getHash
  * Generates a SHA256 Hash from text or path
  *
  * @param string $mixed contains either the path to a file or any other content that is literally processed)
  * @return string
  */
 public function getHash($mixed)
 {
     if (file_exists($mixed)) {
         return hash_file("sha256", $mixed);
     } else {
         return hash("sha256", $mixed);
     }
 }
Example #22
0
File: Hash.php Project: mleko/hash
 /**
  * @param string $algorithm
  * @param string $filename
  * @param bool|false $raw
  * @return string
  */
 public static function hashFile($algorithm, $filename, $raw = false)
 {
     $hash = @hash_file($algorithm, $filename, $raw);
     if (false === $hash) {
         throw new HashException();
     }
     return $hash;
 }
 function testCorrectPassword()
 {
     $lib = $this->encryptFileAndReturnLib();
     //Attempt to decrypt with good passphrase
     $decrypted_file = $lib->decryptFile($this->file_enc, $this->passphrase, $this->file_dec);
     $this->assertTrue(file_exists($decrypted_file));
     $this->assertEqual(hash_file("sha256", $this->file_orig), hash_file("sha256", $decrypted_file));
 }
Example #24
0
 protected function checkEndingAndEtagForView(Request $request, $ending, $viewPath)
 {
     return $this->checkEndingAndEtag($request, $ending, function () use($viewPath) {
         $path = $this->get('kernel')->locateResource($viewPath);
         $etag = hash_file('md5', $path);
         return $etag;
     });
 }
Example #25
0
 public function write(Reflector $reflector)
 {
     $data = $reflector->toArray();
     $hash = hash_file('sha256', $data['getFileName']);
     $fileSize = filesize($data['getFileName']);
     self::$config = [$data['getClassName'] => $data + ['fileSize' => $fileSize, 'fileHash' => $hash]] + self::$config;
     $this->fs->dumpFile(self::PATH . '/config.php', "<?php return " . $this->renderArray(self::$config) . "; " . PHP_EOL . '/*' . PHP_EOL . print_r(self::$config, true) . PHP_EOL . '*/' . PHP_EOL);
 }
Example #26
0
 public function testGetHash()
 {
     $sha1Hash = hash_file('sha1', dirname(__FILE__) . '/assets/foo.txt');
     $this->assertEquals($sha1Hash, $this->fileWithExtension->getHash('sha1'));
     $md5Hash = hash_file('md5', dirname(__FILE__) . '/assets/foo.txt');
     $this->assertEquals($md5Hash, $this->fileWithExtension->getHash('md5'));
     $this->assertEquals($md5Hash, $this->fileWithExtension->getHash());
 }
 /**
  * Rename uploaded file
  *
  * @param  array $file, files uploaded via HTTP POST
  * @return string $hash, sha256 hash of file
  */
 public static function upload($file)
 {
     $dir = dirname(dirname(__FILE__));
     move_uploaded_file($file["tmp_name"], "{$dir}/textures/tmp.png");
     $hash = hash_file('sha256', "{$dir}/textures/tmp.png");
     rename("{$dir}/textures/tmp.png", "{$dir}/textures/" . $hash);
     return $hash;
 }
 public function run($inQuery, $args)
 {
     $hash = file_exists($inQuery) ? hash_file('sha512', $inQuery) : hash('sha512', $inQuery);
     if ($args[1] == 'XML') {
         return array(array('uid' => 'sha512', 'arg' => $hash, 'title' => 'SHA512: ' . $hash, 'icon' => 'icon.png', 'valid' => 'true'));
     }
     return $hash;
 }
Example #29
0
 public static function sha256($file)
 {
     $file = self::get_root() . preg_replace('{[^' . self::$whitelist . ']}i', '-', $file);
     if (self::is_enabled() && file_exists($file)) {
         return hash_file('sha256', $file);
     }
     return false;
 }
Example #30
-1
 /**
  * Upload provided file and create matching FileRecord object
  *
  * @param UploadedFile $file
  * @param $clientIp
  * @return FileRecord
  */
 public function uploadFile(UploadedFile $file, $clientIp)
 {
     $extension = Str::lower($file->getClientOriginalExtension());
     $generatedName = $this->generateName($extension);
     // Create SHA-256 hash of file
     $fileHash = hash_file('sha256', $file->getPathname());
     // Check if file already exists
     $existingFile = FileRecord::where('hash', '=', $fileHash)->first();
     if ($existingFile) {
         return $existingFile;
     }
     // Query previous scans in VirusTotal for this file
     if (config('virustotal.enabled') === true) {
         $this->checkVirusTotalForHash($fileHash);
     }
     // Get filesize
     $filesize = $file->getSize();
     // Check max upload size
     $maxUploadSize = config('upload.max_size');
     if ($filesize > $maxUploadSize) {
         throw new MaxUploadSizeException();
     }
     // Move the file
     $uploadDirectory = config('upload.directory');
     $file->move($uploadDirectory, $generatedName);
     // Create the record
     /** @var FileRecord $record */
     $record = FileRecord::create(['client_name' => $file->getClientOriginalName(), 'generated_name' => $generatedName, 'filesize' => $filesize, 'hash' => $fileHash, 'uploaded_by_ip' => $clientIp]);
     return $record;
 }