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


Python hmac.HMAC属性代码示例

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


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

示例1: seal_aes_ctr_legacy

# 需要导入模块: from cryptography.hazmat.primitives import hmac [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
def seal_aes_ctr_legacy(key_service, secret, digest_method=DEFAULT_DIGEST):
    """
    Encrypts `secret` using the key service.
    You can decrypt with the companion method `open_aes_ctr_legacy`.
    """
    # generate a a 64 byte key.
    # Half will be for data encryption, the other half for HMAC
    key, encoded_key = key_service.generate_key_data(64)
    ciphertext, hmac = _seal_aes_ctr(
        secret, key, LEGACY_NONCE, digest_method,
    )
    return {
        'key': b64encode(encoded_key).decode('utf-8'),
        'contents': b64encode(ciphertext).decode('utf-8'),
        'hmac': codecs.encode(hmac, "hex_codec"),
        'digest': digest_method,
    } 
开发者ID:fugue,项目名称:credstash,代码行数:19,代码来源:credstash.py

示例2: _encrypt_from_parts

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

        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:aliyun,项目名称:oss-ftp,代码行数:21,代码来源:fernet.py

示例3: _encrypt_from_parts

# 需要导入模块: from cryptography.hazmat.primitives import hmac [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac import HMAC [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:tp4a,项目名称:teleport,代码行数:20,代码来源:fernet.py

示例4: test_allowed_unsecured_valid_token

# 需要导入模块: from cryptography.hazmat.primitives import hmac [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
def test_allowed_unsecured_valid_token(self):
        """Test payload data from valid secured token (unsecured allowed)."""
        header = force_bytes(json.dumps({'alg': 'HS256', 'typ': 'JWT'}))
        payload = force_bytes(json.dumps({'foo': 'bar'}))

        # Compute signature
        key = b'mysupersecuretestkey'
        h = hmac.HMAC(key, hashes.SHA256(), backend=default_backend())
        msg = '{}.{}'.format(smart_text(b64encode(header)), smart_text(b64encode(payload)))
        h.update(force_bytes(msg))
        signature = b64encode(h.finalize())

        token = '{}.{}.{}'.format(
            smart_text(b64encode(header)),
            smart_text(b64encode(payload)),
            smart_text(signature)
        )
        token_bytes = force_bytes(token)
        key_text = smart_text(key)
        output = self.backend.get_payload_data(token_bytes, key_text)
        self.assertEqual(output, payload) 
开发者ID:mozilla,项目名称:mozilla-django-oidc,代码行数:23,代码来源:test_auth.py

示例5: test_disallowed_unsecured_valid_token

# 需要导入模块: from cryptography.hazmat.primitives import hmac [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
def test_disallowed_unsecured_valid_token(self):
        """Test payload data from valid secure token (unsecured disallowed)."""
        header = force_bytes(json.dumps({'alg': 'HS256', 'typ': 'JWT'}))
        payload = force_bytes(json.dumps({'foo': 'bar'}))

        # Compute signature
        key = b'mysupersecuretestkey'
        h = hmac.HMAC(key, hashes.SHA256(), backend=default_backend())
        msg = '{}.{}'.format(smart_text(b64encode(header)), smart_text(b64encode(payload)))
        h.update(force_bytes(msg))
        signature = b64encode(h.finalize())

        token = '{}.{}.{}'.format(
            smart_text(b64encode(header)),
            smart_text(b64encode(payload)),
            smart_text(signature)
        )
        token_bytes = force_bytes(token)
        key_text = smart_text(key)
        output = self.backend.get_payload_data(token_bytes, key_text)
        self.assertEqual(output, payload) 
开发者ID:mozilla,项目名称:mozilla-django-oidc,代码行数:23,代码来源:test_auth.py

示例6: test_allowed_unsecured_invalid_token

# 需要导入模块: from cryptography.hazmat.primitives import hmac [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
def test_allowed_unsecured_invalid_token(self):
        """Test payload data from invalid secure token (unsecured allowed)."""
        header = force_bytes(json.dumps({'alg': 'HS256', 'typ': 'JWT'}))
        payload = force_bytes(json.dumps({'foo': 'bar'}))

        # Compute signature
        key = b'mysupersecuretestkey'
        fake_key = b'mysupersecurefaketestkey'
        h = hmac.HMAC(key, hashes.SHA256(), backend=default_backend())
        msg = '{}.{}'.format(smart_text(b64encode(header)), smart_text(b64encode(payload)))
        h.update(force_bytes(msg))
        signature = b64encode(h.finalize())

        token = '{}.{}.{}'.format(
            smart_text(b64encode(header)),
            smart_text(b64encode(payload)),
            smart_text(signature)
        )
        token_bytes = force_bytes(token)
        key_text = smart_text(fake_key)

        with self.assertRaises(SuspiciousOperation) as ctx:
            self.backend.get_payload_data(token_bytes, key_text)
        self.assertEqual(ctx.exception.args[0], 'JWS token verification failed.') 
开发者ID:mozilla,项目名称:mozilla-django-oidc,代码行数:26,代码来源:test_auth.py

示例7: test_disallowed_unsecured_invalid_token

# 需要导入模块: from cryptography.hazmat.primitives import hmac [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
def test_disallowed_unsecured_invalid_token(self):
        """Test payload data from invalid secure token (unsecured disallowed)."""
        header = force_bytes(json.dumps({'alg': 'HS256', 'typ': 'JWT'}))
        payload = force_bytes(json.dumps({'foo': 'bar'}))

        # Compute signature
        key = b'mysupersecuretestkey'
        fake_key = b'mysupersecurefaketestkey'
        h = hmac.HMAC(key, hashes.SHA256(), backend=default_backend())
        msg = '{}.{}'.format(smart_text(b64encode(header)), smart_text(b64encode(payload)))
        h.update(force_bytes(msg))
        signature = b64encode(h.finalize())

        token = '{}.{}.{}'.format(
            smart_text(b64encode(header)),
            smart_text(b64encode(payload)),
            smart_text(signature)
        )
        token_bytes = force_bytes(token)
        key_text = smart_text(fake_key)

        with self.assertRaises(SuspiciousOperation) as ctx:
            self.backend.get_payload_data(token_bytes, key_text)
        self.assertEqual(ctx.exception.args[0], 'JWS token verification failed.') 
开发者ID:mozilla,项目名称:mozilla-django-oidc,代码行数:26,代码来源:test_auth.py

示例8: insert_encrypted_value

# 需要导入模块: from cryptography.hazmat.primitives import hmac [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
def insert_encrypted_value(self, element, encryption_algorithm, encrypted_string):
        """
        Add an encrypted value (key) to the document.
        """
        encrypted_value = element_tree.SubElement(element, "{urn:ietf:params:xml:ns:keyprov:pskc}EncryptedValue")
        encryption_method = element_tree.SubElement(encrypted_value, "{http://www.w3.org/2001/04/xmlenc#}EncryptionMethod")
        encryption_method.set("Algorithm", encryption_algorithm)
        cipher_data = element_tree.SubElement(encrypted_value, "{http://www.w3.org/2001/04/xmlenc#}CipherData")
        cipher_value = element_tree.SubElement(cipher_data, "{http://www.w3.org/2001/04/xmlenc#}CipherValue")
        cipher_value.text = encrypted_string
        # calculate and set MAC using HMAC-SHA512 over data in CipherValue
        if not self.hmac_key:
            raise Exception("Missing HMAC key")
        value_mac = element_tree.SubElement(element, "{urn:ietf:params:xml:ns:keyprov:pskc}ValueMAC")
        hmac_instance = hmac.HMAC(self.hmac_key, hashes.SHA512(), backend=default_backend())
        hmac_instance.update(base64.b64decode(encrypted_string))
        value_mac.text = base64.b64encode(hmac_instance.finalize()).decode('utf-8') 
开发者ID:awslabs,项目名称:speke-reference-server,代码行数:19,代码来源:key_server_common.py

示例9: load_key

# 需要导入模块: from cryptography.hazmat.primitives import hmac [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
def load_key(self, key, key_type, key_encoding):
        # (bytes, EncryptionKeyType, KeyEncodingType) -> bytes
        """Load a raw key from bytes.

        :param bytes key: Raw key bytes to load
        :param EncryptionKeyType key_type: Type of key to load
        :param KeyEncodingType key_encoding: Encoding used to serialize ``key``
        :returns: Loaded key
        :rtype: bytes
        :raises ValueError: if ``key_type`` is not symmetric or ``key_encoding`` is not raw
        """
        if not (key_type is EncryptionKeyType.SYMMETRIC and key_encoding is KeyEncodingType.RAW):
            raise ValueError("Key type must be symmetric and encoding must be raw.")

        if len(key) * 8 < MinimumKeySizes.HMAC.value:
            _LOGGER.warning("HMAC keys smaller than %d bits are unsafe" % MinimumKeySizes.HMAC.value)

        return key 
开发者ID:aws,项目名称:aws-dynamodb-encryption-python,代码行数:20,代码来源:authentication.py

示例10: generate

# 需要导入模块: from cryptography.hazmat.primitives import hmac [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
def generate(self, key_size=DEFAULT_AES_KEY_SIZE):
        """
        Generate a new AES key with the corresponding HMAC key.

        :rtype: :class:`AESKey`
        """
        if key_size < MINIMUM_AES_KEY_SIZE:
            raise ValueError('Unsafe key size: %s' % (key_size))

        aes_key_bytes = os.urandom(int(key_size / 8))
        aes_key_string = Base64WSEncode(aes_key_bytes)

        hmac_key_bytes = os.urandom(int(key_size / 8))
        hmac_key_string = Base64WSEncode(hmac_key_bytes)

        return AESKey(aes_key_string=aes_key_string, hmac_key_string=hmac_key_string,
                      hmac_key_size=key_size, mode='CBC', size=key_size) 
开发者ID:StackStorm,项目名称:st2,代码行数:19,代码来源:crypto.py

示例11: update

# 需要导入模块: from cryptography.hazmat.primitives import hmac [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
def update(self, data):
        ret = b""
        if self.cipher is None:
            key = os.urandom(16)
            nonce = os.urandom(16)
            auth_key = os.urandom(32)
            self.cipher = Cipher(algorithms.AES(key), modes.CTR(nonce), backend=default_backend()).encryptor()
            self.authenticator = HMAC(auth_key, SHA256(), backend=default_backend())
            pad = padding.OAEP(mgf=padding.MGF1(algorithm=SHA1()),
                               algorithm=SHA1(),
                               label=None)
            cipherkey = self.rsa_public_key.encrypt(key + nonce + auth_key, pad)
            ret = FILEMAGIC + struct.pack(">H", len(cipherkey)) + cipherkey
        cur = self.cipher.update(data)
        self.authenticator.update(cur)
        if ret:
            return ret + cur
        else:
            return cur 
开发者ID:aiven,项目名称:pghoard,代码行数:21,代码来源:encryptor.py

示例12: process_header

# 需要导入模块: from cryptography.hazmat.primitives import hmac [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
def process_header(self, data):
        if self._cipher_key_len is None:
            if data[0:6] != FILEMAGIC:
                raise EncryptorError("Invalid magic bytes")
            self._cipher_key_len = struct.unpack(">H", data[6:8])[0]
        else:
            pad = padding.OAEP(mgf=padding.MGF1(algorithm=SHA1()),
                               algorithm=SHA1(),
                               label=None)
            try:
                plainkey = self.rsa_private_key.decrypt(data, 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._header_size = 8 + len(data)

            self.cipher = Cipher(algorithms.AES(key), modes.CTR(nonce), backend=default_backend()).decryptor()
            self.authenticator = HMAC(auth_key, SHA256(), backend=default_backend()) 
开发者ID:aiven,项目名称:pghoard,代码行数:24,代码来源:encryptor.py

示例13: _verify_ciphertext

# 需要导入模块: from cryptography.hazmat.primitives import hmac [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
def _verify_ciphertext(self):
        backend = default_backend()
        h = hmac.HMAC(self.mac_key, hashes.SHA256(), backend=backend)
        stream = self.iv.asOctets() + self.ciphertext
        h.update(stream)
        mac_code = h.finalize()

        if mac_code != self.mac:
            sys.stderr.write("Calculated MAC did not match anticipated MAC\n")
            sys.stderr.write("Calculated MAC: {0}\n".format(mac_code))
            sys.stderr.write("Expected MAC: {0}\n".format(self.mac))
            die()
        if self.DEBUG:
            sys.stderr.write("MAC Calculated over IV and Ciphertext: {0}\n".format(mac_code)) 
开发者ID:fireeye,项目名称:ADFSpoof,代码行数:16,代码来源:EncryptedPfx.py

示例14: _hmac_setup

# 需要导入模块: from cryptography.hazmat.primitives import hmac [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
def _hmac_setup(self, key, payload):
        h = hmac.HMAC(key, self.hashfn, backend=self.backend)
        h.update(payload)
        return h 
开发者ID:latchset,项目名称:jwcrypto,代码行数:6,代码来源:jwa.py

示例15: _mac

# 需要导入模块: from cryptography.hazmat.primitives import hmac [as 别名]
# 或者: from cryptography.hazmat.primitives.hmac import HMAC [as 别名]
def _mac(self, k, a, iv, e):
        al = _encode_int(_bitsize(a), 64)
        h = hmac.HMAC(k, self.hashfn, backend=self.backend)
        h.update(a)
        h.update(iv)
        h.update(e)
        h.update(al)
        m = h.finalize()
        return m[:_inbytes(self.keysize)]

    # RFC 7518 - 5.2.2 
开发者ID:latchset,项目名称:jwcrypto,代码行数:13,代码来源:jwa.py


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