Neste tópico, você verá como realizar as seguintes operações de chave simétrica:
- Usar uma chave do Cloud Key Management Service para criptografar texto ou conteúdo binário (texto simples).
- Descriptografar texto cifrado que foi criptografado com uma chave do Cloud KMS.
Se você quiser usar uma chave assimétrica para criptografia, consulte Como criptografar e descriptografar dados com uma chave assimétrica. Para saber mais sobre criptografia simétrica bruta, consulte criptografia simétrica bruta.
Antes de começar
Crie um keyring e uma chave, conforme descrito em Como criar keyrings e chaves.
Verifique se o usuário que está chamando os métodos de criptografia e descriptografia tem as permissões
cloudkms.cryptoKeyVersions.useToEncrypt
ecloudkms.cryptoKeyVersions.useToDecrypt
na chave usada para criptografar ou descriptografar.Uma maneira de permitir que um usuário criptografe ou descriptografe é adicionar o usuário aos papéis de IAM
roles/cloudkms.cryptoKeyEncrypter
,roles/cloudkms.cryptoKeyDecrypter
ouroles/cloudkms.cryptoKeyEncrypterDecrypter
dessa chave. O papelroles/cloudkms.admin
não concede essas duas permissões. Para mais informações, consulte Permissões e papéis.
Encrypt
gcloud
Para usar o Cloud KMS na linha de comando, primeiro Instale ou faça upgrade para a versão mais recente da 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
Substitua key pelo nome da chave a ser usada para criptografia. Substitua key-ring pelo nome do keyring em que a chave está localizada. Substitua location pelo local do Cloud KMS do keyring. Substitua file-with-data-to-encrypt e file-to-store-encrypted-data pelos caminhos de arquivo local para ler os dados de texto simples e salvar a saída criptografada.
Para informações sobre todas as sinalizações e valores possíveis, execute o comando com a sinalização --help
.
C#
Para executar esse código, primeiro configure um ambiente de desenvolvimento C# e instale o SDK do Cloud KMS para C#.
Go
Para executar esse código, primeiro configure um ambiente de desenvolvimento Go e instale o SDK do Cloud KMS para Go.
Java
Para executar esse código, primeiro configure um ambiente de desenvolvimento Java e instale o SDK do Cloud KMS para Java.
Node.js
Para executar esse código, primeiro configure um ambiente de desenvolvimento do Node.js e instale o SDK do Cloud KMS para Node.js.
PHP
Para executar esse código, primeiro saiba como usar o PHP no Google Cloud e instalar o SDK do Cloud KMS para PHP.
Python
Para executar esse código, primeiro configure um ambiente de desenvolvimento Python e instale o SDK do Cloud KMS para Python.
Ruby
Para executar esse código, primeiro configure um ambiente de desenvolvimento Ruby e instale o SDK do Cloud KMS para Ruby.
API
Estes exemplos usam curl como um cliente HTTP para demonstrar o uso da API. Para mais informações sobre controle de acesso, consulte Como acessar a API Cloud KMS.
Ao usar o JSON e a API REST, o conteúdo precisa ser codificado em Base64 antes de ser criptografado pelo Cloud KMS.
Para criptografar dados, faça uma solicitação POST
e forneça as informações apropriadas do projeto e da chave. Além disso, especifique o texto codificado em base64 a ser criptografado no campo plaintext
do corpo da solicitação.
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\"}"
Veja um exemplo de payload com dados codificados em base64:
{ "plaintext": "U3VwZXIgc2VjcmV0IHRleHQgdGhhdCBtdXN0IGJlIGVuY3J5cHRlZAo=", }
Decrypt
gcloud
Para usar o Cloud KMS na linha de comando, primeiro Instale ou faça upgrade para a versão mais recente da 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
Substitua key pelo nome da chave a ser usada para descriptografia. Substitua key-ring pelo nome do keyring em que a chave estará localizada. Substitua location pelo local do Cloud KMS para o keyring. Substitua file-path-with-encrypted-data e file-path-to-store-plaintext pelos caminhos de arquivo locais para ler os dados criptografados e salvar a saída descriptografada.
Para informações sobre todas as sinalizações e valores possíveis, execute o comando com a sinalização --help
.
C#
Para executar esse código, primeiro configure um ambiente de desenvolvimento C# e instale o SDK do Cloud KMS para C#.
Go
Para executar esse código, primeiro configure um ambiente de desenvolvimento Go e instale o SDK do Cloud KMS para Go.
Java
Para executar esse código, primeiro configure um ambiente de desenvolvimento Java e instale o SDK do Cloud KMS para Java.
Node.js
Para executar esse código, primeiro configure um ambiente de desenvolvimento do Node.js e instale o SDK do Cloud KMS para Node.js.
PHP
Para executar esse código, primeiro saiba como usar o PHP no Google Cloud e instalar o SDK do Cloud KMS para PHP.
Python
Para executar esse código, primeiro configure um ambiente de desenvolvimento Python e instale o SDK do Cloud KMS para Python.
Ruby
Para executar esse código, primeiro configure um ambiente de desenvolvimento Ruby e instale o SDK do Cloud KMS para Ruby.
API
Estes exemplos usam curl como um cliente HTTP para demonstrar o uso da API. Para mais informações sobre controle de acesso, consulte Como acessar a API Cloud KMS.
O texto descriptografado retornado no JSON do Cloud KMS é codificado em base64.
Para descriptografar dados criptografados, crie uma solicitação POST
e forneça as informações apropriadas do projeto e da chave. Além disso, especifique o texto criptografado a ser descriptografado no campo ciphertext
do corpo da solicitação.
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\"}"
Veja um exemplo de payload com dados codificados em base64:
{ "ciphertext": "CiQAhMwwBo61cHas7dDgifrUFs5zNzBJ2uZtVFq4ZPEl6fUVT4kSmQ...", }
A seguir
- Leia mais sobre criptografia simétrica bruta.
- Leia mais sobre criptografia de envelope.
- Confira o codelab Criptografar e descriptografar dados com o Cloud KMS.