Get started with key management

更新时间:
复制 MD 格式

Use Key Management Service (KMS) to create keys and encrypt your business data.

Overview

KMS provides three key types — default keys, software keys, and hardware keys — for different business, security, and compliance requirements. Overview of KMS. Key types and specifications.

  • Default keys are free and enable server-side encryption for cloud products such as ECS. Default keys support only symmetric encryption and cannot be used for client-side encryption.

  • Software keys provide server-side encryption and support client-side data encryption and decryption and digital signature computation and verification. They support symmetric and asymmetric key types with automatic key rotation to reduce the risk of key leakage.

  • Hardware keys offer the same features as software keys — server-side encryption, client-side encryption and decryption APIs, and digital signature computation and verification — with symmetric and asymmetric key types. Hardware keys support more key specifications and store keys in an HSM for compliance with standards such as China's Cryptography Law and FIPS. They do not support automatic key rotation.

Encrypt data for cloud products

KMS enables server-side encryption for cloud products such as ECS. Supported key types: default key, software key, and hardware key.

Example

The following example integrates ECS with a KMS default key. For other cloud product integrations, see Overview of KMS integration with other cloud products and Cloud products that can be integrated with KMS.

Step 1: Enable a default master key

  1. Log on to the Key Management Service console. In the top navigation bar, select a region. In the left-side navigation pane, choose Resource > Keys.

  2. On the Key Management page, click the Default Keys tab. In the Actions column of the master key, click Enable and set the alias to alias/main.image

Note

The default key master key supports only server-side encryption by cloud products. For client-side encryption, purchase a software key or hardware key instance.

Step 2: Integrate ECS with the default key

When purchasing an ECS instance, select the master key alias/main on the purchase page to enable server-side encryption.

image

Step 3: Encrypt data transmission in ECS

ECS automatically calls KMS APIs to encrypt and decrypt data within the ECS instance. Cloud products typically use envelope encryption. Use KMS keys for envelope encryption.

Build application-layer cryptographic solutions

Use KMS APIs for client-side encryption, decryption, and digital signature computation and verification. Supported key types: software key and hardware key.

Prerequisites

A KMS software or hardware key management instance is purchased and enabled. Purchase and enable a KMS instance.

Example

The following example uses a software key instance to call Encrypt and Decrypt on application data. Use KMS keys to encrypt and decrypt data online.

Step 1: Create a software key

  1. Log on to the Key Management Service console. In the top navigation bar, select a region. In the left-side navigation pane, choose Resource > Keys.

  2. Go to the Customer Master Keys tab and click Create Key. Follow the prompts to complete the configuration.

    • KMS Instance: select your software key management instance.

    • For Key Type, select Symmetric Key.

    • For Key Spec, select Aliyun_AES_256.image

Step 2: Upgrade the KMS instance image version

This example uses dedicated KMS for cryptographic operations, which requires image version 3.0.0 or later.

Note

Skip this step if your KMS instance image version is 3.0.0 or later.

On the Instances page, check the image version in the instance details. If it is earlier than 3.0.0, click Upgrade. Upgrade the image version of a KMS instance.image

Step 3: Install dependencies

  1. Prepare your environment

    Requirements

    Java 8 or later must be installed.

    Verify the version

    Open a terminal and run the java -version command to check your Java (JDK) version.

  2. Install the SDK

    Add the following Maven dependency. Maven automatically downloads the required SDK files from its repository. Use Alibaba Cloud SDK V2.0.

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>kms20160120</artifactId>
      <version>1.2.3</version>
    </dependency>
    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>tea</artifactId>
      <version>1.3.2</version>
    </dependency>
    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>tea-openapi</artifactId>
      <version>0.3.6</version>
    </dependency>

Step 4: Create API credentials

This example authenticates with a RAM user AccessKey pair via Resource Access Management (RAM). For other methods, see Manage access credentials.

  1. Create an AccessKey pair for a RAM user in the RAM console. Create an AccessKey.

    If you already have an AccessKey pair, skip this step.image

  2. Grant appropriate permissions to the RAM user.

    For example, to restrict the RAM user to cryptographic operations only, grant the AliyunKMSCryptoUserAccess system policy. Manage permissions for a RAM user.image

    Note

    KMS supports two permission models:

Step 5: Obtain the KMS instance CA certificate

On the instance details page, obtain the instance CA certificate.

image

Step 6: Obtain the instance VPC endpoint

On the instance details page, obtain the instance VPC endpoint.

image

Step 7: Make client-side API calls

  1. Initialize the Alibaba Cloud SDK.

    Important

    Use Alibaba Cloud SDK V2.0. Set the instance VPC endpoint as the endpoint and configure the instance CA certificate.

        public static com.aliyun.kms20160120.Client createClient() throws Exception {
            // Hard-coding access credentials in your code can lead to security risks. This code is for demonstration only.
            // For improved security, we recommend using STS. For more authentication methods, see https://help.aliyun.com/document_detail/378657.html.
            com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                    // Required. Make sure the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
                    .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                    // Required. Make sure the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
                    .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            // For the Endpoint, enter the VPC endpoint of your instance. Example: kst-hzz65f176a0ogplgq****.cryptoservice.kms.aliyuncs.com
            config.endpoint = "<your_instance_vpc_endpoint>";
            // Enter the content of your instance CA certificate.
            config.ca = "<your_instance_ca_certificate>";
            return new com.aliyun.kms20160120.Client(config);
        }
  2. Call the Encrypt operation to encrypt data.

    package com.aliyun.sample;
    
    import com.aliyun.tea.*;
    
    public class Sample {
      public static com.aliyun.kms20160120.Client createClient() throws Exception {
            // Hard-coding access credentials in your code can lead to security risks. This code is for demonstration only.
            // For improved security, we recommend using STS. For more authentication methods, see https://help.aliyun.com/document_detail/378657.html.
            com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                    // Required. Make sure the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
                    .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                    // Required. Make sure the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
                    .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            // For the Endpoint, enter the VPC endpoint of your instance. Example: kst-hzz65f176a0ogplgq****.cryptoservice.kms.aliyuncs.com
            config.endpoint = "<your_instance_vpc_endpoint>";
            // Enter the content of your instance CA certificate.
            config.ca = "<your_instance_ca_certificate>";
            return new com.aliyun.kms20160120.Client(config);
        }
       
         public static void main(String[] args_) throws Exception {
            java.util.List<String> args = java.util.Arrays.asList(args_);
            com.aliyun.kms20160120.Client client = Sample.createClient();
            com.aliyun.kms20160120.models.EncryptRequest encryptRequest = new com.aliyun.kms20160120.models.EncryptRequest()
                    .setKeyId("<your_key_id>")
                    .setPlaintext("<your_plaintext>");
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            try {
                // Add your own code to print the API response.
                client.encryptWithOptions(encryptRequest, runtime);
            } catch (TeaException error) {
                // The following code is for demonstration only. We recommend that you handle exceptions with care and do not ignore them in your projects.
                // Error message
                System.out.println(error.getMessage());
                // Troubleshooting URL
                System.out.println(error.getData().get("Recommend"));
                com.aliyun.teautil.Common.assertAsString(error.message);
            } catch (Exception _error) {
                TeaException error = new TeaException(_error.getMessage(), _error);
                // The following code is for demonstration only. We recommend that you handle exceptions with care and do not ignore them in your projects.
                // Error message
                System.out.println(error.getMessage());
                // Troubleshooting URL
                System.out.println(error.getData().get("Recommend"));
                com.aliyun.teautil.Common.assertAsString(error.message);
            }        
        }
    }
  3. Call the Decrypt operation to decrypt data.

    package com.aliyun.sample;
    
    import com.aliyun.tea.*;
    
    public class Sample {
    
        public static com.aliyun.kms20160120.Client createClient() throws Exception {
            // Hard-coding access credentials in your code can lead to security risks. This code is for demonstration only.
            // For improved security, we recommend using STS. For more authentication methods, see https://help.aliyun.com/document_detail/378657.html.
            com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                    // Required. Make sure the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
                    .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                    // Required. Make sure the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
                    .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            // For the Endpoint, enter the VPC endpoint of your instance. Example: kst-hzz65f176a0ogplgq****.cryptoservice.kms.aliyuncs.com
            config.endpoint = "<your_instance_vpc_endpoint>";
            // Enter the content of your instance CA certificate.
            config.ca = "<your_instance_ca_certificate>";
            return new com.aliyun.kms20160120.Client(config);
        }
    
        public static void main(String[] args_) throws Exception {
            java.util.List<String> args = java.util.Arrays.asList(args_);
            com.aliyun.kms20160120.Client client = Sample.createClient();
            com.aliyun.kms20160120.models.DecryptRequest decryptRequest = new com.aliyun.kms20160120.models.DecryptRequest()
                    .setCiphertextBlob("<your_ciphertext_blob>");
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            try {
                // Add your own code to print the API response.
                client.decryptWithOptions(decryptRequest, runtime);
            } catch (TeaException error) {
                // The following code is for demonstration only. We recommend that you handle exceptions with care and do not ignore them in your projects.
                // Error message
                System.out.println(error.getMessage());
                // Troubleshooting URL
                System.out.println(error.getData().get("Recommend"));
                com.aliyun.teautil.Common.assertAsString(error.message);
            } catch (Exception _error) {
                TeaException error = new TeaException(_error.getMessage(), _error);
                // The following code is for demonstration only. We recommend that you handle exceptions with care and do not ignore them in your projects.
                // Error message
                System.out.println(error.getMessage());
                // Troubleshooting URL
                System.out.println(error.getData().get("Recommend"));
                com.aliyun.teautil.Common.assertAsString(error.message);
            }        
        }
    }

Related documentation