当前位置: 首页>>代码示例>>Python>>正文


Python HMAC.update方法代码示例

本文整理汇总了Python中cryptography.hazmat.primitives.hmac.HMAC.update方法的典型用法代码示例。如果您正苦于以下问题:Python HMAC.update方法的具体用法?Python HMAC.update怎么用?Python HMAC.update使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cryptography.hazmat.primitives.hmac.HMAC的用法示例。


在下文中一共展示了HMAC.update方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: salted_hmac

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import update [as 别名]
def salted_hmac(key_salt, value, secret=None):
    """
    Returns the HMAC-HASH of 'value', using a key generated from key_salt and a
    secret (which defaults to settings.SECRET_KEY).

    A different key_salt should be passed in for every application of HMAC.

    :type key_salt: any
    :type value: any
    :type secret: any
    :rtype: HMAC
    """
    if secret is None:
        secret = settings.SECRET_KEY

    key_salt = force_bytes(key_salt)
    secret = force_bytes(secret)

    # We need to generate a derived key from our base key.  We can do this by
    # passing the key_salt and our base key through a pseudo-random function and
    # SHA1 works nicely.
    digest = hashes.Hash(settings.CRYPTOGRAPHY_DIGEST,
                         backend=settings.CRYPTOGRAPHY_BACKEND)
    digest.update(key_salt + secret)
    key = digest.finalize()

    # If len(key_salt + secret) > sha_constructor().block_size, the above
    # line is redundant and could be replaced by key = key_salt + secret, since
    # the hmac module does the same thing for keys longer than the block size.
    # However, we need to ensure that we *always* do this.
    h = HMAC(key, settings.CRYPTOGRAPHY_DIGEST,
             backend=settings.CRYPTOGRAPHY_BACKEND)
    h.update(force_bytes(value))
    return h
开发者ID:JD-accounts,项目名称:django-cryptography,代码行数:36,代码来源:crypto.py

示例2: checkHMAC

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import update [as 别名]
    def checkHMAC(self, fp, segments_start, segments_end, fileHMAC):
        '''Check the file's integrity'''
        filehash = HMAC(self.hmackey, primitives.hashes.SHA256(), backend)
        filehash.update(self.FileMACPrefix)
        for segmentIndex, startpos, datalen in self.segment_ranges(segments_start, segments_end):

            print("        Segment %d" % (segmentIndex))
            fp.seek(startpos)
            segmentIV = fp.read(self.SegIVLen)
            segmentMAC = fp.read(self.SegMACLen)

            # Verify the segment's own MAC against the segment data
            segmenthash = HMAC(self.hmackey, primitives.hashes.SHA256(), backend)
            segmenthash.update(segmentIV)
            segmenthash.update(struct.pack('>I', segmentIndex))
            segmenthash.update(fp.read(datalen))

            # The cryptography module doesn't handle truncated HMACs directly
            computed = segmenthash.finalize()
            assert primitives.constant_time.bytes_eq(computed[:self.SegMACLen], segmentMAC)

            # Add the segment's MAC to the file-MAC context
            filehash.update(segmentMAC)

        # Finally, verify the file MAC
        print("        File hash")
        filehash.verify(fileHMAC) # Raises on mismatch.
开发者ID:BossKing10086,项目名称:OmniGroup,代码行数:29,代码来源:DecryptionExample.py

示例3: encrypt_with_hmac

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import update [as 别名]
    def encrypt_with_hmac(self, data, data_id, iv):
        if not isinstance(data, bytes):
            raise TypeError("data must be bytes.")

        if not isinstance(data_id, int):
            raise TypeError("data_id must be int.")

        main_parts = (
            struct.pack(config.FORMAT_CHAR, data_id) + data
        )

        # PKCS7 padding
        padded_data = self.add_padding(main_parts, algorithms.AES.block_size)
        # AES with CBC mode
        encryptor = Cipher(algorithms.AES(self.aes_key), modes.CBC(iv), backend=self.backend).encryptor()
        ciphertext = encryptor.update(padded_data) + encryptor.finalize()

        basic_parts = (
            b"\x80" + iv + ciphertext
        )

        h = HMAC(self.mac_key, hashes.SHA256(), backend=self.backend)
        h.update(basic_parts)
        hmac = h.finalize()
        return basic_parts + hmac
开发者ID:marcjulian,项目名称:pyoram,代码行数:27,代码来源:aes_crypto.py

示例4: verifyThenDecrypt

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import update [as 别名]
def verifyThenDecrypt(cipher, emailTime, key):
	encryptKey = key[16:]
	signKey = key[:16]
	payload = base64.urlsafe_b64decode(cipher)

	#verify timestamp to prevent replay
	try:
		timestamp, = struct.unpack(">Q", payload[1:9])
	except struct.error:
		raise ValueError('Invalid message')
	if timestamp + TTL < emailTime:
		raise Exception('Invalid timestamp: replay attack detected')

	#verify HMAC
	hasher = HMAC(signKey, hashes.SHA256(), backend=default_backend())
	hasher.update(payload[:-32])
	try:
		hasher.verify(payload[-32:])
	except InvalidSignature:
		raise Exception('Invalid HMAC: data modification detected')

	#decrypt cipher text
	iv = payload[9:25]
	ciphertext = payload[25:-32]
	decryptor = Cipher(algorithms.AES(encryptKey), modes.CBC(iv), default_backend()).decryptor()
	paddedPlaintext = decryptor.update(ciphertext)
	paddedPlaintext += decryptor.finalize()
	unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
	plaintext = unpadder.update(paddedPlaintext)
	plaintext += unpadder.finalize()

	return plaintext
开发者ID:minhtritran,项目名称:cryptography-cs6903,代码行数:34,代码来源:project2_functions.py

示例5: _decrypt_data

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import update [as 别名]
    def _decrypt_data(self, data, timestamp, ttl):
        current_time = int(time.time())
        if ttl is not None:
            if timestamp + ttl < current_time:
                raise InvalidToken

            if current_time + _MAX_CLOCK_SKEW < timestamp:
                raise InvalidToken

        h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
        h.update(data[:-32])
        try:
            h.verify(data[-32:])
        except InvalidSignature:
            raise InvalidToken

        iv = data[9:25]
        ciphertext = data[25:-32]
        decryptor = Cipher(
            algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend
        ).decryptor()
        plaintext_padded = decryptor.update(ciphertext)
        try:
            plaintext_padded += decryptor.finalize()
        except ValueError:
            raise InvalidToken
        unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()

        unpadded = unpadder.update(plaintext_padded)
        try:
            unpadded += unpadder.finalize()
        except ValueError:
            raise InvalidToken
        return unpadded
开发者ID:Sp1l,项目名称:cryptography,代码行数:36,代码来源:fernet.py

示例6: decrypt

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import update [as 别名]
def decrypt(privkey, data):
    s = serialize.Deserializer(data)
    iv = s.bytes(16)
    curve = s.uint(2)
    assert curve == 0x02ca
    x_len = s.uint(2)
    assert x_len <= 32 # TODO Should we assert this? And should we assert no leading zero bytes?
    x = s.bytes(x_len)
    y_len = s.uint(2)
    assert y_len <= 32 # TODO Should we assert this? And should we assert no leading zero bytes?
    y = s.bytes(y_len)
    encrypted = s.bytes(-32)
    assert encrypted != b''
    mac = s.bytes(32)
    pubkey = x.rjust(32, b'\x00') + y.rjust(32, b'\x00')
    public_key = _pub_to_public(pubkey)
    private_key = _priv_to_private(privkey)
    secret = private_key.exchange(ec.ECDH(), public_key)
    key = hashlib.sha512(secret).digest()
    enckey = key[0:32]
    mackey = key[32:64]
    maccer = HMAC(mackey, hashes.SHA256(), openssl.backend)
    maccer.update(data[0:-32])
    maccer.verify(mac)
    cipher = Cipher(algorithms.AES(enckey), modes.CBC(iv), openssl.backend)
    decryptor = cipher.decryptor()
    padded = decryptor.update(encrypted) + decryptor.finalize()
    unpadder = padding.PKCS7(128).unpadder()
    return unpadder.update(padded) + unpadder.finalize()
开发者ID:mirrorwish,项目名称:hyperbit,代码行数:31,代码来源:crypto.py

示例7: encrypt

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import update [as 别名]
def encrypt(pubkey, data):
    public_key = _pub_to_public(pubkey)
    private_key = ec.generate_private_key(ec.SECP256K1(), openssl.backend)
    secret = private_key.exchange(ec.ECDH(), public_key)
    key = hashlib.sha512(secret).digest()
    enckey = key[0:32]
    mackey = key[32:64]
    iv = os.urandom(16)
    padder = padding.PKCS7(128).padder()
    paddeddata = padder.update(data) + padder.finalize()
    cipher = Cipher(algorithms.AES(enckey), modes.CBC(iv), openssl.backend)
    encryptor = cipher.encryptor()
    ciphertext = encryptor.update(paddeddata) + encryptor.finalize()
    s = serialize.Serializer()
    s.bytes(iv)
    s.uint(0x02ca, 2)
    public_numbers = private_key.public_key().public_numbers()
    x = public_numbers.x.to_bytes(32, 'big').lstrip(b'\x00')
    s.uint(len(x), 2)
    s.bytes(x)
    y = public_numbers.y.to_bytes(32, 'big').lstrip(b'\x00')
    s.uint(len(y), 2)
    s.bytes(y)
    s.bytes(ciphertext)
    maccer = HMAC(mackey, hashes.SHA256(), openssl.backend)
    maccer.update(s.data)
    mac = maccer.finalize()
    s.bytes(mac)
    return s.data
开发者ID:mirrorwish,项目名称:hyperbit,代码行数:31,代码来源:crypto.py

示例8: _verify_signature

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import update [as 别名]
 def _verify_signature(self, data):
     h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
     h.update(data[:-32])
     try:
         h.verify(data[-32:])
     except InvalidSignature:
         raise InvalidToken
开发者ID:ctrlaltdel,项目名称:neutrinator,代码行数:9,代码来源:fernet.py

示例9: signature

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import update [as 别名]
 def signature(self, value):
     """
     :type value: any
     :rtype: HMAC
     """
     h = HMAC(self.key, self.digest, backend=settings.CRYPTOGRAPHY_BACKEND)
     h.update(force_bytes(value))
     return h
开发者ID:omarwllorente,项目名称:django-cryptography,代码行数:10,代码来源:signing.py

示例10: _get_hmac

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import update [as 别名]
def _get_hmac(key, ciphertext, digest_method):
    hmac = HMAC(
        key,
        get_digest(digest_method),
        backend=default_backend()
    )
    hmac.update(ciphertext)
    return hmac.finalize()
开发者ID:l2ol33rt,项目名称:credstash,代码行数:10,代码来源:credstash.py

示例11: Decryptor

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import update [as 别名]
class Decryptor(object):
    def __init__(self, rsa_private_key_pem):
        if not isinstance(rsa_private_key_pem, bytes):
            rsa_private_key_pem = rsa_private_key_pem.encode("ascii")
        self.rsa_private_key = serialization.load_pem_private_key(
            data=rsa_private_key_pem,
            password=None,
            backend=default_backend())
        self.cipher = None
        self.authenticator = None
        self.buf = b""

    def update(self, data):
        self.buf += data
        if self.cipher is None:
            if len(self.buf) < 8:
                return b""
            if self.buf[0:6] != FILEMAGIC:
                raise EncryptorError("Invalid magic bytes")
            cipherkeylen = struct.unpack(">H", self.buf[6:8])[0]
            if len(self.buf) < 8 + cipherkeylen:
                return b""
            pad = padding.OAEP(mgf=padding.MGF1(algorithm=SHA1()),
                               algorithm=SHA1(),
                               label=None)
            try:
                plainkey = self.rsa_private_key.decrypt(self.buf[8:8 + cipherkeylen], pad)
            except AssertionError:
                raise EncryptorError("Decrypting key data failed")
            if len(plainkey) != 64:
                raise EncryptorError("Integrity check failed")
            key = plainkey[0:16]
            nonce = plainkey[16:32]
            auth_key = plainkey[32:64]

            self.cipher = Cipher(algorithms.AES(key), modes.CTR(nonce), backend=default_backend()).decryptor()
            self.authenticator = HMAC(auth_key, SHA256(), backend=default_backend())
            self.buf = self.buf[8 + cipherkeylen:]

        if len(self.buf) < 32:
            return b""

        self.authenticator.update(self.buf[:-32])
        result = self.cipher.update(self.buf[:-32])
        self.buf = self.buf[-32:]

        return result

    def finalize(self):
        if self.cipher is None:
            return b""  # empty encrypted input yields empty plaintext output
        elif self.buf != self.authenticator.finalize():
            raise EncryptorError("Integrity check failed")
        result = self.cipher.finalize()
        self.buf = b""
        self.cipher = None
        self.authenticator = None
        return result
开发者ID:hnousiainen,项目名称:pghoard,代码行数:60,代码来源:encryptor.py

示例12: calculate_hmac

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import update [as 别名]
def calculate_hmac(key, data):
    """Shortcut for calculating HMAC of a string."""
    h = HMAC(
        key=key,
        algorithm=hashes.SHA256(),
        backend=backend
    )
    h.update(data)
    return h.finalize()
开发者ID:davehunt,项目名称:PyFxA,代码行数:11,代码来源:crypto.py

示例13: verify_hmac

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import update [as 别名]
def verify_hmac(key, data, signature):
    """Shortcut for verifying HMAC of a string."""
    h = HMAC(
        key=key,
        algorithm=hashes.SHA256(),
        backend=backend
    )
    h.update(data)
    return h.verify(signature)
开发者ID:davehunt,项目名称:PyFxA,代码行数:11,代码来源:crypto.py

示例14: generate_mac

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import update [as 别名]
 def generate_mac(key, data, algorithm="SHA256", backend=BACKEND):
     """ Returns a message authentication code for verifying the integrity and
         authenticity of data by entities that possess the key. 
         
         Note this is a lower level function then apply_mac and
         only returns the mac itself. 
         
         The mac is generated via HMAC with the specified algorithm and key. """
     hasher = HMAC(key, getattr(hashes, algorithm.upper())(), backend=backend)
     hasher.update(algorithm + '::' + data)
     return hasher.finalize()
开发者ID:erose1337,项目名称:pride,代码行数:13,代码来源:security.py

示例15: compute_verify_data

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import update [as 别名]
    def compute_verify_data(self, basekey, handshake_context):
        hash_len = self.hash.digest_size
        finished_key = self.expand_label(basekey, b"finished", b"", hash_len)

        h = Hash(self.hash, backend=default_backend())
        h.update(handshake_context)
        hash_value = h.finalize()

        hm = HMAC(finished_key, self.hash, default_backend())
        hm.update(hash_value)
        return hm.finalize()
开发者ID:commial,项目名称:scapy,代码行数:13,代码来源:hkdf.py


注:本文中的cryptography.hazmat.primitives.hmac.HMAC.update方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。