Este tópico demonstra como chamar as APIs Encrypt e Decrypt com o SDK de instância do KMS para Go. Assim, você criptografa e descriptografa dados usando uma chave simétrica.
Pré-requisitos
Antes de começar, verifique se você tem:
Uma instância do KMS com uma chave simétrica criada
Um arquivo ClientKey ou seu conteúdo e a senha correspondente
O arquivo de certificado CA da sua instância do KMS (
caCert.pem)O endpoint da sua instância do KMS no formato
<KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com
Complete example
Explicação do exemplo
As seções a seguir detalham cada parte do exemplo completo acima.
Inicialize o cliente
Crie um cliente do Dedicated Key Management Service (DKMS) usando o conteúdo do ClientKey ou o caminho do arquivo ClientKey. Ambos os métodos exigem o protocolo HTTPS, pois o service de instância do KMS não aceita conexões sem HTTPS.
Com o conteúdo do ClientKey (guia de inicialização do cliente para Go):
import (
dedicatedkmsopenapi "github.com/aliyun/alibabacloud-dkms-gcs-go-sdk/openapi"
dedicatedkmssdk "github.com/aliyun/alibabacloud-dkms-gcs-go-sdk/sdk"
"github.com/alibabacloud-go/tea/tea"
)
func getDkmsClientByClientKeyContent() *dedicatedkmssdk.Client {
config := &dedicatedkmsopenapi.Config{
Protocol: tea.String("https"),
ClientKeyContent: tea.String("<CLIENT_KEY_CONTENT>"),
Password: tea.String("<CLIENT_KEY_PASSWORD>"),
Endpoint: tea.String("<ENDPOINT>"),
}
client, err := dedicatedkmssdk.NewClient(config)
if err != nil {
panic(err)
}
return client
}
Com o caminho do arquivo ClientKey:
func getDkmsClientByClientKeyFile() *dedicatedkmssdk.Client {
config := &dedicatedkmsopenapi.Config{
Protocol: tea.String("https"),
ClientKeyFile: tea.String("<CLIENT_KEY_FILE>"),
Password: tea.String("<CLIENT_KEY_PASSWORD>"),
Endpoint: tea.String("<ENDPOINT>"),
}
client, err := dedicatedkmssdk.NewClient(config)
if err != nil {
panic(err)
}
return client
}
Substitua os espaços reservados pelos valores reais:
|
Espaço reservado |
Descrição |
|
|
Conteúdo do arquivo ClientKey |
|
|
Caminho para o arquivo ClientKey |
|
|
Senha definida ao criar o ClientKey |
|
|
|
Chame a API Encrypt para criptografar dados
A função EncryptWithOptions recebe um KeyId e um Plaintext. Ela retorna o texto cifrado, o vetor de inicialização (IV) e o algoritmo usado.
Salve os valores de Iv, CiphertextBlob e Algorithm da resposta de criptografia. Todos são obrigatórios para descriptografar os dados. O Iv é gerado a cada chamada e não pode ser reconstruído.
func encryptSample(client *dedicatedkmssdk.Client, plaintext []byte, keyId string) *AesEncryptContext {
encryptRequest := &dedicatedkmssdk.EncryptRequest{
KeyId: tea.String(keyId),
Plaintext: plaintext,
}
// Verify the server certificate.
ca, err := ioutil.ReadFile("path/to/caCert.pem")
if err != nil {
panic(err)
}
runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
Verify: tea.String(string(ca)),
}
// Or, ignore the certificate.
//runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
// IgnoreSSL: tea.Bool(true),
//}
encryptResponse, err := client.EncryptWithOptions(encryptRequest, runtimeOptions)
if err != nil {
panic(err)
}
_keyId := tea.StringValue(encryptResponse.KeyId)
_iv := encryptResponse.Iv // Required for decryption.
_cipher := encryptResponse.CiphertextBlob
_algorithm := tea.StringValue(encryptResponse.Algorithm)
fmt.Println("KeyId:", _keyId)
fmt.Println("CiphertextBlob:", _cipher)
fmt.Println("Iv:", _iv)
fmt.Println("Algorithm:", _algorithm)
fmt.Println("RequestId:", tea.StringValue(encryptResponse.RequestId))
return &AesEncryptContext{
KeyId: _keyId,
Iv: _iv,
CiphertextBlob: _cipher,
Algorithm: _algorithm,
}
}
Chame a API Decrypt para descriptografar dados
A função DecryptWithOptions usa o KeyId, o CiphertextBlob, o Iv e o Algorithm da resposta de criptografia para retornar o texto simples original.
func decryptSample(client *dedicatedkmssdk.Client, ctx *AesEncryptContext) []byte {
decryptRequest := &dedicatedkmssdk.DecryptRequest{
KeyId: tea.String(ctx.KeyId),
CiphertextBlob: ctx.CiphertextBlob,
Iv: ctx.Iv, // Must be the Iv returned by Encrypt.
Algorithm: tea.String(ctx.Algorithm),
}
// Verify the server certificate.
ca, err := ioutil.ReadFile("path/to/caCert.pem")
if err != nil {
panic(err)
}
runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
Verify: tea.String(string(ca)),
}
// Or, ignore the certificate.
//runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
// IgnoreSSL: tea.Bool(true),
//}
decryptResponse, err := client.DecryptWithOptions(decryptRequest, runtimeOptions)
if err != nil {
panic(err)
}
fmt.Println("KeyId:", tea.StringValue(decryptResponse.KeyId))
fmt.Println("Plaintext:", string(decryptResponse.Plaintext))
fmt.Println("RequestId:", tea.StringValue(decryptResponse.RequestId))
return decryptResponse.Plaintext
}