Todos os produtos
Search
Central de documentação

Key Management Service:Código de exemplo para assinatura e verificação

Última atualização: Sep 15, 2026

Após inicializar o cliente SDK da instância do KMS, use-o para chamar as APIs Sign e Verify para assinar e verificar dados. Este tópico fornece exemplos de código para essas operações.

Exemplo completo

package main

import (
	"fmt"
	"github.com/alibabacloud-go/tea/tea"
	dedicatedkmsopenapi "github.com/aliyun/alibabacloud-dkms-gcs-go-sdk/openapi"
	dedicatedkmsopenapiutil "github.com/aliyun/alibabacloud-dkms-gcs-go-sdk/openapi-util"
	dedicatedkmssdk "github.com/aliyun/alibabacloud-dkms-gcs-go-sdk/sdk"
	"io/ioutil"
)

// The signature context may be stored.
type SignatureContext struct {
	KeyId     string
	Signature []byte
	// Use default algorithm value,if the value is not set.
	Algorithm   string
	MessageType string
}

func main() {
	// ID or alias of the KMS instance signature key.
	keyId := "<KEY_ID>"
	// Data digest or preprocessed data to be signed
	//digest := sha256.Sum256([]byte("message"))
	message := "<MESSAGE>"
	// Type of data to be signed, RAW - raw data to be signed, DIGEST - digest of the data to be signed
	//messageType := "DIGEST"
	messageType := "RAW"

	// Create DKMS Client object.
	client := getDkmsClientByClientKeyContent()
	//client := getDkmsClientByClientKeyFile()

	signatureCtx := signSample(client, keyId, []byte(message), messageType)
	verifyResult := verifySample(client, []byte(message), signatureCtx)
	fmt.Println(verifyResult)
}

// Signing example.
func signSample(client *dedicatedkmssdk.Client, keyId string, message []byte, messageType string) *SignatureContext {
	signRequest := &dedicatedkmssdk.SignRequest{
		KeyId:       tea.String(keyId),
		Message:     message,
		MessageType: tea.String(messageType),
	}
	// 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),
	//}
	// Call the signing API for signing.
	signResponse, err := client.SignWithOptions(signRequest, runtimeOptions)
	if err != nil {
		panic(err)
	}

	// Key ID.
	_keyId := tea.StringValue(signResponse.KeyId)
	// Signature value.
	_signature := signResponse.Signature
	// Message type.
	_messageType := tea.StringValue(signResponse.MessageType)
	// Signature algorithm.
	_algorithm := tea.StringValue(signResponse.Algorithm)

	fmt.Println("KeyId:", _keyId)
	fmt.Println("Signature:", _signature)
	fmt.Println("MessageType:", _messageType)
	fmt.Println("RequestId:", tea.StringValue(signResponse.RequestId))

	return &SignatureContext{
		KeyId:       _keyId,
		Signature:   _signature,
		MessageType: messageType,
		Algorithm:   _algorithm,
	}
}

// Signature verification example.
func verifySample(client *dedicatedkmssdk.Client, message []byte, ctx *SignatureContext) (_value bool) {
	verifyRequest := &dedicatedkmssdk.VerifyRequest{
		KeyId:       tea.String(ctx.KeyId),
		Message:     message,
		MessageType: tea.String(ctx.MessageType),
		Signature:   ctx.Signature,
		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),
	//}
	// Call the signature verification API for signature verification.
	verifyResponse, err := client.VerifyWithOptions(verifyRequest, runtimeOptions)
	if err != nil {
		panic(err)
	}

	// Signature verification result.
	_value = tea.BoolValue(verifyResponse.Value)
	// Message type.
	_messageType := verifyResponse.MessageType

	fmt.Println("KeyId:", tea.StringValue(verifyResponse.KeyId))
	fmt.Println("Value:", _value)
	fmt.Println("MessageType:", tea.StringValue(_messageType))
	fmt.Println("RequestId:", tea.StringValue(verifyResponse.RequestId))

	return tea.BoolValue(verifyResponse.Value)
}

// Create the SDK client object for the KMS instance using the ClientKey content.
func getDkmsClientByClientKeyContent() *dedicatedkmssdk.Client {
	// Create the SDK client configuration for the KMS instance.
	config := &dedicatedkmsopenapi.Config{
	        // Set the connection protocol to "https". The KMS instance service only allows access through the HTTPS protocol.
		Protocol: tea.String("https"),
		// Replace with the content of the ClientKey file.
		ClientKeyContent: tea.String("<CLIENT_KEY_CONTENT>"),
		// Replace with the encryption password entered when creating the ClientKey.
		Password: tea.String("<CLIENT_KEY_PASSWORD>"),
		// Set the endpoint to <KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com.
		Endpoint: tea.String("<ENDPOINT>"),
	}
	// Create the SDK client object for the KMS instance.
	client, err := dedicatedkmssdk.NewClient(config)
	if err != nil {
		// Handle exceptions
		panic(err)
	}
	return client
}

// Create the SDK client object for the KMS instance using the ClientKey file path.
func getDkmsClientByClientKeyFile() *dedicatedkmssdk.Client {
	// Create the DKMS Client configuration.
	config := &dedicatedkmsopenapi.Config{
		// Set the connection protocol to "https". The KMS instance service only allows access through the HTTPS protocol.
		Protocol: tea.String("https"),
		// Replace with the path of the ClientKey file.
		ClientKeyFile: tea.String("<CLIENT_KEY_FILE>"),
		// Replace with the encryption password entered when creating the ClientKey.
		Password: tea.String("<CLIENT_KEY_PASSWORD>"),
                 // Set the endpoint to <KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com.
		Endpoint: tea.String("<ENDPOINT>"),
	}
	// Create the SDK client object for the KMS instance.
	client, err := dedicatedkmssdk.NewClient(config)
	if err != nil {
		// Handle exceptions.
		panic(err)
	}
	return client
}

Detalhamento do exemplo

Initialize client

Crie um objeto de cliente SDK da instância do KMS usando o conteúdo da ClientKey ou o caminho do arquivo da ClientKey.

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"
)

// getDkmsClientByClientKeyFile creates a KMS instance SDK client using
// the ClientKey file path.
func getDkmsClientByClientKeyFile() *dedicatedkmssdk.Client {
    config := &dedicatedkmsopenapi.Config{
        // KMS instance service only allows HTTPS.
        Protocol: tea.String("https"),
        // Path to the ClientKey file (clientKey_****.json).
        ClientKeyFile: tea.String("<CLIENT_KEY_FILE>"),
        // Password for the ClientKey (from clientKey_****_Password.txt).
        Password: tea.String("<CLIENT_KEY_PASSWORD>"),
        // Endpoint format: <KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com
        Endpoint: tea.String("<ENDPOINT>"),
    }
    client, err := dedicatedkmssdk.NewClient(config)
    if err != nil {
        panic(err)
    }
    return client
}

Chame a API Sign para assinar digitalmente com uma chave assimétrica

// Signing example
func signSample(client *dedicatedkmssdk.Client, keyId string, message []byte, messageType string) *SignatureContext {
	signRequest := &dedicatedkmssdk.SignRequest{
		KeyId:       tea.String(keyId),
		Message:     message,
		MessageType: tea.String(messageType),
	}
	// 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),
	//}
	// Call the signing API for signing.
	signResponse, err := client.SignWithOptions(signRequest, runtimeOptions)
	if err != nil {
		panic(err)
	}

	// Key ID.
	_keyId := tea.StringValue(signResponse.KeyId)
	// Signature value.
	_signature := signResponse.Signature
	// Message type.
	_messageType := tea.StringValue(signResponse.MessageType)
	// Signature algorithm.
	_algorithm := tea.StringValue(signResponse.Algorithm)

	fmt.Println("KeyId:", _keyId)
	fmt.Println("Signature:", _signature)
	fmt.Println("MessageType:", _messageType)
	fmt.Println("RequestId:", tea.StringValue(signResponse.RequestId))

	return &SignatureContext{
		KeyId:       _keyId,
		Signature:   _signature,
		MessageType: messageType,
		Algorithm:   _algorithm,
	}
}

Chame a API Verify para verificar a assinatura digital com uma chave assimétrica

// Signature verification example.
func verifySample(client *dedicatedkmssdk.Client, message []byte, ctx *SignatureContext) (_value bool) {
	verifyRequest := &dedicatedkmssdk.VerifyRequest{
		KeyId:       tea.String(ctx.KeyId),
		Message:     message,
		MessageType: tea.String(ctx.MessageType),
		Signature:   ctx.Signature,
		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),
	//}
	// Call the signature verification API for signature verification.
	verifyResponse, err := client.VerifyWithOptions(verifyRequest, runtimeOptions)
	if err != nil {
		panic(err)
	}

	// Signature verification result.
	_value = tea.BoolValue(verifyResponse.Value)
	// Message type
	_messageType := verifyResponse.MessageType

	fmt.Println("KeyId:", tea.StringValue(verifyResponse.KeyId))
	fmt.Println("Value:", _value)
	fmt.Println("MessageType:", tea.StringValue(_messageType))
	fmt.Println("RequestId:", tea.StringValue(verifyResponse.RequestId))

	return tea.BoolValue(verifyResponse.Value)
}