Python cryptography.hazmat.primitives.hmac.HMAC Examples

The following are 30 code examples of cryptography.hazmat.primitives.hmac.HMAC(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cryptography.hazmat.primitives.hmac , or try the search function .
Example #1
Source File: test_auth.py    From mozilla-django-oidc with Mozilla Public License 2.0 6 votes vote down vote up
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) 
Example #2
Source File: authentication.py    From aws-dynamodb-encryption-python with Apache License 2.0 6 votes vote down vote up
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 
Example #3
Source File: crypto.py    From st2 with Apache License 2.0 6 votes vote down vote up
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) 
Example #4
Source File: fernet.py    From quickstart-git2s3 with Apache License 2.0 6 votes vote down vote up
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) 
Example #5
Source File: fernet.py    From teleport with Apache License 2.0 6 votes vote down vote up
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) 
Example #6
Source File: fernet.py    From teleport with Apache License 2.0 6 votes vote down vote up
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) 
Example #7
Source File: fernet.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #8
Source File: key_server_common.py    From speke-reference-server with Apache License 2.0 6 votes vote down vote up
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') 
Example #9
Source File: fernet.py    From teleport with Apache License 2.0 6 votes vote down vote up
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) 
Example #10
Source File: fernet.py    From learn_python3_spider with MIT License 6 votes vote down vote up
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) 
Example #11
Source File: fernet.py    From oss-ftp with MIT License 6 votes vote down vote up
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) 
Example #12
Source File: encryptor.py    From pghoard with Apache License 2.0 6 votes vote down vote up
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 
Example #13
Source File: encryptor.py    From pghoard with Apache License 2.0 6 votes vote down vote up
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()) 
Example #14
Source File: test_auth.py    From mozilla-django-oidc with Mozilla Public License 2.0 6 votes vote down vote up
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) 
Example #15
Source File: test_auth.py    From mozilla-django-oidc with Mozilla Public License 2.0 6 votes vote down vote up
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.') 
Example #16
Source File: credstash.py    From credstash with Apache License 2.0 6 votes vote down vote up
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,
    } 
Example #17
Source File: test_auth.py    From mozilla-django-oidc with Mozilla Public License 2.0 6 votes vote down vote up
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.') 
Example #18
Source File: fernet.py    From quickstart-redhat-openshift with Apache License 2.0 6 votes vote down vote up
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) 
Example #19
Source File: uacrypto.py    From opcua-modeling-tool with MIT License 5 votes vote down vote up
def hmac_sha1(key, message):
    hasher = hmac.HMAC(key, hashes.SHA1(), backend=default_backend())
    hasher.update(message)
    return hasher.finalize() 
Example #20
Source File: hkdf.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _extract(self, key_material):
        h = hmac.HMAC(self._salt, self._algorithm, backend=self._backend)
        h.update(key_material)
        return h.finalize() 
Example #21
Source File: hkdf.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _expand(self, key_material):
        output = [b""]
        counter = 1

        while self._algorithm.digest_size * (len(output) - 1) < self._length:
            h = hmac.HMAC(key_material, self._algorithm, backend=self._backend)
            h.update(output[-1])
            h.update(self._info)
            h.update(six.int2byte(counter))
            output.append(h.finalize())
            counter += 1

        return b"".join(output)[:self._length] 
Example #22
Source File: hmac_generate.py    From vulpy with MIT License 5 votes vote down vote up
def hmac_generate(key, message):

    h = hmac.HMAC(key.encode(), hashes.SHA256(), backend=default_backend())
    h.update(message.encode())

    print(hexlify(h.finalize()).decode()) 
Example #23
Source File: ecies.py    From trinity with MIT License 5 votes vote down vote up
def hmac_sha256(key: bytes, msg: bytes) -> bytes:
    mac = hmac.HMAC(key, hashes.SHA256(), default_backend())
    mac.update(msg)
    return mac.finalize() 
Example #24
Source File: hmac.py    From jws with Apache License 2.0 5 votes vote down vote up
def __init__(self, hmac_key, algorithm):
    """Constructor for Hmac.

    Args:
      hmac_key: bytes, the symmetric hmac key.
      algorithm: string, HMAC algorithm as defined at
        https://tools.ietf.org/html/rfc7518#section-3.1.

    Raises:
      TypeError: if the hmac key is not bytes.
      UnsupportedAlgorithm: if the algorithm is not supported or key is too
      short.
    """
    if algorithm == "HS256":
      self._hash = hashes.SHA256()
    elif algorithm == "HS384":
      self._hash = hashes.SHA384()
    elif algorithm == "HS512":
      self._hash = hashes.SHA512()
    else:
      raise exceptions.UnsupportedAlgorithm(
          "Unknown algorithm: %s " % (algorithm))
    if not isinstance(hmac_key, six.binary_type):
      raise TypeError("hmac key must be bytes")
    if len(hmac_key) < 16:
      raise exceptions.UnsupportedAlgorithm("key too short")
    self._hmac_key = hmac_key
    self.algorithm = algorithm 
Example #25
Source File: fernet.py    From learn_python3_spider with MIT License 5 votes vote down vote up
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 
Example #26
Source File: hkdf.py    From scapy with GNU General Public License v2.0 5 votes vote down vote up
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() 
Example #27
Source File: authentication.py    From aws-dynamodb-encryption-python with Apache License 2.0 5 votes vote down vote up
def _build_hmac_signer(self, key):
        # type: (bytes) -> Any
        """Build HMAC signer using instance algorithm and hash type and ``key``.

        :param bytes key: Key to use in signer
        """
        return self.algorithm_type(key, self.hash_type(), backend=default_backend()) 
Example #28
Source File: crypto.py    From pycepa with GNU General Public License v3.0 5 votes vote down vote up
def hmac(key, msg):
    hmac = HMAC(key, algorithm=SHA256(), backend=bend)
    hmac.update(msg)
    return hmac.finalize() 
Example #29
Source File: test_auth.py    From mozilla-django-oidc with Mozilla Public License 2.0 5 votes vote down vote up
def test_retrieve_not_existing_jwk(self, mock_requests):
        """Test retrieving jwk that doesn't exist."""

        get_json_mock = Mock()
        get_json_mock.json.return_value = {
            "keys": [
                {
                    "alg": "RS256",
                    "kid": "kid"
                }
            ]
        }
        mock_requests.get.return_value = get_json_mock

        header = force_bytes(json.dumps({'alg': 'RS256', 'typ': 'JWT', 'kid': 'differentkid'}))
        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)
        )

        with self.assertRaises(SuspiciousOperation) as ctx:
            self.backend.retrieve_matching_jwk(force_bytes(token))

        self.assertEqual(ctx.exception.args[0], 'Could not find a valid JWKS.') 
Example #30
Source File: test_auth.py    From mozilla-django-oidc with Mozilla Public License 2.0 5 votes vote down vote up
def test_retrieve_jwk_optional_alg(self, mock_requests):
        """Test retrieving jwk with optional alg"""

        get_json_mock = Mock()
        get_json_mock.json.return_value = {
            "keys": [
                {
                    "kid": "kid",
                }
            ]
        }
        mock_requests.get.return_value = get_json_mock

        header = force_bytes(json.dumps({'alg': 'HS256', 'typ': 'JWT', 'kid': 'kid'}))
        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)
        )

        jwk_key = self.backend.retrieve_matching_jwk(force_bytes(token))
        self.assertEqual(jwk_key, get_json_mock.json.return_value['keys'][0])