Search code examples
google-cloud-kms

Google cloud KMS: encryption works but decryption fails


I am trying to decrypt a token using the google KMS tool. Running it locally, for some reason, encryption seems to work but not decryption.

I am running the following code:

import base64
import googleapiclient.discovery
kms_client = googleapiclient.discovery.build('cloudkms', 'v1')
crypto_keys = kms_client.projects().locations().keyRings().cryptoKeys()
name = "projects/my-project/locations/my-loc/keyRings/my-kr/cryptoKeys/my-key"
request = crypto_keys.decrypt(name=name, body={'ciphertext': base64.b64encode("my text").decode('ascii')})
response = request.execute()

The last line returns a 400 error:

HttpError: <HttpError 400 when requesting https://cloudkms.g[...]ion:decrypt?alt=json 
returned "Decryption failed: verify that 'name' refers to the correct CryptoKey.">

The name, however, actually seems to be correct. Surprisingly enough, replacing the call to decrypt by encrypt, I obtain a valid output.

Am I missing an obvious mistake, or should I just open a issue on the project's github ?

EDIT: I was trying to decrypt plain text, which of course does not make much sense (but the error message misled me somewhat).


Solution

  • Make sure that the ciphertext you're trying to decrypt was encrypted using the same key. In case you used another key to encrypt, KMS tells you that it could not find the key while actually the key was found but couldn't be used to decrypt the cipher.

    I think the error message is "a bit" misleading.