7

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).

Pascal Delange
  • 417
  • 5
  • 17
  • Looks like you're trying to decrypt plain text? – Mat Jan 09 '18 at 15:40
  • Oh my bad, I was kind of assuming that it would still decrypt something, but obviously that need not be the case. Trying again. – Pascal Delange Jan 09 '18 at 15:52
  • 4
    Do you think it's worth us changing the error message here? What should we change it to? Thanks for using Google Cloud KMS! – Tim Dierks Jan 10 '18 at 04:14
  • Well, I suppose there is no obvious way to determine if one is using the wrong key or if the ciphertext is wrong. In hindsight I was doing a trivially wrong manipulation, so I'm not sure if there is a better error message to give. Maybe something more like "The ciphertext is not compatible with the chose CryptoKey ? – Pascal Delange Jan 10 '18 at 16:12
  • Just ran into the same... IMHO it's SUPER confusing to give this error when actually the key was found but the input is invalid. Just wasted 1.5h to figure this out. A better error message shouid be used @TimDierks – soupdiver May 24 '19 at 09:48
  • 2
    I've filed an internal issue [b/134206804] to improve the error messages if possible and we'll see if we can find the time to work on it as a "product excellence" improvement. Thanks for your report and engagement in helping us to make the product better, and thanks for using GCP and Cloud KMS! – Tim Dierks Jun 01 '19 at 17:52
  • Thanks ! I'm sure it will be useful for new users – Pascal Delange Jun 03 '19 at 17:04

1 Answers1

16

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.

soupdiver
  • 3,504
  • 9
  • 40
  • 68