2017-08-15 54 views
0

我试图解密公里加密的文件,并在下面的错误运行:谷歌云KMS:无法解密

UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 3: invalid start byte 

我使用的示例代码解密。

我可以使用命令行解密文件。

异常正从这里抛出:

cipher_text.decode('utf-8') 

代码:https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/kms/api-client/snippets.py

请让我知道如果我失去了一些东西。

+0

找出使用命令行实用程序加密的文件无法使用Python解密API解密(不知道它是否与其他语言API一样)。 因此,要通过Python API解密加密文件,还必须通过加密Python API来完成加密。 不知道我的理解是否正确,但是使用上述方法得到了解。 –

回答

3

当您使用Python库时,所有输入必须以base64编码,输出也将以base64编码。在snippets.py中的加密函数中,您可以在将代码传递给KMS加密API之前,看到该代码是base64编码的明文。

encoded_text = base64.b64encode(plaintext) 

当您使用gcloud kms encrypt命令,你不必为base64编码自己的明文和密文是不是base64编码。

因此,当您将密文从gcloud kms encrypt传递到Python库进行解密时,您必须先对其进行64位编码。在发送之前,将snippets.py中的解密函数更改为base64编码文件数据。

# Read cipher text from the input file. 
with io.open(encrypted_file_name, 'rb') as encrypted_file: 
    ciphertext = encrypted_file.read() 
encoded_text = base64.b64encode(ciphertext) 

# Use the KMS API to decrypt the text. 
cryptokeys = kms_client.projects().locations().keyRings().cryptoKeys() 
request = cryptokeys.decrypt(
    name=name, body={'ciphertext': encoded_text.decode('utf-8')}) 
response = request.execute() 

你能想到的基于64位编码的作为是一个传输层实现细节:这只是必要的,这样任意的二进制数据可以JSON,只接受Unicode字符串发送。因此,云端KMS API要求此数据以base64编码,并且还必须对输出进行64位编码。但是gcloud命令为你做这个工作,所以你不必这样做。

我认为Python示例代码具有误导性。它应该总是将64位输入编码为API和base64解码输出,而不仅仅是有时候这样做。我会尽快更新Python示例代码,并仔细检查其他语言的示例代码。

+0

感谢您的澄清。说得通。 –

+0

Python示例代码已修复,请参阅https://github.com/GoogleCloudPlatform/python-docs-samples/commit/e0f957c816a42117a02c3d6db09e0611c15d4c70。 –