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


Python HMAC.finalize方法代码示例

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


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

示例1: encrypt

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [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

示例2: encrypt_with_hmac

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [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

示例3: checkHMAC

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [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

示例4: _get_hmac

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [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

示例5: Decryptor

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [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

示例6: calculate_hmac

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [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

示例7: __init__

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [as 别名]
  def __init__(self, key, backend=None):
    if backend is None:
      backend = default_backend()

    key = base64.urlsafe_b64decode(key)
    if len(key) != 32:
      raise ValueError(
        "Fernet key must be 32 url-safe base64-encoded bytes."
    )

    h = HMAC(key, hashes.SHA256(), backend=backend)
    h.update(b"\x00")
    self._signing_key = h.finalize()[:16]

    h = HMAC(key, hashes.SHA256(), backend=backend)
    h.update(b"\x01")
    self._encryption_key = h.finalize()[:16]

    self._backend = backend
开发者ID:gidglass,项目名称:db-encryption,代码行数:21,代码来源:fernet2.py

示例8: compute_verify_data

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [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

示例9: generate_mac

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [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

示例10: _a

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [as 别名]
def _a(secret, hash_algorithm, n, seed):
    """
    a() is defined as:
        a(0) = seed
        a(i) = HMAC_hash(secret, A(i-1))
    """
    if n == 0:
        return seed
    else:
        h = HMAC(secret, hash_algorithm, default_backend())
        h.update(_a(secret, hash_algorithm, n - 1, seed))
        return h.finalize()
开发者ID:ashfall,项目名称:tls,代码行数:14,代码来源:prf.py

示例11: _encrypt_cryptography

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [as 别名]
    def _encrypt_cryptography(b_plaintext, b_key1, b_key2, b_iv):
        cipher = C_Cipher(algorithms.AES(b_key1), modes.CTR(b_iv), CRYPTOGRAPHY_BACKEND)
        encryptor = cipher.encryptor()
        padder = padding.PKCS7(algorithms.AES.block_size).padder()
        b_ciphertext = encryptor.update(padder.update(b_plaintext) + padder.finalize())
        b_ciphertext += encryptor.finalize()

        # COMBINE SALT, DIGEST AND DATA
        hmac = HMAC(b_key2, hashes.SHA256(), CRYPTOGRAPHY_BACKEND)
        hmac.update(b_ciphertext)
        b_hmac = hmac.finalize()

        return to_bytes(hexlify(b_hmac), errors='surrogate_or_strict'), hexlify(b_ciphertext)
开发者ID:ernstp,项目名称:ansible,代码行数:15,代码来源:__init__.py

示例12: _p_hash

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [as 别名]
def _p_hash(hash_algorithm, secret, seed, output_length):
    """
    A seed expansion function that uses a single hash function to expand a
    secret and seed into the number of bytes specified by output_length.
    """
    result = bytearray()
    i = 1
    while len(result) < output_length:
        h = HMAC(secret, hash_algorithm, default_backend())
        h.update(_a(secret, hash_algorithm, i, seed))
        h.update(seed)
        result.extend(h.finalize())
        i += 1
    return bytes(result[:output_length])
开发者ID:ashfall,项目名称:tls,代码行数:16,代码来源:prf.py

示例13: __init__

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [as 别名]
    def __init__(self, key, backend=None):
        if backend is None:
            backend = default_backend()

        # initialize a fernet object
        self._f = Fernet(key, backend=backend)

        key = base64.urlsafe_b64decode(key)
        if len(key) != 32:
            raise ValueError(
                "Fernet2 key must be 32 url-safe base64-encoded bytes."
            )

        h0 = HMAC(key, hashes.SHA256(), backend=backend)
        h1 = HMAC(key, hashes.SHA256(), backend=backend)
        # 
        h0 .update(b"0")
        h1 .update(b"1")
        k0 = h0.finalize()[:16]
        k1 = h1.finalize()[:16]

        self._signing_key = k0
        self._encryption_key = k1
        self._backend = backend
开发者ID:NCEghtebas,项目名称:cryptohw3,代码行数:26,代码来源:fernet2.py

示例14: _encrypt_from_parts

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [as 别名]
    def _encrypt_from_parts(self, data, current_time, iv):
        if isinstance(data, six.text_type):
            raise TypeError("Unicode-objects must be encoded before encryption")

        padder = padding.PKCS7(algorithms.AES.block_size).padder()
        padded_data = padder.update(data) + padder.finalize()
        encryptor = Cipher(algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend).encryptor()
        ciphertext = encryptor.update(padded_data) + encryptor.finalize()

        basic_parts = b"\x80" + struct.pack(">Q", current_time) + iv + ciphertext

        h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
        h.update(basic_parts)
        hmac = h.finalize()
        return base64.urlsafe_b64encode(basic_parts + hmac)
开发者ID:hsd315,项目名称:scrapy-test,代码行数:17,代码来源:fernet.py

示例15: _encrypt_from_parts

# 需要导入模块: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac.HMAC import finalize [as 别名]
    def _encrypt_from_parts(self, data, current_time, iv):
        utils._check_bytes("data", data)

        padder = padding.PKCS7(algorithms.AES.block_size).padder()
        padded_data = padder.update(data) + padder.finalize()
        encryptor = Cipher(
            algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend
        ).encryptor()
        ciphertext = encryptor.update(padded_data) + encryptor.finalize()

        basic_parts = (
            b"\x80" + struct.pack(">Q", current_time) + iv + ciphertext
        )

        h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
        h.update(basic_parts)
        hmac = h.finalize()
        return base64.urlsafe_b64encode(basic_parts + hmac)
开发者ID:ctrlaltdel,项目名称:neutrinator,代码行数:20,代码来源:fernet.py


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