Compartilhar via


Início rápido: biblioteca de clientes de chaves do Azure Key Vault para Go

Neste início rápido, você aprenderá a usar o SDK do Azure para Go para criar, recuperar, atualizar, listar e excluir chaves do Azure Key Vault.

O Azure Key Vault é um serviço de nuvem que funciona como um repositório de segredos seguro. Você pode armazenar chaves, senhas, certificados e outros segredos com segurança. Para saber mais sobre o Key Vault, analise a Visão geral.

Siga este guia para saber como usar o pacote azkeys para gerenciar suas chaves do Azure Key Vault usando o Go.

Prerequisites

Entre no Portal do Azure

  1. Execute o seguinte comando na CLI do Azure:

    az login
    

    Se a CLI do Azure puder abrir seu navegador padrão, ele abrirá o navegador para a página de entrada do portal do Azure.

    Se a página não abrir automaticamente, acesse https://aka.ms/devicelogin, e então digite o código de autorização que é exibido em seu terminal.

  2. Entre no portal do Azure com as credenciais da sua conta.

Criar um grupo de recursos e um cofre de chaves

Este início rápido usa um cofre de chaves do Azure pré-criado. Você pode criar um cofre de chaves seguindo as etapas nestes guias de início rápido:

Como alternativa, você pode executar esses comandos da CLI do Azure.

Important

Cada cofre de chaves deve ter um nome exclusivo. Substitua <seu-nome-de cofre-de-chaves-exclusivo> pelo nome do seu cofre de chaves nos exemplos a seguir.

az group create --name "myResourceGroup" -l "EastUS"

az keyvault create --name "<your-unique-keyvault-name>" -g "myResourceGroup" --enable-rbac-authorization

Permitir acesso ao cofre de chaves

Para obter permissões para o cofre de chaves por meio do RBAC (controle de acesso baseado em função), atribua uma função ao seu UPN (nome principal do usuário) usando o comando da CLI do Azure az role assignment create.

az role assignment create --role "Key Vault Crypto Officer" --assignee "<upn>" --scope "/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.KeyVault/vaults/<your-unique-keyvault-name>"

Substitua <upn>, <subscription-id>, <resource-group-name> e <your-unique-keyvault-name> pelos valores reais. Seu UPN normalmente estará no formato de um endereço de email (por exemplo, username@domain.com).

Criar um módulo Go e instalar pacotes

Execute os seguintes comandos Go:

go mod init quickstart-keys
go get -u github.com/Azure/azure-sdk-for-go/sdk/azidentity
go get -u github.com/Azure/azure-sdk-for-go/sdk/keyvault/azkeys

Criar o código de exemplo

Crie um arquivo chamado main.go e copie o seguinte código nele:

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	"github.com/Azure/azure-sdk-for-go/sdk/keyvault/azkeys"
)

func main() {
	keyVaultName := os.Getenv("KEY_VAULT_NAME")
	keyVaultUrl := fmt.Sprintf("https://%s.vault.azure.net/", keyVaultName)

	// create credential
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}

	// create azkeys client
	client, err := azkeys.NewClient(keyVaultUrl, cred, nil)
	if err != nil {
		log.Fatal(err)
	}

	// create RSA Key
	rsaKeyParams := azkeys.CreateKeyParameters{
		Kty:     to.Ptr(azkeys.JSONWebKeyTypeRSA),
		KeySize: to.Ptr(int32(2048)),
	}
	rsaResp, err := client.CreateKey(context.TODO(), "new-rsa-key", rsaKeyParams, nil)
	if err != nil {
		log.Fatalf("failed to create rsa key: %v", err)
	}
	fmt.Printf("New RSA key ID: %s\n", *rsaResp.Key.KID)

	// create EC Key
	ecKeyParams := azkeys.CreateKeyParameters{
		Kty:   to.Ptr(azkeys.JSONWebKeyTypeEC),
		Curve: to.Ptr(azkeys.JSONWebKeyCurveNameP256),
	}
	ecResp, err := client.CreateKey(context.TODO(), "new-ec-key", ecKeyParams, nil)
	if err != nil {
		log.Fatalf("failed to create ec key: %v", err)
	}
	fmt.Printf("New EC key ID: %s\n", *ecResp.Key.KID)

	// list all vault keys
	fmt.Println("List all vault keys:")
	pager := client.NewListKeysPager(nil)
	for pager.More() {
		page, err := pager.NextPage(context.TODO())
		if err != nil {
			log.Fatal(err)
		}
		for _, key := range page.Value {
			fmt.Println(*key.KID)
		}
	}

	// update key properties to disable key
	updateParams := azkeys.UpdateKeyParameters{
		KeyAttributes: &azkeys.KeyAttributes{
			Enabled: to.Ptr(false),
		},
	}
	// an empty string version updates the latest version of the key
	version := ""
	updateResp, err := client.UpdateKey(context.TODO(), "new-rsa-key", version, updateParams, nil)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Key %s Enabled attribute set to: %t\n", *updateResp.Key.KID, *updateResp.Attributes.Enabled)

	// delete the created keys
	for _, keyName := range []string{"new-rsa-key", "new-ec-key"} {
		// DeleteKey returns when Key Vault has begun deleting the key. That can take several
		// seconds to complete, so it may be necessary to wait before performing other operations
		// on the deleted key.
		delResp, err := client.DeleteKey(context.TODO(), keyName, nil)
		if err != nil {
			panic(err)
		}
		fmt.Printf("Successfully deleted key %s", *delResp.Key.KID)
	}
}

Executar o código

Antes de executar o código, crie uma variável de ambiente chamada KEY_VAULT_NAME. Defina o valor da variável de ambiente para o nome do Azure Key Vault criado anteriormente.

export KEY_VAULT_NAME=quickstart-kv

Em seguida, execute o seguinte comando go run para executar o aplicativo:

go run main.go
Key ID: https://quickstart-kv.vault.azure.net/keys/new-rsa-key4/f78fe1f34b064934bac86cc8c66a75c3: Key Type: RSA
Key ID: https://quickstart-kv.vault.azure.net/keys/new-ec-key2/10e2cec51d1749c0a26aab784808cfaf: Key Type: EC
List all vault keys:
https://quickstart-kv.vault.azure.net/keys/new-ec-key
https://quickstart-kv.vault.azure.net/keys/new-ec-key1
https://quickstart-kv.vault.azure.net/keys/new-ec-key2
https://quickstart-kv.vault.azure.net/keys/new-rsa-key4
Enabled set to: false
Successfully deleted key https://quickstart-kv.vault.azure.net/keys/new-rsa-key4/f78fe1f34b064934bac86cc8c66a75c3

Note

A saída é apenas para fins informativos. Seus valores retornados podem variar com base em sua assinatura do Azure e no Azure Key Vault.

Exemplos de código

Para obter mais exemplos, consulte a documentação do módulo.

Limpar os recursos

Execute o seguinte comando para excluir o grupo de recursos e todos os recursos restantes:

az group delete --resource-group quickstart-rg

Próximas etapas