in envelope-encryption-sample/python-cli/cli.py [0:0]
def main(argv):
mode = FLAGS.mode
project_id = FLAGS.project_id
kek_name = FLAGS.kek_name
keyring_name = FLAGS.keyring_name
location = FLAGS.location
num_bytes = FLAGS.num_bytes
wrapped_key_path = FLAGS.wrapped_key_path
input = FLAGS.input
output = FLAGS.output
if mode == "generate":
random_bytes_response = generate_random_bytes(
project_id=project_id, location=location, num_bytes=num_bytes
)
decoded_dek = b64encode(random_bytes_response["data"]).decode("utf-8")
wrapped_key = gcp_encrypt_symmetric(
project_id=project_id,
location=location,
keyring_name=keyring_name,
kek_name=kek_name,
plaintext=decoded_dek,
)
save_json_to_file(
json_data=b64encode(wrapped_key.ciphertext).decode("utf-8"),
file_path=wrapped_key_path,
)
elif mode == "encrypt":
wrapped_key = load_json_from_file(wrapped_key_path)
key = gcp_decrypt_symmetric(
project_id=project_id,
location=location,
keyring_name=keyring_name,
kek_name=kek_name,
ciphertext=b64decode(wrapped_key),
)
content = read_text_file(input)
ciphertext = local_encrypt_symmetric(
data_encryption_key=key.plaintext, plaintext=content
)
save_json_to_file(
json_data=b64encode(ciphertext).decode("utf-8"), file_path=output
)
elif mode == "decrypt":
wrapped_key = load_json_from_file(wrapped_key_path)
key = gcp_decrypt_symmetric(
project_id=project_id,
location=location,
keyring_name=keyring_name,
kek_name=kek_name,
ciphertext=b64decode(wrapped_key),
)
content = read_text_file(input)
plaintext = local_decrypt_symmetric(
data_encryption_key=key.plaintext, ciphertext=b64decode(content)
)
save_json_to_file(
json_data=plaintext.decode("utf-8"), file_path=output
)
else:
print("Unsupported mode. Please choose generate, encrypt, or decrypt")