Calculate SHA-256 hash of a File

@param file - the File to hash
@return the SHA-256 hash value
@throws IOException
190887
public static String getFileSHA256String(File file) throws IOException {
        MessageDigest messageDigest = getMessageDigest(SHA256);
        return getFileHashString(file, messageDigest);
    }
258703
def hash_file(fileobj):
    
    hasher = hashlib.md5()
    buf = fileobj.read(65536)
    while len(buf) > 0:
        hasher.update(buf)
        buf = fileobj.read(65536)
    return hasher.hexdigest()
1139210
function calculateHash(file, fn) {
  read(file, function(err, bin) {
    if (err) return fn(err);
    fn(null, hash('sha256').update(bin).digest('hex'));
  });
}
1334653
def sha_hash_file(filename):
    
    hash_sha = hashlib.sha1()

    with open(filename, 'rb') as f:
        for chunk in iter(lambda: f.read(1024*1024), b""):
            hash_sha.update(chunk)

    return hash_sha.hexdigest()
911541
public static byte[] md5(File file) throws IOException {
		try (InputStream in = new FileInputStream(file)) {
			return md5(in);
		}
	}
712438
public static byte[] fileBytes(File file) throws IOException {

		FileInputStream fis = new FileInputStream(file);

		return streamBytes(fis);
	}
1276811
def hash_stream(fileobj, hasher=None, blocksize=65536):
    
    hasher = hasher or hashlib.sha1()
    buf = fileobj.read(blocksize)
    while buf:
        hasher.update(buf)
        buf = fileobj.read(blocksize)
    return hasher
747479
public static HashId createHashId(File file) throws IOException {
	try (FileInputStream stream = new FileInputStream(file)) {
	    return createHashId(stream);
	}
    }
1052044
public static byte[] hash(File file) throws IOException {
    return Files.hash(file, Hashing.md5()).asBytes();
  }
316410
public static String sha1(File sourceFile) throws Exception {
        byte[] buffer = new byte[1024];
        MessageDigest complete = MessageDigest.getInstance("SHA-1");
        updateDigest(complete, sourceFile, buffer);
        byte[] bytes = complete.digest();
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
364627
def hash(self, hash):
        
        self.md5 = None
        self.sha1 = None
        self.sha256 = None
        if (hash is None):
            return
        hash_seen = set()
        errors = []
        for entry in hash.split():
            (hash_type, value) = entry.split(':', 1)
            if (hash_type in hash_seen):
                errors.append("Ignored duplicate hash type %s" % (hash_type))
            else:
                hash_seen.add(hash_type)
                if (hash_type == 'md5'):
                    self.md5 = value
                elif (hash_type == 'sha-1'):
                    self.sha1 = value
                elif (hash_type == 'sha-256'):
                    self.sha256 = value
                else:
                    errors.append("Ignored unsupported hash type (%s)" %
                                  (hash_type))
        if (len(errors) > 0):
            raise ValueError(". ".join(errors))
187730
public static byte[] readFile(File file) throws IOException
    {
        //create stream to file
        InputStream inputStream=new FileInputStream(file);

        //read data
        byte[] data=IOHelper.readStream(inputStream);

        return data;
    }
909831
public byte[] getFileBytes(File file) throws IORuntimeException {
		byte[] bytes = cache.get(file);
		if (bytes != null) {
			return bytes;
		}

		// add file
		bytes = FileUtil.readBytes(file);

		if ((maxFileSize != 0) && (file.length() > maxFileSize)) {
			//大于缓存空间，不缓存，直接返回
			return bytes;
		}

		usedSize += bytes.length;

		//文件放入缓存，如果usedSize > capacity，purge()方法将被调用
		cache.put(file, bytes);

		return bytes;
	}
510201
def _checksum(in_file, block_size=65536):
    
    cs = hashlib.sha256()
    with open(in_file, "rb") as f:
        for block in iter(lambda: f.read(block_size), b''):
            cs.update(block)
    return cs.hexdigest()
767526
def hash_file(path, block_size=65536):
    
    sha256 = hashlib.sha256()
    with open(path, 'rb') as f:
        for block in iter(lambda: f.read(block_size), b''):
            sha256.update(block)
    return sha256.hexdigest()
1246025
static function hash_data($file, $offset, $end, $algorithm) {
		static $tempdir = '';
		if (!getid3_lib::intValueSupported($end)) {
			return false;
		}
		switch ($algorithm) {
			case 'md5':
				$hash_function = 'md5_file';
				$unix_call     = 'md5sum';
				$windows_call  = 'md5sum.exe';
				$hash_length   = 32;
				break;

			case 'sha1':
				$hash_function = 'sha1_file';
				$unix_call     = 'sha1sum';
				$windows_call  = 'sha1sum.exe';
				$hash_length   = 40;
				break;

			default:
				throw new Exception('Invalid algorithm ('.$algorithm.') in getid3_lib::hash_data()');
				break;
		}
		$size = $end - $offset;
		while (true) {
			if (GETID3_OS_ISWINDOWS) {

				// It seems that sha1sum.exe for Windows only works on physical files, does not accept piped data
				// Fall back to create-temp-file method:
				if ($algorithm == 'sha1') {
					break;
				}

				$RequiredFiles = array('cygwin1.dll', 'head.exe', 'tail.exe', $windows_call);
				foreach ($RequiredFiles as $required_file) {
					if (!is_readable(GETID3_HELPERAPPSDIR.$required_file)) {
						// helper apps not available - fall back to old method
						break;
					}
				}
				$commandline  = GETID3_HELPERAPPSDIR.'head.exe -c '.$end.' "'.escapeshellarg(str_replace('/', DIRECTORY_SEPARATOR, $file)).'" | ';
				$commandline .= GETID3_HELPERAPPSDIR.'tail.exe -c '.$size.' | ';
				$commandline .= GETID3_HELPERAPPSDIR.$windows_call;

			} else {

				$commandline  = 'head -c'.$end.' '.escapeshellarg($file).' | ';
				$commandline .= 'tail -c'.$size.' | ';
				$commandline .= $unix_call;

			}
			if (preg_match('#(1|ON)#i', ini_get('safe_mode'))) {
				//throw new Exception('PHP running in Safe Mode - backtick operator not available, using slower non-system-call '.$algorithm.' algorithm');
				break;
			}
			return substr(`$commandline`, 0, $hash_length);
		}

		if (empty($tempdir)) {
			// yes this is ugly, feel free to suggest a better way
			require_once(dirname(__FILE__).'/getid3.php');
			$getid3_temp = new getID3();
			$tempdir = $getid3_temp->tempdir;
			unset($getid3_temp);
		}
		// try to create a temporary file in the system temp directory - invalid dirname should force to system temp dir
		if (($data_filename = tempnam($tempdir, 'gI3')) === false) {
			// can't find anywhere to create a temp file, just fail
			return false;
		}

		// Init
		$result = false;

		// copy parts of file
		try {
			getid3_lib::CopyFileParts($file, $data_filename, $offset, $end - $offset);
			$result = $hash_function($data_filename);
		} catch (Exception $e) {
			throw new Exception('getid3_lib::CopyFileParts() failed in getid_lib::hash_data(): '.$e->getMessage());
		}
		unlink($data_filename);
		return $result;
	}
478724
def hash_sha256(buf):
    """"""
    a = hashlib.sha256(buf).hexdigest()
    return (64 - len(a)) * '0' + a