Fay*_*med 3 google-cloud-platform google-cloud-kms
我正在尝试解密kms加密文件并运行以下错误:
UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 3: invalid start byte
Run Code Online (Sandbox Code Playgroud)
我正在使用示例解密代码。
我可以使用命令行解密文件。
从这里抛出异常:
cipher_text.decode('utf-8')
Run Code Online (Sandbox Code Playgroud)
代码:https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/kms/api-client/snippets.py
如果我在这里缺少什么,请告诉我。
使用Python库时,所有输入都必须经过base64编码,输出也必须经过base64编码。在snippets.py中的加密函数中,您可以看到该代码在将明文传递给KMS加密API之前,已经对base64进行了编码。
encoded_text = base64.b64encode(plaintext)
Run Code Online (Sandbox Code Playgroud)
使用该gcloud kms encrypt命令时,您不必自己对明文进行base64编码,并且密文也不会进行base64编码。
因此,将密文从传递gcloud kms encrypt到Python库进行解密时,必须先对其进行base64编码。在发送之前,将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()
Run Code Online (Sandbox Code Playgroud)
您可以将base64编码视为传输层实现的详细信息:这样做仅是必要的,以便可以使用JSON发送任意二进制数据,该JSON仅接受Unicode字符串。因此,Cloud KMS API要求此数据经过base64编码,并且还必须对输出进行base64编码。但是gcloud命令可以为您完成这项工作,因此您不必这样做。
我认为Python示例代码具有误导性。它应该始终对API进行base64编码输入,并始终对base64解码输出进行输出,而不是仅在某些时候这样做。我将很快查看更新Python示例代码,并仔细检查其他语言的示例代码。
| 归档时间: |
|
| 查看次数: |
1075 次 |
| 最近记录: |