Importing RSA Key as an External Key Version (Script)

You can automate the import of AES key material as a new key version for an existing key.

Open a command prompt, and then run the following script, replacing example file names and values as appropriate:
#!/bin/bash

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

set -e;
#set -x;

OPENSSL_PATH="<path to patched openssl.sh>"
PRIVATE_KEY="<path to target private key which needs to be imported>"
WRAPPING_KEY="<path to vault public wrapping key>"
KEY_OCID="<Key OCID of OCI Vault in which the key version will be created>"
WORK_DIR=$(mktemp -d -t kms_XXXX)
BASE64="base64"

echo "Openssl Path: ${OPENSSL_PATH}"
echo "Work Dir: ${WORK_DIR}"

# Convert the private key to PKCS8 DER format.
target_key_path=${WORK_DIR}/target_key.key
${OPENSSL_PATH} pkcs8 -topk8 -nocrypt -inform PEM -outform DER -in ${PRIVATE_KEY} -out ${target_key_path} 

# Generate a temporary AES key.
temp_aes_key_path=${WORK_DIR}/temp_aes_key.key
${OPENSSL_PATH} rand -out ${temp_aes_key_path} 32

# Wrap the temporary AES key by using RSA-OAEP with SHA-256.
wrapped_temp_aes_key=${WORK_DIR}/wrapped_temp_aes_key.bin
${OPENSSL_PATH} pkeyutl -encrypt -in ${temp_aes_key_path} -inkey ${WRAPPING_KEY} -pubin -out ${wrapped_temp_aes_key} -pkeyopt rsa_padding_mode:oaep -pkeyopt rsa_oaep_md:sha256

# Wrap the target RSA key.
wrapped_target_key=${WORK_DIR}/wrapped_target_key.bin
temp_aes_key_hexdump=$(hexdump -v -e '/1 "%02x"' < ${temp_aes_key_path})
${OPENSSL_PATH} enc -id-aes256-wrap-pad -iv A65959A6 -K ${temp_aes_key_hexdump} -in ${target_key_path} -out ${wrapped_target_key}

# Create the wrapped key material.
wrapped_key_material_bin=${WORK_DIR}/wrapped_key_material.bin
cat ${wrapped_temp_aes_key} ${wrapped_target_key} > ${wrapped_key_material_bin}

echo "Binary wrapped key for console is available at: ${wrapped_key_material_bin}"

#
# Import the wrapped key to the Vault service after base64 encoding the payload.
#
wrapped_key_material_base64=${WORK_DIR}/wrapped_key_material.base64
${BASE64} ${wrapped_key_material_bin} -w 0 > ${wrapped_key_material_base64}
echo "Base64 encoded wrapped key for CLI or API is available at: ${wrapped_key_material_base64}"


##### 1. IMPORT NEW KEY_VERSION USING CONSOLE #####
# browse and upload ${WORK_DIR}/wrapped_key_material.bin file in import key version section on console.

##### 2. IMPORT NEW KEY_VERSION USING OCI_CLI #####
# key_material=$(${BASE64} ${wrapped_key_material_bin})
# echo "{ \"wrappingAlgorithm\": \"RSA_OAEP_AES_SHA256\", \"keyMaterial\": \"${key_material}\" }" > wrapped_import_key.json
#
# oci kms management key-version import --key-id ${KEY_OCID} --wrapped-import-key file://wrapped_import_key.json