1

我正在尝试使用 AES GCM 将加密数据存储在 BigQuery 中。

数据使用 Python 的 Cryptodome 库进行加密。

这是代码

from Cryptodome.Cipher import AES
from Cryptodome.Random import get_random_bytes

key = get_random_bytes(32)


def encrypt(txt):
   nonce = get_random_bytes(16)
   cipher = AES.new(key, AES.MODE_GCM, nonce)
   cipher, tag = cipher.encrypt_and_digest(txt)
   return nonce, cipher, tag


def decrypt(nonce, ciphertext, tag):
   cipher = AES.new(key, AES.MODE_GCM, nonce)
   return cipher.decrypt_and_verify(ciphertext, tag)


if __name__ == '__main__':
   # Bigquery insert key
   # row_to_insert = [[email, key]]
   # errors = client.insert_rows(table_keys, row_to_insert)

   e = encrypt('that is a message'.encode('utf-8'))

   # BigQuery insert encrypt message
   # row_to_insert = [[email, b''.join(e)]]
   # errors = client.insert_rows(table_data, row_to_insert)
   print(decrypt(e[0], e[1], e[2]))

密钥和密文的输出示例将是:

key --> b'\x91\xfa\x02\xa9+\x1d\xcf_\xcd\n\xe3ci\x9dCq\x8dw\x94\xbb\xfd\x040\xad\xaer!8_\xb0\xe4\xb3'
ciphertext -> b'\x1a\xa8F\x17 \xfa\xfbf\x19*A\xc80\xd96e\xcf'
Nonce -> b'\xe1s\x9er\xb4{\xe6\xfd[\xcdw(\xd4\x00\xf3\x1b'
tag -> b'f\t\x1b\xcd\x8b\x1au\xfc\xba\x87\xa2\x85\xca\xa7\n\xe8'

在 python 中,数据被很好地解密,但在返回的 bigquery 中没有:

Failed to decrypt ciphertext using key of length 32. IV and ciphertext (in hexadecimal) are 'c103fcf32913be2de8883dfe' and '771b52e409157a5cb148769dfb789c33bbbada74424f0aa657c216e2748dda40f22fbb45eccbef1f776b11fd22dbd4c28d86...'. OpenSSL error is: BAD_DECRYPT

这是查询:

SELECT BQ.AES_DECRYPT('GCM',message, key) FROM `origen.data` join `origen.keys` on `origen.data`.email  = 'email@gmail.com'

知道我做错了什么吗?

4

0 回答 0