Generate a hash digest string for a file.
424376
def get_hash(path, form='sha1', chunk_size=4096):
    '''
    
    '''
    try:
        hash_type = getattr(hashlib, form)
    except AttributeError:
        raise ValueError('Invalid hash type: {0}'.format(form))
    with open(path, 'rb') as ifile:
        hash_obj = hash_type()
        # read the file in in chunks, not the entire file
        for chunk in iter(lambda: ifile.read(chunk_size), b''):
            hash_obj.update(chunk)
        return hash_obj.hexdigest()
1123208
def hash_file(filename):
    
    hasher = hashlib.sha1()
    with open(filename, 'rb') as f:
        buf = f.read(65536)
        while len(buf) > 0:
            hasher.update(buf)
            buf = f.read(65536)

    return hasher.hexdigest()
272589
async function hash (file) {
  const filesize = await fileUtil.getFileSize(file)

  const chunkSize = 64 * 1024

  const firstBytesPromise = fileUtil.readBytes({
    file,
    chunkSize,
    start: 0
  })

  const lastBytesPromise = fileUtil.readBytes({
    file,
    chunkSize,
    start: filesize - chunkSize
  })

  const [ firstBytes, lastBytes ] = await Promise.all([firstBytesPromise, lastBytesPromise])

  return crypto
    .createHash('md5')
    .update(firstBytes)
    .update(lastBytes)
    .digest('hex')
}
1076419
final byte[] hash(final byte[] input, final int offset, final int len) {
		mdHash.update(input, offset, len);
		return mdHash.digest();
	}
883479
def _path_hash(path, transform, kwargs):
    
    sortedargs = ["%s:%r:%s" % (key, value, type(value))
                  for key, value in sorted(iteritems(kwargs))]
    srcinfo = "{path}:{transform}:{{{kwargs}}}".format(path=os.path.abspath(path),
                                                   transform=transform,
                                                   kwargs=",".join(sortedargs))
    return digest_string(srcinfo)
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()
1286528
def hash_str(string):
    ''''''
    m = hashlib.md5()
    m.update(string)
    dig = m.digest()
    return ''.join(['%x' % ord(x) for x in dig])
398353
def make_hash(s, n_bytes):
    """"""
    raw_h = int(md5(s.encode('utf-8')).hexdigest()[:n_bytes], 16)
    # Make it a signed int.
    return 16**n_bytes//2 - raw_h
1185980
def WriteFileHash(self, path, hash_value):
    
    string = '{0:s}\t{1:s}\n'.format(hash_value, path)

    encoded_string = self._EncodeString(string)
    self._file_object.write(encoded_string)
1345052
def file_digest(source):
    
    hash_sha256 = hashlib.sha256()

    should_close = False

    if isinstance(source, six.string_types):
        should_close = True
        source = open(source, 'rb')

    for chunk in iter(lambda: source.read(_BUFFER_SIZE), b''):
        hash_sha256.update(chunk)

    if should_close:
        source.close()

    return hash_sha256.hexdigest()
693566
def _file_md5(file_):
    
    md5 = hashlib.md5()
    chunk_size = 128 * md5.block_size
    for chunk in iter(lambda: file_.read(chunk_size), b''):
        md5.update(chunk)
    file_.seek(0)
    byte_digest = md5.digest()
    return base64.b64encode(byte_digest).decode()
1166014
def file_hash(load, fnd):
    '''
    
    '''
    if 'env' in load:
        # "env" is not supported; Use "saltenv".
        load.pop('env')

    ret = {}

    if 'saltenv' not in load:
        return ret

    if 'path' not in fnd or 'bucket' not in fnd or not fnd['path']:
        return ret

    cached_file_path = _get_cached_file_name(
            fnd['bucket'],
            load['saltenv'],
            fnd['path'])

    if os.path.isfile(cached_file_path):
        ret['hsum'] = salt.utils.hashutils.get_hash(cached_file_path)
        ret['hash_type'] = 'md5'

    return ret
669432
def new_checksum(self):
        """"""
        if self.context.is_file(self.filename):
            friendly_name = format_path(self.filename)
            logger.debug("Calculating SHA1 of %s ..", friendly_name)
            context = hashlib.sha1()
            context.update(self.context.read_file(self.filename))
            checksum = context.hexdigest()
            logger.debug("The SHA1 digest of %s is %s.", friendly_name, checksum)
            return checksum
802005
def _hashfile(self,filename,blocksize=65536):
        """"""
        logger.debug("Hashing file %s"%(filename))
        hasher=hashlib.sha256()
        afile=open(filename,'rb')
        buf=afile.read(blocksize)
        while len(buf) > 0:
            hasher.update(buf)
            buf = afile.read(blocksize)
        return hasher.hexdigest()
260362
function readAndHashFiles(files) {
    const fileHashes = {};
    const fileContents = {};
    const promises = [];

    function readSingleFile(file) {
        return new Promise((resolve, reject) => {
            fs.readFile(file, (err, data) => {
                if (err) {
                    console.log(err);
                    reject(err);
                    return;
                }
                const hash = crypto.createHash('sha1');
                hash.update(data);
                const bufferHash = hash.digest();
                fileHashes[file] = bufferHash.toString('hex');
                if (file.endsWith('.js') && !file.endsWith('.test.js')) {
                    fileContents[file] = data.toString('utf8');
                }
                resolve();
            });
        });
    }

    files.forEach((file) => {
        promises.push(readSingleFile(file));
    });

    return new Promise((resolve, reject) => {
        Promise.all(promises)
            .then(() => {
                resolve({ files, fileContents, fileHashes });
            })
            .catch(reject);
    });
}
1338350
def checksum_file(scheme, path):
    """"""
    h = getattr(hashlib, scheme)()

    with open(path, 'rb') as f:
        chunk = f.read(65535)
        while chunk:
            h.update(chunk)
            chunk = f.read(65535)
    return h.hexdigest()
1099334
def digester(data):
    """"""
    if not isinstance(data, six.binary_type):
        data = data.encode('utf_8')
    hashof = hashlib.sha1(data).digest()
    encoded_hash = base64.b64encode(hashof)
    if not isinstance(encoded_hash, six.string_types):
        encoded_hash = encoded_hash.decode('utf_8')
    chunked = splitter(encoded_hash, chunksize=60)
    lines = '\n'.join(chunked)
    return lines