Importing AES Key as an External Key Version (Script)

Automate the process to import AES key as an external key version.

Open a command prompt, and then run the following script, replacing example file names and values as appropriate:

#!/usr/bin/env bash

#
# This script is for demonstration purposes only. It provides
# a functioning set of calls to show how to import AES keys 
# into the Vault service.
#


set -x

OPENSSL="<path_to_OpenSSL>"
AES_KEY="<path_to_AES_key>"
WRAPPING_KEY="<path_to_RSA_wrapping_key>"
WRAPPED_KEY="<path_to_wrapped_AES_key>"

KEY_ID="<key_OCID>"
KEY_SIZE="<key_size_as_bytes>"

BASE64="base64"
if [[ $(uname -s) == "MINGW"* ]]
then
    BASE64="base64 -w0";
fi


#
# Generate an AES key.
#
# Use OpenSSL to generate an AES key of ${KEY_SIZE} bytes.
# You can use any source for your AES key.
#
${OPENSSL} rand ${KEY_SIZE} > ${AES_KEY}

#
# Ask the Vault service for the public wrapping key by using 
# the vault's key management endpoint.
# The public key is stored as ${WRAPPING_KEY}.
#
key_text=$(oci kms management wrapping-key get --endpoint $VAULT_KEYMANAGEMENT_ENDPOINT | grep public-key | cut -d: -f2  | sed 's# "\(.*\)",#\1#g')
echo -e $key_text > ${WRAPPING_KEY}

#
# Wrap the AES key by using RSA-OAEP with SHA-256.
#
${OPENSSL} pkeyutl -encrypt -in ${AES_KEY} -inkey ${WRAPPING_KEY} -pubin -out ${WRAPPED_KEY} -pkeyopt rsa_padding_mode:oaep -pkeyopt rsa_oaep_md:sha256


#
# Import the wrapped key to the Vault service after base64 encoding the payload.
#
# The service will provide a JSON document containing key details.
#
key_material=$(${BASE64} ${WRAPPED_KEY})
echo "{ \"wrappingAlgorithm\": \"RSA_OAEP_SHA256\", \"keyMaterial\": \"${key_material}\" }" > wrapped_import_key.json
echo "{ \"algorithm\": \"AES\", \"length\": ${KEY_SIZE} }" > key_shape.json

oci kms management key import --wrapped-import-key file://./wrapped_import_key.json --compartment-id ${COMPARTMENT_ID} --display-name ${DISPLAY_NAME} --endpoint ${VAULT_KEYMANAGEMENT_ENDPOINT} --key-shape file://./key_shape.json

##### IMPORT NEW KEY VERSION #####
# import the key version by using the CLI
oci kms management key-version import --key-id ${KEY_ID} --wrapped-import-key ${WRAPPED_KEY}