Calculate the digest of a bootloader image, in the same way the hardware
    secure boot engine would do so. Can be used with a pre-loaded key to update a
    secure bootloader.
489213
def digest_secure_bootloader(args):
    
    if args.iv is not None:
        print("WARNING: --iv argument is for TESTING PURPOSES ONLY")
        iv = args.iv.read(128)
    else:
        iv = os.urandom(128)
    plaintext_image = args.image.read()
    args.image.seek(0)

    # secure boot engine reads in 128 byte blocks (ie SHA512 block
    # size), but also doesn't look for any appended SHA-256 digest
    fw_image = esptool.ESP32FirmwareImage(args.image)
    if fw_image.append_digest:
        if len(plaintext_image) % 128 <= 32:
            # ROM bootloader will read to the end of the 128 byte block, but not
            # to the end of the SHA-256 digest at the end
            new_len = len(plaintext_image) - (len(plaintext_image) % 128)
            plaintext_image = plaintext_image[:new_len]

    # if image isn't 128 byte multiple then pad with 0xFF (ie unwritten flash)
    # as this is what the secure boot engine will see
    if len(plaintext_image) % 128 != 0:
        plaintext_image += b"\xFF" * (128 - (len(plaintext_image) % 128))

    plaintext = iv + plaintext_image

    # Secure Boot digest algorithm in hardware uses AES256 ECB to
    # produce a ciphertext, then feeds output through SHA-512 to
    # produce the digest. Each block in/out of ECB is reordered
    # (due to hardware quirks not for security.)

    key = _load_hardware_key(args.keyfile)
    aes = pyaes.AESModeOfOperationECB(key)
    digest = hashlib.sha512()

    for block in get_chunks(plaintext, 16):
        block = block[::-1]  # reverse each input block

        cipher_block = aes.encrypt(block)
        # reverse and then byte swap each word in the output block
        cipher_block = cipher_block[::-1]
        for block in get_chunks(cipher_block, 4):
            # Python hashlib can build each SHA block internally
            digest.update(block[::-1])

    if args.output is None:
        args.output = os.path.splitext(args.image.name)[0] + "-digest-0x0000.bin"
    with open(args.output, "wb") as f:
        f.write(iv)
        digest = digest.digest()
        for word in get_chunks(digest, 4):
            f.write(word[::-1])  # swap word order in the result
        f.write(b'\xFF' * (0x1000 - f.tell()))  # pad to 0x1000
        f.write(plaintext_image)
    print("digest+image written to %s" % args.output)
155934
def np_hash(a):
    """"""
    if a is None:
        return hash(None)
    # Ensure that hashes are equal whatever the ordering in memory (C or
    # Fortran)
    a = np.ascontiguousarray(a)
    # Compute the digest and return a decimal int
    return int(hashlib.sha1(a.view(a.dtype)).hexdigest(), 16)
158541
def of_bytes(self, py_bytes):
        
        m = self.hash_algo()
        m.update(py_bytes)
        return self.digest(m)
141840
def _update_image_flash_params(esp, address, args, image):
    
    if len(image) < 8:
        return image  # not long enough to be a bootloader image

    # unpack the (potential) image header
    magic, _, flash_mode, flash_size_freq = struct.unpack("BBBB", image[:4])
    if address != esp.BOOTLOADER_FLASH_OFFSET or magic != esp.ESP_IMAGE_MAGIC:
        return image  # not flashing a bootloader, so don't modify this

    if args.flash_mode != 'keep':
        flash_mode = {'qio':0, 'qout':1, 'dio':2, 'dout': 3}[args.flash_mode]

    flash_freq = flash_size_freq & 0x0F
    if args.flash_freq != 'keep':
        flash_freq = {'40m':0, '26m':1, '20m':2, '80m': 0xf}[args.flash_freq]

    flash_size = flash_size_freq & 0xF0
    if args.flash_size != 'keep':
        flash_size = esp.parse_flash_size_arg(args.flash_size)

    flash_params = struct.pack(b'BB', flash_mode, flash_size + flash_freq)
    if flash_params != image[2:4]:
        print('Flash params set to 0x%04x' % struct.unpack(">H", flash_params))
        image = image[0:2] + flash_params + image[4:]
    return image
73153
synchronized void saveDigestAndRenameCheckpointImage(
      long txid, MD5Hash digest) throws IOException {
    if (!digest.equals(storage.getCheckpointImageDigest(txid))) {
      throw new IOException(
          "Checkpoint image is corrupt: expecting an MD5 checksum of" +
              digest + " but is " + storage.getCheckpointImageDigest(txid));
    }
       
    imageSet.saveDigestAndRenameCheckpointImage(txid, digest);
    
    // So long as this is the newest image available,
    // advertise it as such to other checkpointers
    // from now on
    storage.setMostRecentCheckpointTxId(txid);
  }
6146
def _compute_key(self, id, nbytes):
        """"""
        m = Message()
        m.add_mpint(self.K)
        m.add_bytes(self.H)
        m.add_byte(b(id))
        m.add_bytes(self.session_id)
        # Fallback to SHA1 for kex engines that fail to specify a hex
        # algorithm, or for e.g. transport tests that don't run kexinit.
        hash_algo = getattr(self.kex_engine, "hash_algo", None)
        hash_select_msg = "kex engine {} specified hash_algo {!r}".format(
            self.kex_engine.__class__.__name__, hash_algo
        )
        if hash_algo is None:
            hash_algo = sha1
            hash_select_msg += ", falling back to sha1"
        if not hasattr(self, "_logged_hash_selection"):
            self._log(DEBUG, hash_select_msg)
            setattr(self, "_logged_hash_selection", True)
        out = sofar = hash_algo(m.asbytes()).digest()
        while len(out) < nbytes:
            m = Message()
            m.add_mpint(self.K)
            m.add_bytes(self.H)
            m.add_bytes(sofar)
            digest = hash_algo(m.asbytes()).digest()
            out += digest
            sofar += digest
        return out[:nbytes]
1223523
def _do_digest(data, func):
    """"""
    func = FuncReg.get(func)
    hash = FuncReg.hash_from_func(func)
    if not hash:
        raise ValueError("no available hash function for hash", func)
    hash.update(data)
    return bytes(hash.digest())
358216
def encrypt(data)
      Digest::const_get(algorithm.upcase).hexdigest(build(data, salt))
    end
805716
def hexdigest(self):
        """"""
        if self._pre_computed_hash is None:
            return libssdeep_wrapper.fuzzy_digest(self._state, 0)
        else:
            return self._pre_computed_hash
554980
def sign_digest_deterministic(self, digest, hashfunc=None, sigencode=sigencode_string):
        
        secexp = self.privkey.secret_multiplier
        k = rfc6979.generate_k(
            self.curve.generator.order(), secexp, hashfunc, digest)

        return self.sign_digest(digest, sigencode=sigencode, k=k)
906790
def checksum(fpath, hasher=None, asbytes=False):
    """"""
    def blockiter(fpath, blocksize=0x1000):
        with open(fpath, "rb") as afile:
            block = afile.read(blocksize)
            while len(block) > 0:
                yield block
                block = afile.read(blocksize)
    hasher = hasher or hashlib.md5()
    for block in blockiter(fpath):
        hasher.update(block)
    return (hasher.digest() if asbytes else hasher.hexdigest())
1074083
public static String calculateHash(MessageDigest d, byte[] bytes)
    {
        if (bytes == null)
        {
            return null;
        }

        d.update(bytes);
        return ByteUtilities.encode(d.digest());
    }
888251
def digest(self):
        """"""
        total = 0                           # number of triplets seen
        if self.count == 3:                 # 3 chars = 1 triplet
            total = 1
        elif self.count == 4:               # 4 chars = 4 triplets
            total = 4
        elif self.count > 4:                # otherwise 8 triplets/char less
            total = 8 * self.count - 28     # 28 'missed' during 'ramp-up'

        threshold = total / 256             # threshold for accumulators, using the mean

        code = [0]*32                       # start with all zero bits
        for i in range(256):                # for all 256 accumulators
            if self.acc[i] > threshold:     # if it meets the threshold
                code[i >> 3] += 1 << (i&7)  # set corresponding digest bit, equivalent to i/8, 2 ** (i % 8)

        return code[::-1]
389921
def verify(data, digest)
      if valid_digest?(data, digest)
        true
      else
        raise DynamicImage::Errors::InvalidSignature
      end
    end
1209341
def validate_update(
        filepath: str,
        progress_callback: Callable[[float], None]) -> Tuple[str, str]:
    
    filenames = [ROOTFS_NAME, ROOTFS_HASH_NAME, BOOT_NAME, BOOT_HASH_NAME]

    def zip_callback(progress):
        progress_callback(progress/3.0)

    files, sizes = unzip_update(filepath, zip_callback, filenames, filenames)

    def rootfs_hash_callback(progress):
        progress_callback(progress/3.0 + 0.33)

    rootfs = files.get(ROOTFS_NAME)
    assert rootfs
    rootfs_calc_hash = hash_file(rootfs, rootfs_hash_callback,
                                 file_size=sizes[ROOTFS_NAME])
    rootfs_hashfile = files.get(ROOTFS_HASH_NAME)
    assert rootfs_hashfile
    rootfs_packaged_hash = open(rootfs_hashfile, 'rb').read().strip()
    if rootfs_calc_hash != rootfs_packaged_hash:
        msg = f"Hash mismatch (rootfs): calculated {rootfs_calc_hash} != "\
            f"packaged {rootfs_packaged_hash}"
        LOG.error(msg)
        raise HashMismatch(msg)

    def bootfs_hash_callback(progress):
        progress_callback(progress/3.0 + 0.66)

    bootfs = files.get(BOOT_NAME)
    assert bootfs
    bootfs_calc_hash = hash_file(bootfs, bootfs_hash_callback,
                                 file_size=sizes[BOOT_NAME])
    bootfs_hashfile = files.get(BOOT_HASH_NAME)
    assert bootfs_hashfile
    bootfs_packaged_hash = open(bootfs_hashfile, 'rb').read().strip()
    if bootfs_calc_hash != bootfs_packaged_hash:
        msg = f"Hash mismatch (bootfs): calculated {bootfs_calc_hash} != "\
            f"packged {bootfs_packaged_hash}"
        LOG.error(msg)
        raise HashMismatch(msg)

    return rootfs, bootfs
720623
def digested_image_url(*arguments, &block)
      options = arguments.extract_options!
      options.merge!(digested: false)

      wrap_block = proc { |*args| without_digest_asset_url(block.call(*args)) } if block_given?
      image_url(*arguments, options, &wrap_block)
    end
81028
private static long calculateKetamaHash(final byte[] key) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(key);
            byte[] digest = md5.digest();
            long rv = ((long) (digest[3] & 0xFF) << 24)
                    | ((long) (digest[2] & 0xFF) << 16)
                    | ((long) (digest[1] & 0xFF) << 8)
                    | (digest[0] & 0xFF);
            return rv & 0xffffffffL;
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("Could not encode ketama hash.", e);
        }
    }