All Products
Search
Document Center

Key Management Service:KMS Instance SDK for Go

最終更新日:Oct 23, 2023

Key Management Service (KMS) Instance SDK for Go allows you to call KMS Instance API operations in a convenient manner. You can use KMS Instance SDK for Go to encrypt and decrypt data, sign data, verify signatures, and retrieve secret values. This topic describes how to install KMS Instance SDK for Go and call operations to encrypt and decrypt data, sign data, verify signatures, and retrieve secret values.

Background information

KMS provides various types of SDKs. Before you use an SDK, you must get familiar with the scenarios of the SDK. For more information, see SDK user guide.

You can view the source code and sample code of the SDK in the open source code repository for Go. For more information, see Open source code repository. You are welcome to share your comments or provide your sample code.

Prerequisites

  • A KMS instance is purchased and enabled. For more information, see Purchase and enable a KMS instance.

  • A key and a secret are created. For more information, see Software-protected keys, Hardware-protected keys, and Create a secret.

    Note

    If your business does not require a secret, you do not need to create a secret.

  • An application access point (AAP) is created, the client key that is bound to the AAP is saved, and a certificate authority (CA) certificate is obtained for the KMS instance. For more information, see Access a KMS instance by using an AAP.

  • Make sure that the application runtime environment and the VPC of the KMS instance can communicate with each other.

    Business scenario

    Description

    The application runtime environment and the KMS instance reside in the same region and belong to the same VPC.

    By default, the application runtime environment and the KMS instance can communicate with each other. No manual configuration is required.

    The application runtime environment and the KMS instance reside in the same region but belong to different VPCs.

    You must configure multiple VPCs to access the same KMS instance. For more information, see Access a KMS instance from multiple VPCs in the same region.

Install KMS Instance SDK for Go

  • Method 1: Use the go.mod file to manage dependencies.

    Add the following content to the go.mod file to install the dependency package.

    require (
        github.com/aliyun/alibabacloud-dkms-gcs-go-sdk SDK version
    )
    Note

    We recommend that you install the latest version of the SDK. For more information, see Open source code repository.

  • Method 2: Run the go get command to obtain the remote code package.

    $ go get -u github.com/aliyun/alibabacloud-dkms-gcs-go-sdk

Initialize KMS Instance SDK for Go

To use KMS Instance SDK for Go to initiate a request, you must create a client.

  1. Create a client.

    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"
    )
    
    config := &dedicatedkmsopenapi.Config{
      // The connection protocol. Set the value to https. KMS supports connections only over HTTPS. 
      Protocol: tea.String("https"),  
      // The endpoint of your KMS instance. Set the value in the following format: <ID of your KMS instance >.cryptoservice.kms.aliyuncs.com. 
        Endpoint: tea.String("<your KMS Instance Id>.cryptoservice.kms.aliyuncs.com"),
      // The client key. 
        ClientKeyContent: tea.String("<your client key content>"),
      // The password of the client key file. 
        Password: tea.String("<your client key password>"),
    }
    
    client, err := dedicatedkmssdk.NewClient(config)
  2. Configure the certificate authority (CA) certificate of your KMS instance by using RuntimeOptions.

    Important

    To ensure communication security in the production environment, we recommend that you verify the validity of SSL/TLS certificates. If you do not need to verify the validity of SSL/TLS certificates in specific scenarios such as testing scenarios, set the ignoreSSL field of RuntimeOptions to true.

    Set the verify field of RuntimeOptions to the path of the CA certificate of the KMS instance. The following code provides an example:

    import (
        dedicatedkmsopenapiutil "github.com/aliyun/alibabacloud-dkms-gcs-go-sdk/openapi-util"
        "github.com/alibabacloud-go/tea/tea"
        "io/ioutil"
    )
    
    // Verify the certificate.
    ca, err := ioutil.ReadFile("path/to/caCert.pem")
    if err != nil {
        panic(err)
    }
    runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
        Verify: tea.String(string(ca)),
    }

Use the client to call an operation

After you create a client, you can use the client to call KMS Instance API operations. The following sample codes provide examples on how to call operations in different scenarios. For more information about KMS Instance API, see List of operations by function.

  • Call the Encrypt operation to encrypt data by using a symmetric key

    For more information about the sample code, see Source code.

    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"
    )
    
    // The data that you want to encrypt. 
    plaintext := []byte("encrypt plaintext")
    // The ID or alias of the key. 
    keyId := "<your cipher key id>"
    
    encryptRequest := &dedicatedkmssdk.EncryptRequest{
        KeyId:     tea.String(keyId),
        Plaintext: plaintext,
    }
    
    encryptResponse, err := client.EncryptWithOptions(encryptRequest, runtimeOptions)
    if err != nil {
        panic(err)
    }
    
    // The ciphertext. 
    cipher := encryptResponse.CiphertextBlob
    // The initial vector of Cipher, which is used to decrypt data. 
    iv := encryptResponse.Iv
    // The request ID. 
    requestId := tea.StringValue(encryptResponse.RequestId)
  • Call the Decrypt operation to decrypt data by using a symmetric key

    For more information about the sample code, see Source code.

    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"
    )
    
    // The ID or alias of the key. 
    keyId := "<your cipher key id>"
    // The ciphertext that you want to decrypt. 
    ciphertextBlob := []byte("<your cipher data to decrypt>")
    // The initial vector of Cipher. The initial vector must be the same as the initial vector that is specified for encryption. 
    iv := []byte("<IV value>")
    
    decryptRequest := &dedicatedkmssdk.DecryptRequest{
        KeyId:          tea.String(keyId),
        CiphertextBlob: ciphertextBlob,
        Iv:             iv,
    }
    
    decryptResponse, err := client.DecryptWithOptions(decryptRequest, runtimeOptions)
    if err != nil {
        panic(err)
    }
    
    // The plaintext. 
    plaintext := decryptResponse.Plaintext
    // The request ID. 
    requestId := tea.StringValue(decryptResponse.RequestId)
  • Call the Sign operation to sign data by using an asymmetric key

    For more information about the sample code, see Source code.

    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"
    )
    
    // The ID or alias of the key. 
    signerKeyId := "<the signer key id>"
    // The data to sign. 
    message := []byte("<the data to sign>")
    
    signRequest := &dedicatedkmssdk.SignRequest{
        KeyId:       tea.String(signerKeyId),
        Message:     message,
        MessageType: tea.String(messageType),
    }
    
    signResponse, err := client.SignWithOptions(signRequest, runtimeOptions)
    if err != nil {
        panic(err)
    }
    
    // The signature value. 
    signature := signResponse.Signature
    // The request ID. 
    requestId := tea.StringValue(signResponse.RequestId)
  • Call the Verify operation to verify a signature by using an asymmetric key

    For more information about the sample code, see Source code.

    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"
    )
    
    // The ID or alias of the key. 
    signerKeyId := "<the signer key id>"
    // The data for which you want to verify the signature. 
    message := []byte("<the data to sign>")
    
    // The signature value. 
    signature := []byte("<the signature>")
    
    verifyRequest := &dedicatedkmssdk.VerifyRequest{
        KeyId:       tea.String(signerKeyId),
        Message:     message,
        MessageType: tea.String(messageType),
        Signature:   signature,
    }
    
    verifyResponse, err := client.VerifyWithOptions(verifyRequest, runtimeOptions)
    if err != nil {
        panic(err)
    }
    
    // The verification result. 
    value := tea.BoolValue(verifyResponse.Value)
    // The request ID. 
    requestId := tea.StringValue(verifyResponse.RequestId)
  • Call the GetSecretValue operation to retrieve a secret value

    For more information about the sample code, see Source code.

    Important

    This operation is supported only for KMS Instance SDK for Go V0.2.1 or later.

    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"
    )
    
    // The secret name. 
    secretName := "<your-dkms-secret-name>"
    
    getSecretValueRequest := &dedicatedkmssdk.GetSecretValueRequest{
        SecretName: tea.String(secretName),
    }
    
    // The call process. 
    response, err := client.GetSecretValueWithOptions(getSecretValueRequest, runtimeOptions)
    if err != nil {
        panic(err)
    }
    
    // The secret value. 
    _secretData := tea.StringValue(response.SecretData)
    // The request ID. 
    _RequestId := tea.StringValue(response.RequestId)