13
13
14
14
15
15
# [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 ):
17
17
"""
18
- Imports local key material to Cloud KMS.
18
+ Generates and imports local key material to Cloud KMS.
19
19
20
20
Args:
21
21
project_id (string): Google Cloud project ID (e.g. 'my-project').
22
22
location_id (string): Cloud KMS location (e.g. 'us-east1').
23
23
key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
24
24
crypto_key_id (string): ID of the key to import (e.g. 'my-asymmetric-signing-key').
25
25
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.
29
26
"""
30
27
31
28
# Import the client library and Python standard cryptographic libraries.
32
29
import os
33
- from cryptography .hazmat . backends import default_backend
30
+ from cryptography .hazmat import backends
34
31
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
36
33
from google .cloud import kms
37
34
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
+
38
45
# Create the client.
39
46
client = kms .KeyManagementServiceClient ()
40
47
@@ -47,12 +54,12 @@ def import_manually_wrapped_key(project_id, location_id, key_ring_id, crypto_key
47
54
# Generate a temporary 32-byte key for AES-KWP and wrap the key material.
48
55
kwp_key = os .urandom (32 )
49
56
wrapped_target_key = keywrap .aes_key_wrap_with_padding (
50
- kwp_key , key_material , default_backend ())
57
+ kwp_key , formatted_key , backends . default_backend ())
51
58
52
59
# Retrieve the public key from the import job.
53
60
import_job = client .get_import_job (name = import_job_name )
54
61
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 ())
56
63
57
64
# Wrap the KWP key using the import job key.
58
65
wrapped_kwp_key = import_job_pub .encrypt (
0 commit comments