Key management quickstart

更新时间:
复制 MD 格式

You can use Key Management Service (KMS) to create keys for encrypting and decrypting business data. This topic describes how to create and use these keys.

Overview

KMS provides three key management types—default key, software key, and hardware key—to meet different business scenarios and security and compliance requirements. For more information, see Overview of Key Management Service and key management types and key specifications.

  • The default key is provided by KMS free of charge. You can use it for server-side encryption in cloud services, for example, when integrated with ECS. The default key supports only symmetric encryption and does not support client-side data encryption.

  • Similar to a default key, a software key provides server-side encryption for cloud services. You can also use a software key to build application-layer cryptographic solutions using APIs for client-side data encryption, decryption, digital signature generation, and verification. A software key can be a symmetric key or an asymmetric key and supports key rotation (automatic key updates) to reduce the risk of key leakage.

  • Similar to a software key, a hardware key provides server-side encryption for cloud services and lets you build application-layer cryptographic solutions. It provides APIs for client-side data encryption and decryption, digital signature generation and verification, and supports both symmetric keys and asymmetric keys. Compared with a software key, a hardware key supports more key specifications and stores keys in a hardware security module to meet compliance requirements such as China's Cryptography Law and FIPS. However, a hardware key does not support key rotation.

Encrypt data for cloud services

You can use key management for server-side encryption in cloud services like ECS to avoid the security risks of transmitting data in plaintext. The following key types support this feature: default key, software key, and hardware key

Example

This example shows how to integrate ECS with a KMS default master key. For more information about how to integrate cloud services with KMS, see Overview of KMS integration with cloud services and Cloud services 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 Default Keys, and then click Enable in the Actions column for the master key. Name the master key alias/main.

Note

A default key can be used only for server-side encryption in cloud services, not for client-side data encryption. If you require client-side data encryption, create an instance and purchase a customer master key (software) or customer master key (hardware).

Step 2: Integrate ECS with the default KMS key

When you purchase an ECS instance, on the purchase page, select the key alias alias/main to encrypt server-side data.

In the System Disk section of the Storage settings, select the Encrypt check box, and then select the desired key from the Encryption Key drop-down list.

Step 3: Encrypt data in ECS

When data is written to or read from the encrypted disk of the ECS instance, ECS automatically calls KMS APIs to encrypt and decrypt the data. No manual intervention is required. Cloud services typically use envelope encryption to encrypt data. For more information, see Use a KMS key for envelope encryption.

Build application-layer cryptographic solutions

To build application-layer cryptographic solutions, you can use the APIs provided by KMS for client-side data encryption and decryption, and for digital signature generation and verification. The following key types support this feature: software key and hardware key.

Prerequisites

You have purchased and enabled a KMS instance that supports either software keys or hardware keys. For more information, see Purchase and enable a KMS instance.

Example

This example shows how to use a software key to Encrypt and Decrypt application-layer data. For more information about other operations, see Use a KMS key 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, click Create Key, and follow the prompts to complete the configuration.

    • For KMS Instance, select the KMS software key management instance that you purchased.

    • For Key Type, select Symmetric Encryption.

    • For Key specification, select Aliyun_AES_256. Set Key usage to ENCRYPT/DECRYPT. Enter a key alias with the prefix alias/. Add tag key-value pairs as needed. Enable automatic key rotation and set a rotation period, such as 7 days. Each rotation consumes one key from your quota.

Step 2: Upgrade the KMS instance image

This example uses a dedicated KMS gateway to call OpenAPI for cryptographic operations. This requires an image version of 3.0.0 or later.

Note

If the image version of your KMS instance is 3.0.0 or later, skip this step.

You can view the image version in the instance details on the Upgrade page. If the image version is earlier than 3.0.0, click Upgrade to upgrade the image version of the KMS instance. For more information, see Upgrade the image version of a KMS instance.

Step 3: Install dependencies

  1. Prepare the environment

    Requirements

    Java 8 or later is downloaded and installed.

    Verify the version

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

  2. Install the SDK

    Add a Maven dependency to your project to automatically download the SDK from the Maven repository. Use Alibaba Cloud SDK for Java V2.0.

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>kms20160120</artifactId>
      <version>1.3.1</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

Alibaba Cloud SDKs support multiple authentication methods based on RAM. This topic uses the AccessKey pair of a RAM user as an example. For more information about authentication methods, see Manage access credentials.

  1. Create an AccessKey pair for a RAM user in the RAM console. For more information, see Create an AccessKey pair.

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

  2. Grant appropriate permissions to the RAM user.

    For example, if you want the RAM user to perform only cryptographic operations, you can grant the user the AliyunKMSCryptoUserAccess system policy. For more information, see Manage RAM user permissions. In the left-side navigation pane of the RAM console, choose Identities > Users. On the page that appears, find the desired RAM user and click Add Permissions in the Actions column.

    Note

    KMS provides two ways to grant permissions:

    • As shown in the preceding example, this method controls access by associating permissions with an identity. For more information, see Control access by using RAM.

    • Resource-based policies: This type of policy includes key policies and credential policies. These policies are directly associated with resources and define access rules for the resources. For more information, see Key policies and Credential policies.

Step 5: Obtain the KMS instance CA certificate

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

In the Basic Information section, click Download to the right of Instance CA certificate.

Step 6: Obtain the instance VPC address

On the instance details page, obtain the VPC address of the instance.

In the Basic Information section, find and copy the instance VPC address.

Step 7: Make client calls

  1. Initialize the Alibaba Cloud SDK.

    Important

    Use Alibaba Cloud SDK for Java V2.0. Set the Endpoint parameter to the instance VPC address and configure the instance CA certificate.

        public static com.aliyun.kms20160120.Client createClient() throws Exception {
            // Leaking the source code of your project may cause the leak of your AccessKey pair and threaten the security of all resources in your account. The following code is for reference only.
            // We recommend that you use a more secure method, such as by using STS, for authentication. For more information, see https://help.aliyun.com/document_detail/378657.html.
            com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                    // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in your runtime environment.
                    .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                    // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in your runtime environment.
                    .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            // Set Endpoint to the VPC address of the instance. Example: kst-hzz65f176a0ogplgq****.cryptoservice.kms.aliyuncs.com.
            config.endpoint = "<your-instance-vpc-address>";
            // Specify the content of the CA certificate of the instance.
            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 {
            // Leaking the source code of your project may cause the leak of your AccessKey pair and threaten the security of all resources in your account. The following code is for reference only.
            // We recommend that you use a more secure method, such as by using STS, for authentication. For more information, see https://help.aliyun.com/document_detail/378657.html.
            com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                    // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in your runtime environment.
                    .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                    // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in your runtime environment.
                    .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            // Set Endpoint to the VPC address of the instance. Example: kst-hzz65f176a0ogplgq****.cryptoservice.kms.aliyuncs.com.
            config.endpoint = "<your-instance-vpc-address>";
            // Specify the content of the CA certificate of the instance.
            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 {
                // If you copy and run this code, you must add your own code to print the API response.
                client.encryptWithOptions(encryptRequest, runtime);
            } catch (TeaException error) {
                // The following code is for demonstration only. Handle exceptions with care. Do not ignore exceptions in your project.
                // error message
                System.out.println(error.getMessage());
                // Troubleshooting recommendation.
                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. Handle exceptions with care. Do not ignore exceptions in your project.
                // error message
                System.out.println(error.getMessage());
                // Troubleshooting recommendation.
                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 {
            // Leaking the source code of your project may cause the leak of your AccessKey pair and threaten the security of all resources in your account. The following code is for reference only.
            // We recommend that you use a more secure method, such as by using STS, for authentication. For more information, see https://help.aliyun.com/document_detail/378657.html.
            com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                    // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in your runtime environment.
                    .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                    // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in your runtime environment.
                    .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            // Set Endpoint to the VPC address of the instance. Example: kst-hzz65f176a0ogplgq****.cryptoservice.kms.aliyuncs.com.
            config.endpoint = "<your-instance-vpc-address>";
            // Specify the content of the CA certificate of the instance.
            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 {
                // If you copy and run this code, you must add your own code to print the API response.
                client.decryptWithOptions(decryptRequest, runtime);
            } catch (TeaException error) {
                // The following code is for demonstration only. Handle exceptions with care. Do not ignore exceptions in your project.
                // error message
                System.out.println(error.getMessage());
                // Troubleshooting recommendation.
                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. Handle exceptions with care. Do not ignore exceptions in your project.
                // error message
                System.out.println(error.getMessage());
                // Troubleshooting recommendation.
                System.out.println(error.getData().get("Recommend"));
                com.aliyun.teautil.Common.assertAsString(error.message);
            }        
        }
    }

Related topics