1

我已经使用 Python 客户端库加密了密码字符串,将内容写入文件,将其上传到 GCS。接下来,当我下载文件、读取内容并使用相同的客户端库解密时,它给了我这个错误。

google.api_core.exceptions.InvalidArgument: 400 Decryption failed: the ciphertext is invalid.

我正在使用此代码来加密和解密

4

1 回答 1

2

没有代码很难弄清楚。但是,以下是使用 Google Cloud KMS 服务的基本步骤。

加密步骤:

  1. 以base64编码明文。
  2. 加密数据。
  3. 在 base64 中编码二进制密文。

解密步骤:

  1. 解码 base64 密文。
  2. 解密数据。
  3. 将 base64 解密文本解码为纯文本。

示例 Python 代码:

from google.cloud import kms_v1
from google.cloud.kms_v1 import enums
import base64

def encrypt_symmetric(project_id, location_id, key_ring_id, crypto_key_id, plaintext):
    # 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)

    # Base64 Encoding of plaintext
    plaintext = base64.b64encode(plaintext)
    # Encrypt the data
    response = client.encrypt(name, plaintext)
    # Base64 Encoding of ciphertext
    ciphertext = base64.b64encode(response.ciphertext)
    return ciphertext

def decrypt_symmetric(project_id, location_id, key_ring_id, crypto_key_id, ciphertext):
    # 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)

    # Decode Base64 ciphertext
    ciphertext = base64.b64decode(ciphertext)
    # Decrypt the data
    response = client.decrypt(name, ciphertext)
    # Decode Base64 plaintext
    plaintext = base64.b64decode(response.plaintext)
    return plaintext


if __name__=='__main__':
    project_id = 'Your-project-id'
    location_id = 'your-location'
    key_ring_id = 'Key-ring-id'
    crypto_key_id = 'crypto-key-id'
    plaintext = 'Vikas Saini'
    ciphertext = encrypt_symmetric(project_id, location_id, key_ring_id, crypto_key_id, plaintext)
    print ciphertext
    plaintext = decrypt_symmetric(project_id, location_id, key_ring_id, crypto_key_id, ciphertext)
    print plaintext

希望这可以帮助。

于 2020-01-01T07:57:11.850 回答