Constructs metadata for encryption
        :param EncryptionMetadata self: this
        :param str md5digest: md5 digest
        :param str hmacdigest: hmac-sha256 digest (data)
        :rtype: dict
        :return: encryption metadata
437877
def convert_to_json_with_mac(self, md5digest, hmacdigest):
        # type: (EncryptionMetadata, str, str) -> dict
        
        # encrypt keys
        enc_content_key = blobxfer.operations.crypto.\
            rsa_encrypt_key_base64_encoded(
                None, self._rsa_public_key, self.symmetric_key)
        enc_sign_key = blobxfer.operations.crypto.\
            rsa_encrypt_key_base64_encoded(
                None, self._rsa_public_key, self.signing_key)
        # generate json
        encjson = {
            EncryptionMetadata._JSON_KEY_ENCRYPTION_MODE:
            EncryptionMetadata._ENCRYPTION_MODE,
            EncryptionMetadata._JSON_KEY_CONTENT_IV:
            blobxfer.util.base64_encode_as_string(self.content_encryption_iv),
            EncryptionMetadata._JSON_KEY_WRAPPEDCONTENTKEY: {
                EncryptionMetadata._JSON_KEY_KEYID: 'private:pem',
                EncryptionMetadata._JSON_KEY_ENCRYPTED_KEY: enc_content_key,
                EncryptionMetadata._JSON_KEY_ENCRYPTED_AUTHKEY: enc_sign_key,
                EncryptionMetadata._JSON_KEY_ALGORITHM:
                EncryptionMetadata._ENCRYPTED_KEY_SCHEME,
            },
            EncryptionMetadata._JSON_KEY_ENCRYPTION_AGENT: {
                EncryptionMetadata._JSON_KEY_PROTOCOL:
                EncryptionMetadata._ENCRYPTION_PROTOCOL_VERSION,
                EncryptionMetadata._JSON_KEY_ENCRYPTION_ALGORITHM:
                EncryptionMetadata._ENCRYPTION_ALGORITHM,
            },
            EncryptionMetadata._JSON_KEY_INTEGRITY_AUTH: {
                EncryptionMetadata._JSON_KEY_ALGORITHM:
                EncryptionMetadata._AUTH_ALGORITHM,
            },
            EncryptionMetadata._JSON_KEY_KEY_WRAPPING_METADATA: {},
        }
        if md5digest is not None:
            encjson[EncryptionMetadata._JSON_KEY_BLOBXFER_EXTENSIONS] = {
                EncryptionMetadata._JSON_KEY_PREENCRYPTED_MD5: md5digest
            }
        if hmacdigest is not None:
            encjson[EncryptionMetadata._JSON_KEY_INTEGRITY_AUTH][
                EncryptionMetadata._JSON_KEY_MAC] = hmacdigest
        bencjson = json.dumps(
            encjson, sort_keys=True, ensure_ascii=False).encode(
                EncryptionMetadata._AUTH_ENCODING_TYPE)
        encjson = {
            EncryptionMetadata._METADATA_KEY_NAME:
            json.dumps(encjson, sort_keys=True)
        }
        # compute MAC over encjson
        hmacsha256 = hmac.new(self._signkey, digestmod=hashlib.sha256)
        hmacsha256.update(bencjson)
        authjson = {
            EncryptionMetadata._JSON_KEY_AUTH_METAAUTH: {
                EncryptionMetadata._JSON_KEY_ALGORITHM:
                EncryptionMetadata._AUTH_ALGORITHM,
                EncryptionMetadata._JSON_KEY_AUTH_ENCODING:
                EncryptionMetadata._AUTH_ENCODING_TYPE,
                EncryptionMetadata._JSON_KEY_MAC:
                blobxfer.util.base64_encode_as_string(hmacsha256.digest()),
            }
        }
        encjson[EncryptionMetadata._METADATA_KEY_AUTH_NAME] = json.dumps(
            authjson, sort_keys=True)
        return encjson
780218
def setMetadata(doc, m):
    """"""
    if doc.isClosed or doc.isEncrypted:
        raise ValueError("operation on closed or encrypted document")
    if type(m) is not dict:
        raise ValueError("arg2 must be a dictionary")
    for k in m.keys():
        if not k in ("author", "producer", "creator", "title", "format",
                     "encryption", "creationDate", "modDate", "subject",
                     "keywords"):
            raise ValueError("invalid dictionary key: " + k)
    d = "<</Author"
    d += getPDFstr(m.get("author", "none"))
    d += "/CreationDate"
    d += getPDFstr(m.get("creationDate", "none"))
    d += "/Creator"
    d += getPDFstr(m.get("creator", "none"))
    d += "/Keywords"
    d += getPDFstr(m.get("keywords", "none"))
    d += "/ModDate"
    d += getPDFstr(m.get("modDate", "none"))
    d += "/Producer"
    d += getPDFstr(m.get("producer", "none"))
    d += "/Subject"
    d += getPDFstr(m.get("subject", "none"))
    d += "/Title"
    d += getPDFstr(m.get("title", "none"))
    d += ">>"
    doc._setMetadata(d)
    doc.initData()
    return
293838
def get_multipart_md5(self, filename, chunk_size=8 * 1024 * 1024):
        
        # Loop through the file contents ...
        md5s = []
        with open(filename, 'rb') as fp:
            while True:
                # Break it into chunks
                data = fp.read(chunk_size)
                # Finish when there are no more
                if not data:
                    break
                # Generate a md5 hash for each chunk
                md5s.append(hashlib.md5(data))

        # Combine the chunks
        digests = b"".join(m.digest() for m in md5s)

        # Generate a new hash using them
        new_md5 = hashlib.md5(digests)

        # Create the ETag as Amazon will
        new_etag = '"%s-%s"' % (new_md5.hexdigest(), len(md5s))

        # Trim it down and pass it back for comparison
        return new_etag.strip('"').strip("'")
1299046
def get_output_metadata(self, path, filename):
        

        checksums = get_checksums(path, ['md5'])
        metadata = {'filename': filename,
                    'filesize': os.path.getsize(path),
                    'checksum': checksums['md5sum'],
                    'checksum_type': 'md5'}

        if self.metadata_only:
            metadata['metadata_only'] = True

        return metadata
423020
def compute_payload_block_hash(this):
    """"""

    return hmac.new(
        hashlib.sha512(
            struct.pack('<Q', this._index) +
            hashlib.sha512(
                this._._.header.value.dynamic_header.master_seed.data +
                this._.transformed_key + b'\x01'
            ).digest()
        ).digest(),
        struct.pack('<Q', this._index) +
        struct.pack('<I', len(this.block_data)) +
        this.block_data, hashlib.sha256
    ).digest()
731329
def encrypted_to(self, raw_data):
        """"""
        # TODO: make this support multiple keys.
        result = self._gpg.list_packets(raw_data)
        if not result.key:
            raise LookupError(
                "Content is not encrypted to a GnuPG key!")
        try:
            return self.find_key_by_keyid(result.key)
        except:
            return self.find_key_by_subkey(result.key)
998241
def md5(self):
        """"""
        md5 = self.meta.get("md5")
        if md5 is None:
            md5 = str(hashlib.md5(self.value).hexdigest())

        return md5
1142269
public static String hmacDigest(String msg, String keyString, String algo) {
		String digest = null;
		try {
			SecretKeySpec key = new SecretKeySpec(
			        (keyString).getBytes("UTF-8"), algo);
			Mac mac = Mac.getInstance(algo);
			mac.init(key);

			byte[] bytes = mac.doFinal(msg.getBytes("ASCII"));

			StringBuilder hash = new StringBuilder();
			
			for (int i = 0; i < bytes.length; i++) {
				String hex = Integer.toHexString(0xFF & bytes[i]);
				if (hex.length() == 1) {
					hash.append('0');
				}
				hash.append(hex);
			}
			digest = hash.toString();

		} catch (Exception e) {
			return null;
		}

		return digest;
	}
1195427
def hash(self, raw: Any) -> str:
        
        with MultiTimerContext(timer, TIMING_HASH):
            raw_bytes = str(raw).encode('utf-8')
            hmac_obj = hmac.new(key=self.key_bytes, msg=raw_bytes,
                                digestmod=self.digestmod)
            return hmac_obj.hexdigest()
1374238
def getMetadataId(self, metadata):
        
        return str(datamodel.VariantSetMetadataCompoundId(
            self.getCompoundId(), 'metadata:' + metadata.key))
469945
private ObjectMetadata createMetadata(int length) {
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(length);
        if (aes256Encryption)
            metadata.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION);
        return metadata;
    }
288372
def encrypt_and_hmac(self, packet):
        
        final = Packet(exchange_type=packet.exchange_type, iSPI=packet.iSPI, rSPI=packet.rSPI, message_id=1)
        # Set up crypto
        iv = os.urandom(16)
        ikecrypto = Camellia(self.SK_ei, iv)
        ikehash = HMAC(self.SK_ai, digestmod=sha256)
        logger.debug('IV: {}'.format(dump(iv)))

        # Encrypt
        plain = bytes(packet)[const.IKE_HEADER.size:]
        ciphertext = ikecrypto.encrypt(plain)
        sk = payloads.SK(next_payload=packet.payloads[0]._type, iv=iv, ciphertext=ciphertext)
        final.add_payload(sk)
        logger.debug(dump(bytes(final)))

        # Sign
        ikehash.update(bytes(final)[:-MACLEN])
        mac = ikehash.digest()[:MACLEN]
        sk.mac(mac)

        logger.debug(dump(bytes(final)))
        return bytes(final)
735037
def calculate_hmac(cls, params):
        
        encoded_params = cls.__encoded_params_for_signature(params)
        # Generate the hex digest for the sorted parameters using the secret.
        return hmac.new(cls.secret.encode(), encoded_params.encode(), sha256).hexdigest()
500588
def parse_digest_response(digest_response_string):
    '''
    
    '''

    parts = parse_parts(digest_response_string, defaults={'algorithm': 'MD5'})
    if not _check_required_parts(parts, _REQUIRED_DIGEST_RESPONSE_PARTS):
        return None

    if not parts['nc'] or [c for c in parts['nc'] if not c in '0123456789abcdefABCDEF']:
        return None
    parts['nc'] = int(parts['nc'], 16)

    digest_response = _build_object_from_parts(parts, _REQUIRED_DIGEST_RESPONSE_PARTS)
    if ('MD5', 'auth') != (digest_response.algorithm, digest_response.qop):
        return None

    return digest_response
496493
def get_file_metadata(self, secure_data_path, version=None):
        """"""
        if not version:
            version = "CURRENT"

        payload = {'versionId': str(version)}
        secret_resp = head_with_retry(str.join('', [self.cerberus_url, '/v1/secure-file/', secure_data_path]),
                                    params=payload, headers=self.HEADERS)

        throw_if_bad_response(secret_resp)

        return secret_resp.headers
359495
def passphrase_to_key(self, passphrase):
        ''''''
        import hashlib
        h = hashlib.new('sha256')
        h.update(passphrase)
        return h.digest()
401661
def _get_digest(self, info):
        
        result = None
        for algo in ('sha256', 'md5'):
            key = '%s_digest' % algo
            if key in info:
                result = (algo, info[key])
                break
        return result