Ejemplo n.º 1
0
 def test_wrap_additional_vectors(self, backend, params):
     wrapping_key = binascii.unhexlify(params["key"])
     key_to_wrap = binascii.unhexlify(params["input"])
     wrapped_key = keywrap.aes_key_wrap_with_padding(
         wrapping_key, key_to_wrap, backend
     )
     assert wrapped_key == binascii.unhexlify(params["output"])
Ejemplo n.º 2
0
 def wrap(self, secret):
     '''Wrap the key and save the further parameters'''
     # _wrapkey = os.urandom(16)
     _wrapkey = os.urandom(RANDOM_BYTES)
     self._wrappedkey = keywrap.aes_key_wrap_with_padding(
         _wrapkey, secret, default_backend())
     return _wrapkey
Ejemplo n.º 3
0
 def test_wrap(self, backend, params):
     wrapping_key = binascii.unhexlify(params["k"])
     key_to_wrap = binascii.unhexlify(params["p"])
     wrapped_key = keywrap.aes_key_wrap_with_padding(
         wrapping_key, key_to_wrap, backend
     )
     assert params["c"] == binascii.hexlify(wrapped_key)
Ejemplo n.º 4
0
    def _CkmRsaAesKeyWrap(self, public_key_bytes, target_key_bytes):
        try:
            from cryptography.hazmat.primitives import serialization
            from cryptography.hazmat.backends import default_backend
            from cryptography.hazmat.primitives import keywrap
            from cryptography.hazmat.primitives.asymmetric import padding
            from cryptography.hazmat.primitives import hashes
        except ImportError:
            log.err.Print(
                'Cannot load the Pyca cryptography library. Either the '
                'library is not installed, or site packages are not '
                'enabled for the Google Cloud SDK. Please consult '
                'https://cloud.google.com/kms/docs/crypto for further '
                'instructions.')
            sys.exit(1)

        public_key = serialization.load_pem_public_key(
            public_key_bytes, backend=default_backend())
        ephem_key = os.urandom(32)
        wrapped_ephem_key = public_key.encrypt(
            ephem_key,
            padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()),
                         algorithm=hashes.SHA1(),
                         label=None))
        wrapped_target_key = keywrap.aes_key_wrap_with_padding(
            ephem_key, target_key_bytes, default_backend())
        return wrapped_ephem_key + wrapped_target_key
Ejemplo n.º 5
0
    def _CkmRsaAesKeyWrap(self, public_key_bytes, target_key_bytes):
        try:
            # TODO(b/141249289): Move imports to the top of the file. In the
            # meantime, until we're sure that all Cloud SDK users have the
            # cryptography module available, let's not error out if we can't load the
            # module unless we're actually going down this code path.
            # pylint: disable=g-import-not-at-top
            from cryptography.hazmat.primitives import serialization
            from cryptography.hazmat.backends import default_backend
            from cryptography.hazmat.primitives import keywrap
            from cryptography.hazmat.primitives.asymmetric import padding
            from cryptography.hazmat.primitives import hashes
        except ImportError:
            log.err.Print(
                'Cannot load the Pyca cryptography library. Either the '
                'library is not installed, or site packages are not '
                'enabled for the Google Cloud SDK. Please consult '
                'https://cloud.google.com/kms/docs/crypto for further '
                'instructions.')
            sys.exit(1)

        public_key = serialization.load_pem_public_key(
            public_key_bytes, backend=default_backend())
        ephem_key = os.urandom(32)
        wrapped_ephem_key = public_key.encrypt(
            ephem_key,
            padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()),
                         algorithm=hashes.SHA1(),
                         label=None))
        wrapped_target_key = keywrap.aes_key_wrap_with_padding(
            ephem_key, target_key_bytes, default_backend())
        return wrapped_ephem_key + wrapped_target_key
Ejemplo n.º 6
0
 def test_wrap_additional_vectors(self, backend, subtests):
     params = _load_all_params("keywrap", ["kwp_botan.txt"],
                               load_nist_vectors)
     for param in params:
         with subtests.test():
             wrapping_key = binascii.unhexlify(param["key"])
             key_to_wrap = binascii.unhexlify(param["input"])
             wrapped_key = keywrap.aes_key_wrap_with_padding(
                 wrapping_key, key_to_wrap, backend)
             assert wrapped_key == binascii.unhexlify(param["output"])
Ejemplo n.º 7
0
 def test_wrap(self, backend, subtests):
     params = _load_all_params(
         os.path.join("keywrap", "kwtestvectors"),
         ["KWP_AE_128.txt", "KWP_AE_192.txt", "KWP_AE_256.txt"],
         load_nist_vectors,
     )
     for param in params:
         with subtests.test():
             wrapping_key = binascii.unhexlify(param["k"])
             key_to_wrap = binascii.unhexlify(param["p"])
             wrapped_key = keywrap.aes_key_wrap_with_padding(
                 wrapping_key, key_to_wrap, backend)
             assert param["c"] == binascii.hexlify(wrapped_key)
Ejemplo n.º 8
0
def test_keywrap_with_padding(backend, wycheproof):
    wrapping_key = binascii.unhexlify(wycheproof.testcase["key"])
    key_to_wrap = binascii.unhexlify(wycheproof.testcase["msg"])
    expected = binascii.unhexlify(wycheproof.testcase["ct"])

    result = keywrap.aes_key_wrap_with_padding(wrapping_key, key_to_wrap,
                                               backend)
    if wycheproof.valid or wycheproof.acceptable:
        assert result == expected

    if wycheproof.valid or (wycheproof.acceptable and not len(expected) < 16):
        result = keywrap.aes_key_unwrap_with_padding(wrapping_key, expected,
                                                     backend)
        assert result == key_to_wrap
    else:
        with pytest.raises(keywrap.InvalidUnwrap):
            keywrap.aes_key_unwrap_with_padding(wrapping_key, expected,
                                                backend)
Ejemplo n.º 9
0
def test_keywrap_with_padding(backend, wycheproof):
    wrapping_key = binascii.unhexlify(wycheproof.testcase["key"])
    key_to_wrap = binascii.unhexlify(wycheproof.testcase["msg"])
    expected = binascii.unhexlify(wycheproof.testcase["ct"])

    result = keywrap.aes_key_wrap_with_padding(
        wrapping_key, key_to_wrap, backend
    )
    if wycheproof.valid or wycheproof.acceptable:
        assert result == expected

    if wycheproof.valid or (wycheproof.acceptable and not len(expected) < 16):
        result = keywrap.aes_key_unwrap_with_padding(
            wrapping_key, expected, backend
        )
        assert result == key_to_wrap
    else:
        with pytest.raises(keywrap.InvalidUnwrap):
            keywrap.aes_key_unwrap_with_padding(
                wrapping_key, expected, backend
            )
Ejemplo n.º 10
0
 def test_wrap_invalid_key_length(self, backend):
     with pytest.raises(ValueError, match='must be a valid AES key length'):
         keywrap.aes_key_wrap_with_padding(b"badkey", b"\x00", backend)
Ejemplo n.º 11
0
 def test_wrap_invalid_key_length(self, backend):
     with pytest.raises(ValueError, match='must be a valid AES key length'):
         keywrap.aes_key_wrap_with_padding(b"badkey", b"\x00", backend)
def import_manually_wrapped_key(project_id, location_id, key_ring_id,
                                crypto_key_id, import_job_id):
    """
    Generates and imports local key material to Cloud KMS.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        crypto_key_id (string): ID of the key to import (e.g. 'my-asymmetric-signing-key').
        import_job_id (string): ID of the import job (e.g. 'my-import-job').
    """

    # Import the client library and Python standard cryptographic libraries.
    import os
    from cryptography.hazmat import backends
    from cryptography.hazmat.primitives import hashes, keywrap, serialization
    from cryptography.hazmat.primitives.asymmetric import ec, padding
    from google.cloud import kms

    # Generate some key material in Python and format it in PKCS #8 DER as
    # required by Google Cloud KMS.
    key = ec.generate_private_key(ec.SECP256R1, backends.default_backend())
    formatted_key = key.private_bytes(serialization.Encoding.DER,
                                      serialization.PrivateFormat.PKCS8,
                                      serialization.NoEncryption())

    print('Generated key bytes: {}'.format(formatted_key))

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Retrieve the fully-qualified crypto_key and import_job string.
    crypto_key_name = client.crypto_key_path(project_id, location_id,
                                             key_ring_id, crypto_key_id)
    import_job_name = client.import_job_path(project_id, location_id,
                                             key_ring_id, import_job_id)

    # Generate a temporary 32-byte key for AES-KWP and wrap the key material.
    kwp_key = os.urandom(32)
    wrapped_target_key = keywrap.aes_key_wrap_with_padding(
        kwp_key, formatted_key, backends.default_backend())

    # Retrieve the public key from the import job.
    import_job = client.get_import_job(name=import_job_name)
    import_job_pub = serialization.load_pem_public_key(
        bytes(import_job.public_key.pem, 'UTF-8'), backends.default_backend())

    # Wrap the KWP key using the import job key.
    wrapped_kwp_key = import_job_pub.encrypt(
        kwp_key,
        padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()),
                     algorithm=hashes.SHA1(),
                     label=None))

    # Import the wrapped key material.
    client.import_crypto_key_version({
        "parent":
        crypto_key_name,
        "import_job":
        import_job_name,
        "algorithm":
        kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.EC_SIGN_P256_SHA256,
        "rsa_aes_wrapped_key":
        wrapped_kwp_key + wrapped_target_key,
    })

    print('Imported: {}'.format(import_job.name))