Organízate con las colecciones
Guarda y clasifica el contenido según tus preferencias.
En este tema se describe cómo dar formato a las claves para que Cloud KMS pueda importarlas como nuevas versiones de claves.
El formato correcto del material de la clave varía en función de si se importa en una clave simétrica o asimétrica. Para obtener más información sobre la diferencia entre las claves simétricas y asimétricas, consulta Usos y algoritmos de las claves.
Formatos de clave admitidos
Claves simétricas para el cifrado:
Las claves simétricas importadas deben tener 16 bytes (solo para el cifrado simétrico sin formato) o 32 bytes de datos binarios, y no deben estar codificadas.
Si tu clave está codificada en hexadecimal o en Base64, debes descodificarla antes de
intentar importarla.
Claves simétricas para la firma (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 esté usando (por ejemplo, las claves HMAC-SHA256 deben tener una longitud de 32
bytes) y no deben estar codificadas. Si tu clave está codificada en hexadecimal o en Base64, debes descodificarla antes de intentar importarla.
Claves asimétricas para cifrado o firma: las claves asimétricas importadas deben tener el formato PKCS #8 y estar codificadas en DER. El formato PCKS #8 se define en RFC 5208. La codificación DER se define en la 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 una vez que se ha creado. En estos casos, la clave no se puede importar a Cloud KMS.
Comprobar una clave simétrica
Usa el comando wc para comprobar la longitud de una clave simétrica.
wc -c /path/to/unwrapped-key
No puedes importar una clave de cifrado 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 hash criptográfica que se esté usando (por ejemplo, las claves HMAC-SHA256 deben tener una longitud de 32 bytes).
Usa el comando file para comprobar el formato de una clave.
file /path/to/unwrapped-key
Si el resultado es data, la clave tiene el formato correcto para importarse.
Si la salida es ASCII text, usa el comando cat para mostrar el contenido del archivo.
Si se trata de una cadena de letras y números que termina con el signo =, es posible que esté codificada en base64. Usa el comando base64 (Base64.exe en Windows) para descodificarlo. A continuación, se muestra un ejemplo de una clave codificada en base64:
THzArjassB+giKeNeT1Zr74OgV24t+Ep+37Ec6ojB3Y=
Si contiene una o varias líneas de números hexadecimales, es posible que esté codificado en hexadecimal. Usa el comando xxd (o el comando de PowerShell Format-Hex en Windows) para descodificarlo. A continuación, se muestra un ejemplo de una clave codificada en hexadecimal:
Si contiene otro texto, es posible que no sea una clave simétrica válida.
Dar formato a las claves asimétricas
Se pueden importar claves asimétricas con cualquiera de los algoritmos admitidos. En la práctica, es difícil determinar retroactivamente el algoritmo utilizado para crear una clave asimétrica. Por este motivo, te recomendamos que ejecutes los siguientes comandos en cada clave asimétrica antes de intentar importarla en Cloud KMS.
Usa el comando file para comprobar 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,
probablemente esté en formato PEM. En cualquier caso, ejecuta el siguiente comando para convertirlo al formato DER de PCKS#8:
Si el resultado es data, es probable que la clave esté en formato DER, pero puede que no esté en formato PKCS #8. Ejecuta el siguiente comando para asegurarte de que la clave tiene el formato correcto. El comando no tiene ningún 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 el de salida son idénticos.
openssl pkcs8 -topk8 -nocrypt -inform DER -outform DER \
-in /path/to/asymmetric-key-der \
-out /path/to/formatted-key
Solución de problemas
Si ejecutas los comandos anteriores y crees que la clave tiene el formato adecuado, pero la importación sigue fallando, comprueba si hay errores en la Google Cloud consola y, a continuación, consulta la sección Solucionar problemas de importaciones fallidas.
[[["Es fácil de entender","easyToUnderstand","thumb-up"],["Me ofreció una solución al problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Es difícil de entender","hardToUnderstand","thumb-down"],["La información o el código de muestra no son correctos","incorrectInformationOrSampleCode","thumb-down"],["Me faltan las muestras o la información que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-10 (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)"]]