Skip to content

CREATE KEY

Create a new encryption key in a database.

CREATE KEY [ IF NOT EXISTS ] key [ WITH ] SECRET 'hex_string';
IF NOT EXISTS
Create the key if it does not already exist. If it does exist, do not create it and do not return an error.
key
A key name with a maximum length of 128 bytes. Names longer than 128 bytes are automatically truncated. See SQL Identifiers. Encryption keys are referenced in ENCRYPT_KS and DECRYPT_KS functions and in ENCRYPTED WITH column constraints in CREATE TABLE. See also Encrypting Sensitive Data.
hex_string
A valid hexadecimal string with a minimum of 1 character and maximum of 32768 characters. Hexadecimal strings can only contain the following characters: [0-9] and [a-f]. The 0x prefix is not supported.

A newly created key is only accessible by the user creating the key. To grant other users permission to use a key, see GRANT.

The CREATE KEY operation is non-transactional and will error out when run inside a transaction block.

Note that keys are not backed up during backup operations because they are not actually stored in the database. The remote keystore administrator must make sure keys are backed up and stored safely.

You cannot create keys in one database and reference them in a table that you create in another database.

Examples

For example, create a key named yb100key with secret a1b2c3d4:

premdb=# create key yb100key secret 'a1b2c3d4';
CREATE KEY

Create the key playerkey if it does not already exist:

premdb=# create key if not exists playerkey secret 'a1b2c3d4e5';
CREATE KEY

Using an invalid hexadecimal string as a secret will result in the following error:

premdb=# create key yb100key secret 'g1h2i3j4';
ERROR:  invalid secret. HINT: secret must be a valid hexadecimal string (i.e. non-empty and without a '0x' prefix) smaller than 32768 characters

Parent topic:SQL Commands