How to use KEYS.KEYSET_CHAIN in BigQuery

Viewed 412

I'm trying to use KEYS.KEYSET_CHAIN to obtain the a key from the KMS but I haven't figured out how to generate the first_level_keyset correctly. I'm getting the following message:

AEAD.ENCRYPT failed: Keyset deserialization failed: Error reading keyset data: Could not parse the input stream as a Keyset-proto.

I'm following the doc:

My code:

DECLARE KMS_RESOURCE_NAME STRING;
DECLARE FIRST_LEVEL_KEYSET BYTES;

SET KMS_RESOURCE_NAME = 'gcp-kms://projects/XXX/locations/XXX/keyRings/XXX-key-ring/cryptoKeys/XXX-key';
SET FIRST_LEVEL_KEYSET = FROM_HEX("0a240... <suppressed>");

select AEAD.ENCRYPT(KEYS.KEYSET_CHAIN(KMS_RESOURCE_NAME, FIRST_LEVEL_KEYSET), b'string to encrypt', b'customer_id');
1 Answers

To generate the first_level_keyset, you will need to:

1.-Create a Key Management Service. Users need to have the cloudkms.cryptoKeyDecrypterViaDelegation role.

2.-Create a raw keyset.You need to execute the next command at cloud shell:

bq --project_id=my_project query --use_legacy_sql=false "SELECT KEYS.NEW_KEYSET('AEAD_AES_GCM_256') AS raw_keyset"

This command is going to return the raw keyset.

3.-Create and format a wrapped keyset.

echo "CK3245gBE...    <suppressed>..." |base64 --decode > /tmp/decoded_key

gcloud kms encrypt --plaintext-file=/tmp/decoded_key --key=projects/my_project/locations/my_location/keyRings/my_keyring/cryptoKeys/my_key --ciphertext-file=/tmp/bankaccounts_wrapped

od -An --format=o1 /tmp/bankaccounts_wrapped |tr -d '\n'|tr ' ' '\'

This is going to return the array of bytes that you need to set at the first_level_keyset, such as:

DECLARE KMS_RESOURCE_NAME STRING;
DECLARE FIRST_LEVEL_KEYSET BYTES;
 
SET KMS_RESOURCE_NAME = 'gcp-kms://projects/my_project/locations/my_location/keyRings/my_keyring/cryptoKeys/my_key';
SET FIRST_LEVEL_KEYSET = b'\012\044\000\150\267\053\201 <suppressed>';
 
select AEAD.ENCRYPT(KEYS.KEYSET_CHAIN(KMS_RESOURCE_NAME, FIRST_LEVEL_KEYSET), b'string to encrypt', b'customer_id');

The result of this:

enter image description here

Related