1313
1414
1515# [START kms_import_manually_wrapped_key]
16- def import_manually_wrapped_key (project_id , location_id , key_ring_id , crypto_key_id , import_job_id , key_material ):
16+ def import_manually_wrapped_key (project_id , location_id , key_ring_id , crypto_key_id , import_job_id ):
1717 """
18- Imports local key material to Cloud KMS.
18+ Generates and imports local key material to Cloud KMS.
1919
2020 Args:
2121 project_id (string): Google Cloud project ID (e.g. 'my-project').
2222 location_id (string): Cloud KMS location (e.g. 'us-east1').
2323 key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
2424 crypto_key_id (string): ID of the key to import (e.g. 'my-asymmetric-signing-key').
2525 import_job_id (string): ID of the import job (e.g. 'my-import-job').
26- key_material (bytes): Locally generated key material in PKCS #8 DER format.
27- Returns:
28- CryptoKeyVersion: An instance of the imported key in Cloud KMS.
2926 """
3027
3128 # Import the client library and Python standard cryptographic libraries.
3229 import os
33- from cryptography .hazmat . backends import default_backend
30+ from cryptography .hazmat import backends
3431 from cryptography .hazmat .primitives import hashes , keywrap , serialization
35- from cryptography .hazmat .primitives .asymmetric import padding
32+ from cryptography .hazmat .primitives .asymmetric import ec , padding
3633 from google .cloud import kms
3734
35+ # Generate some key material in Python and format it in PKCS #8 DER as
36+ # required by Google Cloud KMS.
37+ key = ec .generate_private_key (ec .SECP256R1 , backends .default_backend ())
38+ formatted_key = key .private_bytes (
39+ serialization .Encoding .DER ,
40+ serialization .PrivateFormat .PKCS8 ,
41+ serialization .NoEncryption ())
42+
43+ print ('Generated key bytes: {}' .format (formatted_key ))
44+
3845 # Create the client.
3946 client = kms .KeyManagementServiceClient ()
4047
@@ -47,12 +54,12 @@ def import_manually_wrapped_key(project_id, location_id, key_ring_id, crypto_key
4754 # Generate a temporary 32-byte key for AES-KWP and wrap the key material.
4855 kwp_key = os .urandom (32 )
4956 wrapped_target_key = keywrap .aes_key_wrap_with_padding (
50- kwp_key , key_material , default_backend ())
57+ kwp_key , formatted_key , backends . default_backend ())
5158
5259 # Retrieve the public key from the import job.
5360 import_job = client .get_import_job (name = import_job_name )
5461 import_job_pub = serialization .load_pem_public_key (
55- bytes (import_job .public_key .pem , 'UTF-8' ), default_backend ())
62+ bytes (import_job .public_key .pem , 'UTF-8' ), backends . default_backend ())
5663
5764 # Wrap the KWP key using the import job key.
5865 wrapped_kwp_key = import_job_pub .encrypt (
0 commit comments