Google Cloud KMS: Unable to decrypt

Viewed 2776
2 Answers

Given the date of the question, the accepted answer should be @Russ (also, thank you for updating the git). Since the documentation changed a little, here is a function that deals with an already encrypted json file.

Encrypted using the GCloud Command Line:

gcloud kms encrypt \
  --plaintext-file=[SECRETS.json] \
  --ciphertext-file=[ENCRYPTED-SECRETS.json.enc] \
  --location=[REGION] \
  --keyring=[KEYRING-NAME] \
  --key=[KEY-NAME]

Here is the function for decrypting said file (cipher_file being the path to [ENCRYPTED-SECRETS.json.enc]):

def decrypt(cipher_file):
    project_id = "project"
    location_id = "region"
    key_ring_id = "key-ring"
    crypto_key_id = "key"

    # 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.
    with io.open(cipher_file, "rb") as file:
        c_text = file.read()

    response = client.decrypt(name, c_text)

    secret_dict = json.loads(response.plaintext.decode("utf-8"))

    return secret_dict
Related