Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
En este tema, se describe cómo formatear tus claves para que Cloud KMS pueda importarlas como versiones de claves nuevas.
El formato correcto para tu material de clave varía según si el material de clave se importa a una clave simétrica o asimétrica. Para obtener más información sobre la diferencia entre las claves asimétricas y las asimétricas, consulta Algoritmos y propósitos de clave.
Formatos de claves compatibles
Claves simétricas para la encriptación:
Las claves simétricas importadas deben ser de 16 bytes (solo para la encriptación simétrica sin procesar) o de 32 bytes de datos binarios, y no deben estar codificadas.
Si tu clave está codificada en hexadecimal o en base64, debes decodificarla antes de intentar importarla.
Claves simétricas para firmar (claves MAC): Las claves de firma HMAC importadas deben tener una longitud igual a la longitud de salida de la función de hash criptográfica que se usa (por ejemplo, las claves HMAC-SHA256 deben tener una longitud de 32 bytes) y no deben codificarse. Si tu clave está codificada en hexadecimal o en base64, debes decodificarla antes de intentar importarla.
Claves asimétricas para encriptación o firma: Las claves asimétricas importadas deben estar en formato PKCS #8 y deben estar codificadas en DER. El formato PCKS #8 se define en RFC 5208. La codificación DER se define en Unión Internacional de Telecomunicaciones X.680. Las claves asimétricas deben usar una de las combinaciones de longitud y algoritmo compatibles con Cloud KMS.
Algunos aspectos de una clave, como su longitud, no se pueden cambiar después de la creación de la clave. En estos casos, la clave no se puede importar a Cloud KMS.
Verifica una clave simétrica
Usa el comando wc para verificar la longitud de una clave simétrica.
wc -c /path/to/unwrapped-key
No puedes importar una clave de encriptación simétrica con una longitud distinta de 32.
Las claves de firma simétricas (claves MAC) deben tener una longitud igual a la longitud de salida de la función de hash criptográfica que se usa (p.ej., las claves HMAC-SHA256 deben tener una longitud de 32 bytes).
Usa el comando file para verificar el formato de una clave.
file /path/to/unwrapped-key
Si el resultado es data, la clave está en el formato correcto para ser importada.
Si el resultado es ASCII text, usa el comando cat para mostrar el contenido del archivo.
Si es una cadena de letras y números que termina en un signo =, es posible que esté codificada en base64. Usa el comando base64 (Base64.exe en Windows) para decodificarlo. El siguiente es un ejemplo de una clave codificada en base64:
THzArjassB+giKeNeT1Zr74OgV24t+Ep+37Ec6ojB3Y=
Si contiene una o más líneas de números hexadecimales, es posible que esté codificado en hexadecimal. Usa el comando xxd (o el comando Format-Hex de PowerShell en Windows) para decodificarlo. El siguiente es un ejemplo de una clave con codificación hexadecimal:
Si contiene algún otro texto, es posible que no sea una clave simétrica válida.
Cómo formatear claves asimétricas
Se pueden importar claves asimétricas que usen cualquiera de los algoritmos compatibles. En la práctica, es difícil determinar de forma retroactiva el algoritmo que se usó para crear una clave asimétrica. Por esa razón, te recomendamos que ejecutes los siguientes comandos en cada clave asimétrica antes de intentar importarla a Cloud KMS.
Usa el comando file para verificar el formato de una clave.
file /path/to/unwrapped-key
Si el resultado es PEM, la clave está en formato PEM. Si es ASCII text, es probable que esté en formato PEM. En cualquier caso, ejecuta el siguiente comando para convertirlo al formato PKCS#8 DER:
Si el resultado es data, es probable que la clave esté en formato DER, pero es posible que no esté en formato PKCS #8. Ejecuta el siguiente comando para asegurarte de que la clave esté en el formato correcto. El comando no tiene efecto si la clave ya tiene el formato correcto. En ese caso, puedes usar el comando diff para verificar que el archivo de entrada y salida sean idénticos.
openssl pkcs8 -topk8 -nocrypt -inform DER -outform DER \
-in /path/to/asymmetric-key-der \
-out /path/to/formatted-key
Soluciona problemas
Si ejecutas los comandos anteriores y crees que la clave tiene un formato adecuado, pero la importación aún falla, comprueba si hay errores en la consola de Google Cloud y, luego, consulta Solución de problemas de importaciones con errores.
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-05 (UTC)"],[],[],null,["# Formatting keys for import\n\nThis topic describes how to format your keys so that they can be imported by\nCloud KMS as new key versions.\n\nThe correct format for your key material varies based on whether the key\nmaterial is being imported into a symmetric key, or into an asymmetric key. For\nmore information about the difference between symmetric and asymmetric keys, see\n[Key purposes and algorithms](/kms/docs/algorithms).\n\nSupported key formats\n---------------------\n\n- **Symmetric keys for encryption** : Imported symmetric keys must be 16 bytes (for [raw symmetric encryption](/kms/docs/raw-encryption) only) or 32 bytes of binary data, and must *not* be encoded. If your key is hex-encoded or base64-encoded, then you must decode it before attempting to import it.\n- **Symmetric keys for signing (MAC keys)** : Imported HMAC signing keys must have a length equal to the output length of the cryptographic hash function being used (for example, HMAC-SHA256 keys must have a length of 32 bytes), and must *not* be encoded. If your key is hex-encoded or base64-encoded, then you must decode it before attempting to import it.\n- **Asymmetric keys for encryption or signing** : Imported asymmetric keys must be in PKCS #8 format and must be DER-encoded. PCKS #8 format is defined in [RFC 5208](https://tools.ietf.org/html/rfc5208). DER encoding is defined in [International\n Telecommunications Union X.680](https://www.itu.int/rec/T-REC-X.680/en). Asymmetric keys must use one of the [length and algorithm combinations](/kms/docs/algorithms) supported by Cloud KMS.\n\n| **Important:** An RSA key's public exponent must be 65,537 or higher. This is a Digital Signature Standard (DSS) requirement noted in the Criteria for IFC Key Pairs section of [FIPS PUB 186-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf), Section B.3.1\n\nSome aspects of a key, such as the key's length, cannot be changed after the key\nis created. In these cases, the key cannot be imported into Cloud KMS.\n\nChecking a symmetric key\n------------------------\n\nUse the `wc` command to check a symmetric key's length. \n\n```\nwc -c /path/to/unwrapped-key\n```\n\n- You cannot import a symmetric encryption key with a length other than 32.\n\n- Symmetric signing keys (MAC keys) must have a length equal to the output\n length of the cryptographic hash function being used (e.g. HMAC-SHA256 keys\n must have a length of 32 bytes).\n\nUse the `file` command to check a key's format. \n\n```\nfile /path/to/unwrapped-key\n```\n\n- If the output is `data`, the key is in the correct format to be imported.\n\n- If the output is `ASCII text`, use the `cat` command to display the contents\n of the file.\n\n - If it is a string of letters and numbers ending in an `=` sign, it might\n be base64-encoded. Use the `base64` command (`Base64.exe` on Windows) to\n decode it. The following is an example of a base64-encoded key:\n\n ```\n THzArjassB+giKeNeT1Zr74OgV24t+Ep+37Ec6ojB3Y=\n ```\n - If it contains one or more lines of hexadecimal numbers, it might be\n hex-encoded. Use the `xxd` command (or the\n [`Format-Hex` PowerShell command](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/format-hex)\n on Windows) to decode it. The following is an example of a hex-encoded\n key:\n\n ```\n 00000000: 4c7c c0ae 36ac b01f a088 a78d 793d 59af L|..6.......y=Y.\n 00000010: be0e 815d b8b7 e129 fb7e c473 aa23 0776 ...]...).~.s.#.v\n ```\n - If it contains any other text, it may not be a valid symmetric key.\n\nFormatting asymmetric keys\n--------------------------\n\nAsymmetric keys using any of the supported [algorithms](/kms/docs/algorithms)\ncan be imported. In practice, it is difficult to retroactively determine the\nalgorithm used to create an asymmetric key. For that reason, we recommend that\nyou run the following commands on each asymmetric key before attempting to\nimport it into Cloud KMS.\n\n1. Use the `file` command to check a key's format.\n\n ```\n file /path/to/unwrapped-key\n ```\n - If the output is `PEM`, the key is in PEM format. If it is `ASCII text`,\n it is probably in PEM format. In either case, run the following command\n to convert it to PCKS#8 DER format:\n\n ```\n openssl pkcs8 -topk8 -nocrypt -inform PEM -outform DER \\\n -in /path/to/asymmetric-key-pem \\\n -out /path/to/formatted-key\n ```\n - If the output is `data`, the key is likely to be in DER format, but it\n may not be in PKCS #8 format. Run the following command to ensure that\n the key is in the correct format. The command has no effect if the key\n is already in the correct format. In that case, you can use the `diff`\n command to verify that the input and output file are identical.\n\n ```\n openssl pkcs8 -topk8 -nocrypt -inform DER -outform DER \\\n -in /path/to/asymmetric-key-der \\\n -out /path/to/formatted-key\n ```\n\nTroubleshooting\n---------------\n\nIf you run the commands above and you believe the key is in an appropriate\nformat, but the import still fails, check for errors in Google Cloud console, and\nthen see [Troubleshooting failed\nimports](/kms/docs/troubleshooting-failed-imports).\n\nWhat's next\n-----------\n\n- Continue to [Import a key version](/kms/docs/importing-a-key)\n- Learn about [key import](/kms/docs/key-import)"]]