Skip to content

Commit

Permalink
samples: add request/response integrity verification to encrypt_symme…
Browse files Browse the repository at this point in the history
…tric.py (#70)
  • Loading branch information
iamtamjam authored and rsamborski committed Nov 14, 2022
1 parent 3dd5d05 commit abe0570
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
33 changes: 32 additions & 1 deletion kms/snippets/encrypt_symmetric.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,45 @@ def encrypt_symmetric(project_id, location_id, key_ring_id, key_id, plaintext):
# Convert the plaintext to bytes.
plaintext_bytes = plaintext.encode('utf-8')

# Optional, but recommended: compute plaintext's CRC32C.
# See crc32c() function defined below.
plaintext_crc32c = crc32c(plaintext_bytes)

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

# Build the key name.
key_name = client.crypto_key_path(project_id, location_id, key_ring_id, key_id)

# Call the API.
encrypt_response = client.encrypt(request={'name': key_name, 'plaintext': plaintext_bytes})
encrypt_response = client.encrypt(
request={'name': key_name, 'plaintext': plaintext_bytes, 'plaintext_crc32c': plaintext_crc32c})

# Optional, but recommended: perform integrity verification on encrypt_response.
# For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
# https://cloud.google.com/kms/docs/data-integrity-guidelines
if not encrypt_response.verified_plaintext_crc32c:
raise Exception('The request sent to the server was corrupted in-transit.')
if not encrypt_response.ciphertext_crc32c == crc32c(encrypt_response.ciphertext):
raise Exception('The response received from the server was corrupted in-transit.')
# End integrity verification

print('Ciphertext: {}'.format(base64.b64encode(encrypt_response.ciphertext)))
return encrypt_response


def crc32c(data):
"""
Calculates the CRC32C checksum of the provided data.
Args:
data: the bytes over which the checksum should be calculated.
Returns:
An int representing the CRC32C checksum of the provided bytes.
"""
import crcmod
import six
crc32c_fun = crcmod.predefined.mkPredefinedCrcFun('crc-32c')
return crc32c_fun(six.ensure_binary(data))
# [END kms_encrypt_symmetric]
3 changes: 2 additions & 1 deletion kms/snippets/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
google-cloud-kms==2.2.0
cryptography==3.2.1
cryptography==3.2.1
crcmod==1.7

0 comments on commit abe0570

Please sign in to comment.