Skip to content

Instantly share code, notes, and snippets.

@justinnaldzin
Created February 15, 2019 21:05
Show Gist options
  • Save justinnaldzin/7dd93ebc696b70761a5a2e0f6c00d5c5 to your computer and use it in GitHub Desktop.
Save justinnaldzin/7dd93ebc696b70761a5a2e0f6c00d5c5 to your computer and use it in GitHub Desktop.
GCP Cloud KMS encrypting and decrypting data
from google.cloud import kms_v1
def encrypt(project_id, location_id, key_ring_id, crypto_key_id, plaintext):
"""Encrypts input plaintext data using the provided symmetric CryptoKey."""
# Creates an API client for the KMS API.
client = kms_v1.KeyManagementServiceClient()
# The resource name of the CryptoKey.
name = client.crypto_key_path_path(project_id, location_id, key_ring_id,
crypto_key_id)
# Use the KMS API to encrypt the data.
response = client.encrypt(name, plaintext)
return response.ciphertext
def decrypt(project_id, location_id, key_ring_id, crypto_key_id, ciphertext):
"""Decrypts input ciphertext using the provided symmetric CryptoKey."""
# Creates an API client for the KMS API.
client = kms_v1.KeyManagementServiceClient()
# The resource name of the CryptoKey.
name = client.crypto_key_path_path(project_id, location_id, key_ring_id,
crypto_key_id)
# Use the KMS API to decrypt the data.
response = client.decrypt(name, ciphertext)
return response.plaintext
project_id = 'gcp-project-id'
location_id = 'us'
key_ring_id = 'my-keyring'
crypto_key_id = 'my_key_id'
plaintext = b'my-secret-value'
ciphertext = encrypt(project_id, location_id, key_ring_id, crypto_key_id, plaintext)
ciphertext_encoded = base64.b64encode(ciphertext).decode('utf-8')
print(ciphertext_encoded)
ciphertext_decoded = base64.b64decode(ciphertext_encoded)
plaintext = decrypt(project_id, location_id, key_ring_id, crypto_key_id, ciphertext_decoded)
print(plaintext.decode('utf-8'))
#For more information: https://cloud.google.com/kms/docs/encrypt-decrypt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment