En este tema, se muestra cómo realizar las siguientes operaciones con claves simétricas:
- Encriptar texto o contenido binario (sin formato) mediante una clave de Cloud Key Management Service
- Desencriptar cifrado que se encriptó con una clave de Cloud KMS
Si, en cambio, deseas usar una clave asimétrica para la encriptación, consulta Encripta y desencripta datos con una clave asimétrica. Para obtener más información sobre la encriptación simétrica sin procesar, consulta Encriptación simétrica sin procesar.
Antes de comenzar
Crea un llavero de claves y una clave como se describe en Crea claves y llaveros de claves.
Asegúrate de que el usuario que llama a los métodos de encriptación y desencriptación tenga los permisos
cloudkms.cryptoKeyVersions.useToEncrypt
ycloudkms.cryptoKeyVersions.useToDecrypt
sobre la clave que se usó para encriptar o desencriptar.Una forma de permitirle a un usuario que encripte o desencripte es agregar el usuario a las funciones de IAM
roles/cloudkms.cryptoKeyEncrypter
,roles/cloudkms.cryptoKeyDecrypter
oroles/cloudkms.cryptoKeyEncrypterDecrypter
para esa clave. Ten en cuenta que la funciónroles/cloudkms.admin
no proporciona estos dos permisos. Para obtener más información, consulta el artículo sobre permisos y funciones.
Encriptar
gcloud
Para usar Cloud KMS en la línea de comandos, primero Instala o actualiza a la versión más reciente de Google Cloud CLI.
gcloud kms encrypt \ --key key \ --keyring key-ring \ --location location \ --plaintext-file file-with-data-to-encrypt \ --ciphertext-file file-to-store-encrypted-data
Reemplaza key por el nombre de la clave que se usará para la encriptación. Reemplaza key-ring por el nombre del llavero de claves en el que se encuentra la clave. Reemplaza location por la ubicación de Cloud KMS para el el llavero de claves. Reemplaza file-with-data-to-encrypt y file-to-store-encrypted-data por las rutas de los archivos locales para leer los datos de texto simple y guardar el resultado encriptado.
Para obtener información sobre todas las marcas y los valores posibles, ejecuta el comando con la marca --help
.
C#
Para ejecutar este código, primero configura un entorno de desarrollo de C# e instala el SDK de C# para Cloud KMS.
Go
Para ejecutar este código, primero configura un entorno de desarrollo de Go y, luego, instala el SDK de Go para Cloud KMS.
Java
Para ejecutar este código, primero configura un entorno de desarrollo de Java y, luego, instala el SDK de Java para Cloud KMS.
Node.js
Para ejecutar este código, primero configura un entorno de desarrollo de Node.js y, luego, instala el SDK de Node.js para Cloud KMS.
PHP
Para ejecutar este código, primero obtén información sobre cómo usar PHP en Google Cloud y, luego, instala el SDK de PHP para Cloud KMS.
Python
Para ejecutar este código, primero configura un entorno de desarrollo de Python y, luego, instala el SDK de Python para Cloud KMS.
Ruby
Para ejecutar este código, primero configura un entorno de desarrollo de Ruby y, luego, instala el SDK de Ruby para Cloud KMS.
API
En estos ejemplos, se usa curl como un cliente HTTP para demostrar el uso de la API. Para obtener más información sobre el control de acceso, consulta Accede a la API de Cloud KMS.
Cuando usas JSON y la API de REST, debes codificar el contenido en Base64 antes de que pueda encriptarlo Cloud KMS.
Para encriptar datos, realiza una solicitud POST
, proporciona la información del proyecto y la clave que corresponda, y especifica el texto codificado en Base64 que se encriptará en el campo plaintext
del cuerpo de la solicitud.
curl "https://cloudkms.googleapis.com/v1/projects/project-id/locations/location/keyRings/key-ring-name/cryptoKeys/key-name:encrypt" \ --request "POST" \ --header "authorization: Bearer token" \ --header "content-type: application/json" \ --data "{\"plaintext\": \"base64-encoded-input\"}"
Esta es una carga útil de ejemplo con datos codificados en Base64:
{ "plaintext": "U3VwZXIgc2VjcmV0IHRleHQgdGhhdCBtdXN0IGJlIGVuY3J5cHRlZAo=", }
Decrypt
gcloud
Para usar Cloud KMS en la línea de comandos, primero Instala o actualiza a la versión más reciente de Google Cloud CLI.
gcloud kms decrypt \ --key key \ --keyring key-ring \ --location location \ --ciphertext-file file-path-with-encrypted-data \ --plaintext-file file-path-to-store-plaintext
Reemplaza key por el nombre de la clave que se usará para la desencriptación. Reemplaza key-ring por el nombre del llavero de claves donde se ubicará la clave. Reemplaza location por la ubicación de Cloud KMS para el llavero de claves. Reemplaza file-path-with-encrypted-data y file-path-to-store-plaintext por las rutas de acceso de los archivos locales para leer los datos encriptados y guardar el resultado desencriptado.
Para obtener información sobre todas las marcas y los valores posibles, ejecuta el comando con la marca --help
.
C#
Para ejecutar este código, primero configura un entorno de desarrollo de C# e instala el SDK de C# para Cloud KMS.
Go
Para ejecutar este código, primero configura un entorno de desarrollo de Go y, luego, instala el SDK de Go para Cloud KMS.
Java
Para ejecutar este código, primero configura un entorno de desarrollo de Java y, luego, instala el SDK de Java para Cloud KMS.
Node.js
Para ejecutar este código, primero configura un entorno de desarrollo de Node.js y, luego, instala el SDK de Node.js para Cloud KMS.
PHP
Para ejecutar este código, primero obtén información sobre cómo usar PHP en Google Cloud y, luego, instala el SDK de PHP para Cloud KMS.
Python
Para ejecutar este código, primero configura un entorno de desarrollo de Python y, luego, instala el SDK de Python para Cloud KMS.
Ruby
Para ejecutar este código, primero configura un entorno de desarrollo de Ruby y, luego, instala el SDK de Ruby para Cloud KMS.
API
En estos ejemplos, se usa curl como un cliente HTTP para demostrar el uso de la API. Para obtener más información sobre el control de acceso, consulta Accede a la API de Cloud KMS.
El texto desencriptado que se muestra en el archivo JSON de Cloud KMS está codificado en base64.
Para desencriptar datos, haz una solicitud POST
y proporciona la información del proyecto y de la clave correspondientes y especifica el texto encriptado (algoritmo de cifrado) que se desencriptará en el campo ciphertext
del cuerpo de la solicitud.
curl "https://cloudkms.googleapis.com/v1/projects/project-id/locations/location/keyRings/key-ring-name/cryptoKeys/key-name:decrypt" \ --request "POST" \ --header "authorization: Bearer token" \ --header "content-type: application/json" \ --data "{\"ciphertext\": \"encrypted-content\"}"
Esta es una carga útil de ejemplo con datos codificados en Base64:
{ "ciphertext": "CiQAhMwwBo61cHas7dDgifrUFs5zNzBJ2uZtVFq4ZPEl6fUVT4kSmQ...", }
¿Qué sigue?
- Obtén más información sobre la encriptación simétrica sin procesar.
- Lee más sobre la encriptación de sobre.
- Prueba los datos de encriptación y desencriptación con Codelab de Cloud KMS.