Importing AES Key as a External Key (Script)

Automate the import of AES key material as a new key with an example script.

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>"
​
VAULT_KEYMANAGEMENT_ENDPOINT="<target_vault_keymanagement_endpoint>"
COMPARTMENT_ID="<target_compartment_ID>"
DISPLAY_NAME="<key_display_name>"
KEY_SIZE="<key_size_as_bytes>" # Specify 16 (for 128 bits), 24 (for 192 bits), or 32 (for 256 bits).
​
# PROTECTION_MODE either SOFTWARE or HSM
PROTECTION_MODE="SOFTWARE"
​
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 --protection-mode ${PROTECTION_MODE}