Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Cette rubrique explique comment encapsuler manuellement une clé avant d'importer la clé dans Cloud KMS. Vous ne devez suivre les instructions de cette rubrique que si vous ne souhaitez pas utiliser la Google Cloud CLI pour encapsuler automatiquement la clé avant de l'importer. Pour obtenir un aperçu des différences, consultez la page Fonctionnement de l'importation de clés.
Vous pouvez suivre la procédure décrite dans cette rubrique en 5 à 10 minutes, sans compter les étapes Avant de commencer.
Avant de commencer
Avant de pouvoir encapsuler une clé, vous devez remplir les conditions préalables suivantes.
Cette section explique comment extraire la clé d'encapsulation de la tâche d'importation que vous avez créée dans la section Avant de commencer. Nous vous recommandons d'utiliser la console Google Cloud .
Console
Accédez à la page Gestion des clés dans la console Google Cloud .
Récupérez la clé publique via le champ publicKey de la réponse fournie par ImportJob.get. Cette valeur est de type WrappingPublicKey.
Le champ pem du type WrappingPublicKey est la clé publique codée au format PEM (Privacy Enhanced Mail).
Les commandes OpenSSL nécessitent plusieurs chemins de fichiers en tant que valeurs d'entrée. Définissez des variables d'environnement pour les chemins de fichiers afin de faciliter l'exécution des commandes.
Assurez-vous d'avoir accès en écriture aux répertoires que vous définissez ci-dessous.
Définissez la variable PUB_WRAPPING_KEY sur le chemin d'accès complet à la clé d'encapsulation que vous avez téléchargée depuis la tâche d'importation. La clé d'encapsulation se termine par .pem.
PUB_WRAPPING_KEY="WRAPPING_KEY_PATH"
Définissez la variable TARGET_KEY sur le chemin d'accès complet à la clé non encapsulée (cible).
TARGET_KEY=TARGET_KEY_PATH
Remplacez TARGET_KEY_PATH par le chemin d'accès au fichier .bin pour les clés symétriques ou par le chemin d'accès au fichier .der pour les clés asymétriques.
Si vous encapsulez avec RSA-AES, définissez la variable TEMP_AES_KEY sur le chemin d'accès complet à la clé AES temporaire.
TEMP_AES_KEY=TEMP_AES_KEY_PATH
Définissez la variable WRAPPED_KEY sur le chemin d'accès complet où vous souhaitez enregistrer la clé cible encapsulée prête à être importée.
WRAPPED_KEY=WRAPPED_KEY_PATH
Vérifiez que toutes les variables d'environnement sont correctement définies à l'aide des commandes suivantes :
Lorsque les variables sont correctement définies, vous êtes prêt à encapsuler la clé. Il existe deux approches, comme décrit ci-dessous: avec RSA uniquement ou avec RSA-AES.
Encapsuler la clé
Encapsuler la clé avec RSA
Dans cette approche, la clé cible est encapsulée dans un bloc RSA. La taille de la clé cible est donc limitée. Par exemple, vous ne pouvez pas utiliser cette méthode pour encapsuler une autre clé RSA. Les méthodes d'importation compatibles sont rsa-oaep-3072-sha256 et rsa-oaep-4096-sha256.
Encapsulez la clé cible avec la clé publique d'encapsulation à l'aide de l'algorithme CKM_RSA_PKCS_OAEP:
Dans cette approche, la clé cible est encapsulée avec une clé AES temporaire. La clé AES temporaire est ensuite encapsulée par la clé RSA. Ces deux clés encapsulées sont concatenatées et importées. Étant donné que la clé cible est encapsulée à l'aide d'AES plutôt que de RSA, cette approche peut être utilisée pour encapsuler de grandes clés. Les méthodes d'importation acceptées sont rsa-oaep-3072-sha1-aes-256, rsa-oaep-4096-sha1-aes-256, rsa-oaep-3072-sha256-aes-256 et rsa-oaep-4096-sha256-aes-256.
Générez une clé AES aléatoire temporaire de 32 octets et enregistrez-la à l'emplacement identifié par ${TEMP_AES_KEY}:
openssl rand -out "${TEMP_AES_KEY}" 32
Encapsulez la clé AES temporaire avec la clé publique d'encapsulation à l'aide de l'algorithme CKM_RSA_PKCS_OAEP. Si la méthode d'importation est rsa-oaep-3072-sha1-aes-256 ou rsa-oaep-4096-sha1-aes-256, utilisez sha1 pour rsa_oaep_md et rsa_mgf1_md. Utilisez sha256 pour rsa-oaep-3072-sha256-aes-256 et rsa-oaep-4096-sha256-aes-256.
Définissez la variable OpenSSL_V110 sur le chemin d'accès de votre script openssl.sh. Si vous avez bien suivi les instructions pour appliquer un correctif et recompiler OpenSSL, vous pouvez utiliser cette commande sans modifier la valeur de la variable.
OPENSSL_V110="${HOME}/local/bin/openssl.sh"
Encapsulez la clé cible avec la clé AES temporaire à l'aide de l'algorithme CKM_AES_KEY_WRAP_PAD, puis ajoutez-la à WRAPPED_KEY.
L'option -iv A65959A6 définit A65959A6 en tant que valeur initiale alternative. Ceci est requis par la spécification RFC 5649.
Étape suivante
La clé encapsulée enregistrée dans WRAPPED_KEY est maintenant prête à être importée.
Pour importer la clé, suivez les instructions de la section Importer une clé encapsulée manuellement.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/02 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/09/02 (UTC)."],[],[],null,["# Wrapping a key using OpenSSL on Linux\n\nThis topic shows how to manually wrap a key before\n[importing the key](/kms/docs/importing-a-key) into Cloud KMS. You\nonly need to follow the instructions in this topic if you do not want to use the\nGoogle Cloud CLI to automatically wrap the key before importing it. For an\noverview of the differences, refer to\n[How key import works](/kms/docs/key-import#key_import_flow).\n\nYou can complete the steps in this topic in 5 to 10 minutes, not including the\n[Before you begin](#before_you_begin) steps.\n\nBefore you begin\n----------------\n\nBefore you can wrap a key, you must complete the following prerequisites.\n\n1. [Create a target key ring and key, and create an import job](/kms/docs/importing-a-key).\n2. [Verify that your key is available locally and formatted correctly](/kms/docs/formatting-keys-for-import) for import into Cloud KMS.\n3. [Patch and recompile OpenSSL](/kms/docs/configuring-openssl-for-manual-key-wrapping)\n\nRetrieve the wrapping key\n-------------------------\n\nThis section shows how to retrieve the wrapping key from the import job you\ncreated in [Before you begin](#before_you_begin). Using the Google Cloud console is\nrecommended. \n\n### Console\n\n1. Go to the **Key Management** page in the Google Cloud console.\n\n [Go to the Key Management page](https://console.cloud.google.com/security/kms)\n2. Click the name of the key ring that contains your import job.\n\n3. Click the **Import Jobs** tab at the top of the page.\n\n4. Click **More** *more_vert* ,\n then **Download wrapping key** in the pop-up menu.\n\n### gcloud CLI\n\nTo verify that the import job is active, run the\n`gcloud kms import-jobs describe` command: \n\n```\ngcloud kms import-jobs describe IMPORT_JOB \\\n --location LOCATION \\\n --keyring KEY_RING \\\n --format=\"value(state)\"\n``` \n\n```\nstate: ACTIVE\n```\n\n\u003cbr /\u003e\n\nRun the following command to save the public key from the import job to\n`${HOME}/wrapping-key.pem` \n\n```\ngcloud kms import-jobs describe \\\n --location=LOCATION \\\n --keyring=KEY_RING \\\n --format=\"value(publicKey.pem)\" \\\n IMPORT_JOB \u003e ${HOME}/wrapping-key.pem\n```\n\n\u003cbr /\u003e\n\n| **Note:** You only need to download the public key once and can use it until the import job expires.\n\n### API\n\n1. Call the [`ImportJob.get`](/kms/docs/reference/rest/v1/projects.locations.keyRings.importJobs/get) method.\n\n2. Retrieve the public key via the [`publicKey`](/kms/docs/reference/rest/v1/projects.locations.keyRings.importJobs#ImportJob.FIELDS.public_key) field of the\n `ImportJob.get` response. This value is of type [`WrappingPublicKey`](/kms/docs/reference/rest/v1/projects.locations.keyRings.importJobs#WrappingPublicKey).\n The [`pem`](/kms/docs/reference/rest/v1/projects.locations.keyRings.importJobs#WrappingPublicKey.FIELDS.pem) field of the `WrappingPublicKey` type is the public\n key encoded in Privacy Enhanced Mail (PEM) format.\n\n| **Note:** Remember to verify that your key's [algorithm and length](/kms/docs/algorithms) are supported. Allowable algorithms for a key depend upon whether the key is used for symmetric encryption, asymmetric encryption or asymmetric signing, as well as whether the key is stored in software or a Hardware Security Module (HSM).\n\nFor more information about the PEM-encoded format, see\n[RFC 7468](https://tools.ietf.org/html/rfc7468), especially the\n[General Considerations](https://tools.ietf.org/html/rfc7468#section-2)\nand\n[Textual Encoding of Subject Public Key Info](https://tools.ietf.org/html/rfc7468#section-2)\nsections.\n\nSet up environment variables\n----------------------------\n\nThe OpenSSL commands require several file paths as input values. Define\nenvironment variables for the file paths to make it easier to run the commands.\nMake sure you have access to write to the directories you define below.\n| **Note:** If desired, you can save all of these commands to a shell script and run the script to set the variables all at once. You may need to adjust some of the values for each key you want to wrap.\n\n1. Set the `PUB_WRAPPING_KEY` variable to the full path to the wrapping key you\n downloaded from the import job. The wrapping key ends in `.pem`.\n\n ```\n PUB_WRAPPING_KEY=\"WRAPPING_KEY_PATH\"\n ```\n\n \u003cbr /\u003e\n\n2. Set the `TARGET_KEY` variable to the full path to the unwrapped (target) key.\n\n ```\n TARGET_KEY=TARGET_KEY_PATH\n ```\n\n \u003cbr /\u003e\n\n Replace `TARGET_KEY_PATH` with the path to the `.bin` file for\n symmetric keys or the path to the `.der` file for asymmetric keys.\n3. If wrapping with RSA-AES, set the `TEMP_AES_KEY` variable to the full path\n to the temporary AES key.\n\n ```\n TEMP_AES_KEY=TEMP_AES_KEY_PATH\n ```\n\n \u003cbr /\u003e\n\n4. Set the `WRAPPED_KEY` variable to the full path where you\n want to save the wrapped target key that is ready for\n import.\n\n ```\n WRAPPED_KEY=WRAPPED_KEY_PATH\n ```\n\n \u003cbr /\u003e\n\n5. Verify that all the environment variables are set correctly using the\n following commands:\n\n ```\n echo \"PUB_WRAPPING_KEY: \" ${PUB_WRAPPING_KEY}; \\\n echo \"TARGET_KEY: \" ${TARGET_KEY}; \\\n echo \"TEMP_AES_KEY: \" ${TEMP_AES_KEY}; \\\n echo \"WRAPPED_KEY: \" ${WRAPPED_KEY}\n ```\n\n \u003cbr /\u003e\n\nWhen the variables are set correctly, you are ready to wrap the key. There are\ntwo approaches as described below: with [RSA only](#rsa_wrap) or with\n[RSA-AES](#rsa_aes_wrap).\n\nWrap the key\n------------\n\n### Wrap the key with RSA\n\nIn this approach, the target key is wrapped in an RSA block. The target key size\nis therefore limited. For example, you can't use this method to wrap another RSA\nkey. The supported import methods are `rsa-oaep-3072-sha256` and\n`rsa-oaep-4096-sha256`.\n\n- Wrap the target key with the wrapping public key using\n the `CKM_RSA_PKCS_OAEP` algorithm:\n\n ```\n openssl pkeyutl \\\n -encrypt \\\n -pubin \\\n -inkey ${PUB_WRAPPING_KEY} \\\n -in ${TARGET_KEY} \\\n -out ${WRAPPED_KEY} \\\n -pkeyopt rsa_padding_mode:oaep \\\n -pkeyopt rsa_oaep_md:sha256 \\\n -pkeyopt rsa_mgf1_md:sha256\n ```\n\n \u003cbr /\u003e\n\n### Wrap the key with RSA-AES\n\nIn this approach, the target key is wrapped with a temporary AES key. The\ntemporary AES key is then wrapped by the RSA key. These two wrapped keys are\nconcatenated and imported. Because the target key is wrapped using AES rather\nthan RSA, this approach can be used to wrap large keys. The supported import\nmethods are `rsa-oaep-3072-sha1-aes-256`, `rsa-oaep-4096-sha1-aes-256`,\n`rsa-oaep-3072-sha256-aes-256` and `rsa-oaep-4096-sha256-aes-256`.\n\n1. Generate a temporary random AES key that is 32 bytes long, and save it to\n the location identified by `${TEMP_AES_KEY}`:\n\n ```\n openssl rand -out \"${TEMP_AES_KEY}\" 32\n ```\n\n \u003cbr /\u003e\n\n2. Wrap the temporary AES key with the wrapping public key using\n the `CKM_RSA_PKCS_OAEP` algorithm. If the import method is either\n `rsa-oaep-3072-sha1-aes-256` or `rsa-oaep-4096-sha1-aes-256`, use `sha1` for\n `rsa_oaep_md` and `rsa_mgf1_md`. Use `sha256` for\n `rsa-oaep-3072-sha256-aes-256` and `rsa-oaep-4096-sha256-aes-256`.\n\n ```\n openssl pkeyutl \\\n -encrypt \\\n -pubin \\\n -inkey ${PUB_WRAPPING_KEY} \\\n -in ${TEMP_AES_KEY} \\\n -out ${WRAPPED_KEY} \\\n -pkeyopt rsa_padding_mode:oaep \\\n -pkeyopt rsa_oaep_md:{sha1|sha256} \\\n -pkeyopt rsa_mgf1_md:{sha1|sha256}\n ```\n\n \u003cbr /\u003e\n\n3. Set the `OpenSSL_V110` variable to the path of your `openssl.sh` script. If\n you followed the instructions for\n [patching and recompiling OpenSSL](/kms/docs/configuring-openssl-for-manual-key-wrapping) exactly,\n you can use this command without modifying the value of the variable.\n\n ```\n OPENSSL_V110=\"${HOME}/local/bin/openssl.sh\"\n ```\n\n \u003cbr /\u003e\n\n4. Wrap the target key with the temporary AES key using the\n `CKM_AES_KEY_WRAP_PAD` algorithm, and append it to the `WRAPPED_KEY`.\n\n ```\n \"${OPENSSL_V110}\" enc \\\n -id-aes256-wrap-pad \\\n -iv A65959A6 \\\n -K $( hexdump -v -e '/1 \"%02x\"' \u003c \"${TEMP_AES_KEY}\" ) \\\n -in \"${TARGET_KEY}\" \u003e\u003e \"${WRAPPED_KEY}\"\n ```\n\n \u003cbr /\u003e\n\n The `-iv A65959A6` flag sets A65959A6 as the Alternate Initial Value. This\n is required by the [RFC 5649](https://tools.ietf.org/html/rfc5649)\n specification.\n\nWhat's next\n-----------\n\n- The wrapped key saved at `WRAPPED_KEY` is now ready to be imported. To import the key, follow the instructions in [Importing a\n manually-wrapped key](/kms/docs/importing-a-key#importing_a_manually-wrapped_key)."]]