All Products
Search
Document Center

Key Management Service:Getting started with secrets manager

Last Updated:Dec 27, 2024

Use KMS to create and manage secrets, allowing for the seamless integration of sensitive data within your applications. This topic outlines the process of creating secrets and incorporating them into your applications.

Background information

KMS offers lifecycle management services for secrets, including creation, updating, and deletion. Applications can retrieve secrets using an SDK, which helps prevent the exposure of sensitive data due to hardcoded secrets within the applications.

KMS supports the management of various secrets, including generic secrets, RAM secrets, database secrets, and ECS secrets. For more information about secrets, see Overview of Secrets Management.

Precautions

KMS encrypts a secret using a specified key. Both the key and the secret must be part of the same KMS instance, and the key must be a symmetric key. For more information about symmetric keys in KMS, see Key Management Types.

Prerequisites

  • A KMS instance has been purchased and activated. For more information, see Purchase and Enable a KMS Instance.

  • A symmetric key for encrypting secrets has been created within the KMS instance. For more information, see Create a Key.

Step 1: Create a secret

When creating a secret, you have the option to enable secret rotation. KMS will periodically update the secret to maintain its security.

  1. Log on to the KMS console. In the top navigation bar, select a region. In the left-side navigation pane, choose Resource > Secrets.

  2. Navigate to the Secrets page, select the tab for the type of secret you want to create, choose the Instance ID, and then click Create Secret. Complete the configurations and click Confirm.

    Generic secrets

    Note

    Generic secrets do not support rotation configuration upon creation. To rotate a generic secret, refer to Manage and Use Generic Secrets.

    Configuration item

    Description

    Secret Name

    The name of the secret. The secret name is unique within the current region.

    Secret Value

    Based on the type of sensitive data that you want to manage, select Key/Value or Plain text.

    The length cannot exceed 30,720 bytes (30 KB).

    Initial Version

    The initial version number of the secret. The default value is v1. You can also customize the version number.

    CMK

    Select the key that is used to encrypt the secret.

    Important
    • Your key and secret must belong to the same KMS instance. The key must be a symmetric key. For more information about the symmetric keys supported by KMS, see Key types and specifications.

    • If you are a RAM user or a RAM role, you must have the permissions to call the GenerateDataKey operation by using a key.

    Tag

    The tag that you want to add to the secret. You can use tags to classify and manage secrets. A tag consists of a key-value pair (Key:Value), which includes a tag key (Key) and a tag value (Value).

    Note
    • A tag key or a tag value can be up to 128 characters in length and can contain letters, digits, forward slashes (/), backslashes (\), underscores (_), hyphens (-), periods (.), plus signs (+), equal sign (=), colons (:), at signs (@), and spaces.

    • A tag key cannot start with aliyun or acs:.

    • You can configure up to 20 key-value pairs for each secret.

    Description

    The description of the secret.

    Policy Settings

    The policy settings of the secret. For more information, see Overview of secret policies.

    You can use the default policy and then modify the policy based on your business requirements after you create the secret.

    RAM secrets

    Configuration item

    Description

    Select RAM User

    Select the RAM user for which you want to manage secrets. The selected RAM user must have at least one AccessKey. If no AccessKey exists, create an AccessKey first. For more information, see Create an AccessKey.

    The secret name is automatically generated based on the name of the RAM user. The secret name is unique within the current region.

    Secret Value

    Enter the AccessKey secret.

    The length cannot exceed 30,720 bytes (30 KB).

    CMK

    Select the key that is used to encrypt the secret.

    Important
    • Your key and secret must belong to the same KMS instance. The key must be a symmetric key. For more information about the symmetric keys supported by KMS, see Key types and specifications.

    • If you are a RAM user or a RAM role, you must have the permissions to call the GenerateDataKey operation by using a key.

    Tag

    The tag that you want to add to the secret. You can use tags to classify and manage secrets. A tag consists of a key-value pair (Key:Value), which includes a tag key (Key) and a tag value (Value).

    Note
    • A tag key or a tag value can be up to 128 characters in length and can contain letters, digits, forward slashes (/), backslashes (\), underscores (_), hyphens (-), periods (.), plus signs (+), equal sign (=), colons (:), at signs (@), and spaces.

    • A tag key cannot start with aliyun or acs:.

    • You can configure up to 20 key-value pairs for each secret.

    Automatic Rotation

    Specifies whether to enable automatic secret rotation.

    Days (7 Days to 365 Days)

    This parameter is required only if Enable Automatic Rotation is enabled.

    This parameter specifies the rotation cycle. After you set this parameter, KMS periodically updates the secret.

    Description

    The description of the secret.

    Policy Settings

    The policy settings of the secret. For more information, see Overview of secret policies.

    You can use the default policy and then modify the policy based on your business requirements after you create the secret.

    Database secrets (RDS)

    Only the option Create Single Secret is available.

    Configuration item

    Description

    Database Type

    Select ApsaraDB RDS Secrets.

    Secret Name

    The name of the secret. The secret name is unique within the current region.

    ApsaraDB RDS Instance

    Select an existing ApsaraDB RDS instance within your Alibaba Cloud account.

    Account Management

    • Manage Dual Accounts (recommended): This option is suitable for scenarios where databases are accessed by using programs. Two accounts that have the same permissions are managed to ensure that the connections between applications and the ApsaraDB RDS instance are not interrupted when the secret is rotated.

      • Click Create Account, configure the account name, select a database, and specify permissions.

        Note

        KMS does not immediately create accounts. KMS creates accounts after you review and confirm the secret information.

      • Click Import Existing Accounts, select a username, and configure a password.

        Note

        We recommend that you specify the same passwords as the passwords that you specified for the accounts when you created the ApsaraDB RDS instance. If an imported account and the specified password do not match, you can obtain the valid account and password after the secret is rotated for the first time.

    • Manage Single Account: This option is suitable for scenarios where privileged accounts or accounts for manual O&M are managed. The current version of the secret may be temporarily unavailable when the secret is rotated.

      • Click Create Account, configure the account name, and select the account type.

        You can select either Standard Account or Privileged Account. If you select Standard Account, you must also select a database and specify permissions.

      • Click the Import Existing Accounts tab, select a username, and configure a password.

    CMK

    Select the key that is used to encrypt the secret.

    Important
    • Your key and secret must belong to the same KMS instance. The key must be a symmetric key. For more information about the symmetric keys supported by KMS, see Key types and specifications.

    • If you are a RAM user or a RAM role, you must have the permissions to call the GenerateDataKey operation by using a key.

    Tag

    The tag that you want to add to the secret. You can use tags to classify and manage secrets. A tag consists of a key-value pair (Key:Value), which includes a tag key (Key) and a tag value (Value).

    Note
    • A tag key or a tag value can be up to 128 characters in length and can contain letters, digits, forward slashes (/), backslashes (\), underscores (_), hyphens (-), periods (.), plus signs (+), equal sign (=), colons (:), at signs (@), and spaces.

    • A tag key cannot start with aliyun or acs:.

    • You can configure up to 20 key-value pairs for each secret.

    Automatic Rotation

    Specifies whether to enable automatic secret rotation.

    Rotation Period

    This parameter is required only if Enable Automatic Rotation is enabled. The value ranges from 6 hours to 365 days.

    This parameter specifies the rotation cycle. After you set this parameter, KMS periodically updates the secret.

    Description

    The description of the secret.

    Policy Settings

    The policy settings of the secret. For more information, see Overview of secret policies.

    You can use the default policy and then modify the policy based on your business requirements after you create the secret.

    Database secret (PolarDB)

    Only the option Create Single Secret is available for PolarDB MySQL/PgSQL, supporting Create Account and Manage Dual Accounts. The options Import Existing Accounts and Manage Single Account are not supported.

    Configuration item

    Description

    Database Type

    Select PolarDB Secret.

    Secret Name

    The name of the secret. The secret name is unique within the current region.

    PolarDB Cluster

    Select an existing PolarDB instance within your Alibaba Cloud account.

    Account Management

    Manage Dual Accounts: This option is suitable for scenarios where databases are accessed by using programs. Two accounts that have the same permissions are created to ensure that the connections between applications and the PolarDB instance are not interrupted when the secret is rotated.

    Create Account: Configure the account name and permissions. Only Standard account is supported. When you create a MySQL secret, you must select a database and specify permissions.

    Note
    • KMS does not immediately create accounts. KMS creates accounts after you review and confirm the secret information.

    • The account name must be unique. If the account name already exists, the account cannot be managed in the secret.

    CMK

    Select the key that is used to encrypt the secret.

    Important
    • Your key and secret must belong to the same KMS instance. The key must be a symmetric key. For more information about the symmetric keys supported by KMS, see Key types and specifications.

    • If you are a RAM user or a RAM role, you must have the permissions to call the GenerateDataKey operation by using a key.

    Tag

    The tag that you want to add to the secret. You can use tags to classify and manage secrets. A tag consists of a key-value pair (Key:Value), which includes a tag key (Key) and a tag value (Value).

    Note
    • A tag key or a tag value can be up to 128 characters in length and can contain letters, digits, forward slashes (/), backslashes (\), underscores (_), hyphens (-), periods (.), plus signs (+), equal sign (=), colons (:), at signs (@), and spaces.

    • A tag key cannot start with aliyun or acs:.

    • You can configure up to 20 key-value pairs for each secret.

    Automatic Rotation

    Specifies whether to enable automatic secret rotation.

    Rotation Period

    This parameter is required only if Enable Automatic Rotation is enabled. The value ranges from 6 hours to 365 days.

    This parameter specifies the rotation cycle. After you set this parameter, KMS periodically updates the secret.

    Description

    The description of the secret.

    Policy Settings

    The policy settings of the secret. For more information, see Overview of secret policies.

    You can use the default policy and then modify the policy based on your business requirements after you create the secret.

    Database secrets (Redis)

    Both options Create Single Secret and Create Bulk Secrets are available. This topic demonstrates the creation of a single secret.

    Configuration item

    Description

    Database Type

    Select ApsaraDB for Redis/Tair Instance.

    Secret Name

    The name of the secret. The secret name is unique within the current region.

    ApsaraDB for Redis/Tair Instance

    Select an existing Redis instance or Tair instance within your Alibaba Cloud account.

    Account Management

    Only Manage Dual Accounts is supported.

    Secret Value

    Only newly created accounts can be managed, and only double account management is supported. Existing Redis/Tair accounts cannot be managed.

    • Account Name: You need to customize the account name of the Redis/Tair database. In this case, KMS calls the API of Redis/Tair to create two database accounts and passwords that have the same permissions. For example, if you customize the account name of the Redis database as user, two Redis database accounts user and user_clone are created.

    • Permissions: The value can be Read/Write or Read-Only. The two newly created database accounts have the same permissions.

    CMK

    Select the key that is used to encrypt the secret.

    Important
    • Your key and secret must belong to the same KMS instance. The key must be a symmetric key. For more information about the symmetric keys supported by KMS, see Key types and specifications.

    • If you are a RAM user or a RAM role, you must have the permissions to call the GenerateDataKey operation by using a key.

    Tag

    The tag that you want to add to the secret. You can use tags to classify and manage secrets. A tag consists of a key-value pair (Key:Value), which includes a tag key (Key) and a tag value (Value).

    Note
    • A tag key or a tag value can be up to 128 characters in length and can contain letters, digits, forward slashes (/), backslashes (\), underscores (_), hyphens (-), periods (.), plus signs (+), equal sign (=), colons (:), at signs (@), and spaces.

    • A tag key cannot start with aliyun or acs:.

    • You can configure up to 20 key-value pairs for each secret.

    Automatic Rotation

    Specifies whether to enable automatic secret rotation.

    Rotation Period

    This parameter is required only if Automatic Rotation is enabled. The value ranges from 6 hours to 365 days.

    This parameter specifies the rotation cycle. After you set this parameter, KMS periodically updates the secret.

    Description

    The description of the secret.

    Policy Settings

    The policy settings of the secret. For more information, see Overview of secret policies.

    You can use the default policy and then modify the policy based on your business requirements after you create the secret.

    ECS secrets

    Configuration item

    Description

    Secret Name

    The name of the secret. The secret name is unique within the current region.

    Managed Instance

    Select an existing ECS instance within your Alibaba Cloud account.

    Managed User

    Enter the name of an existing user on the ECS instance, such as root for the Linux operating system or Administrator for the Windows operating system.

    Initial Secret Value

    The length cannot exceed 30,720 bytes (30 KB).

    • Password: The password that is used to log on to the ECS instance.

    • Key pair: The SSH key pair that is used to log on to the ECS instance.

      Obtain an SSH key pair

      • An SSH key pair that is created in ECS

        • Private key: After the SSH key pair is created, the browser automatically downloads the private key file (Key pair name.pem) to the on-premises computer. For more information, see Create an SSH key pair.

        • Public key: For more information about how to view public key information, see View public key information.

      • An automatically-generated SSH key pair

        Save the private key and the public key of a key pair after the key pair is generated. This example uses the ssh-keygen command to generate and save a 3,072-bit RSA key pair.

        ssh-keygen -t RSA -b 3072 -m PEM -f ~/.ssh/sshKey_demo -N ""

        The following files are generated:

        • ~/.ssh/sshKey_demo: This file contains the private key.

        • ~/.ssh/sshKey_demo.pub: This file contains the public key.

    Note

    Enter a valid secret value. If you enter an invalid secret value, the password or SSH key pair that you retrieve from KMS cannot be used to log on to the ECS instance before the first time the ECS secret is rotated.

    CMK

    Select the key that is used to encrypt the secret.

    Important
    • Your key and secret must belong to the same KMS instance. The key must be a symmetric key. For more information about the symmetric keys supported by KMS, see Key types and specifications.

    • If you are a RAM user or a RAM role, you must have the permissions to call the GenerateDataKey operation by using a key.

    Tag

    The tag that you want to add to the secret. You can use tags to classify and manage secrets. A tag consists of a key-value pair (Key:Value), which includes a tag key (Key) and a tag value (Value).

    Note
    • A tag key or a tag value can be up to 128 characters in length and can contain letters, digits, forward slashes (/), backslashes (\), underscores (_), hyphens (-), periods (.), plus signs (+), equal sign (=), colons (:), at signs (@), and spaces.

    • A tag key cannot start with aliyun or acs:.

    • You can configure up to 20 key-value pairs for each secret.

    Automatic Rotation

    Specifies whether to enable automatic secret rotation.

    Rotation Period

    This parameter is required only if Enable Automatic Rotation is enabled. The value ranges from 1 hour to 365 days.

    This parameter specifies the rotation cycle. After you set this parameter, KMS periodically updates the secret.

    Description

    The description of the secret.

    Policy Settings

    The policy settings of the secret. For more information, see Overview of secret policies.

    You can use the default policy and then modify the policy based on your business requirements after you create the secret.

Step 2: Retrieve the secret

This topic uses the Alibaba Cloud SDK for Java as an example.

Preparations

  1. Set up your environment.

    Environment Requirements

    Ensure Java Development Kit (JDK) V8 or later is installed on your system.

    Verify the Installation

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

  2. Install the SDK.

    Add a Maven dependency to your project to automatically download the Alibaba Cloud SDK (V2.0) Java package from the Maven repository.

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>kms20160120</artifactId>
      <version>1.2.3</version>
    </dependency>
  3. Create credentials for API calls.

    Alibaba Cloud SDK supports various authentication methods based on RAM. This topic uses the AccessKey of a RAM user for illustration. For more details on authentication methods, see Manage Access Credentials.

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

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

    2. Assign the appropriate access privileges to RAM users.

      Ensure the RAM user has the necessary permissions.

      For instance, to enable a RAM user to retrieve secret values, you can assign the system permission policies AliyunKMSSecretUserAccess and AliyunKMSCryptoUserAccess to that user. For more information, see Grant permissions to a RAM user. image

      Note

      KMS offers two methods for configuring access permissions:

      • Identity-based policies: This method, as illustrated in the previous example, controls access by linking identities with their respective permissions. For more information, see Use RAM for access control.

      • Resource-based policies: These include key policies and secret policies, which are directly tied to resources to establish access rules for those specific resources. For more information, see Key policies and Secret policies.

  4. Acquire the CA certificate of the KMS instance.

    1. Log on to the KMS console. In the top navigation bar, select a region. In the left-side navigation pane, choose Resource > Instances.

    2. At the top of the action page on the right, click Instance CA Certificate.

      image

  5. Determine the VPC address of the instance.

    Record the VPC address of the instance from the product page.

    image

Retrieve the secret

  1. Initialize the Alibaba Cloud SDK.

    Important

    Use Alibaba Cloud SDK (V2.0), specifying the VPC address of the instance as the endpoint and setting the CA certificate of the instance.

        public static com.aliyun.kms20160120.Client createClient() throws Exception {
            // If the project code is leaked, the AccessKey pair may be leaked and resources in your account become insecure. The following code is for reference only.
            // We recommend that you use Security Token Service (STS) tokens, which provide higher security. For information about credential-based authentication methods, see the topic at the following URL: https://www.alibabacloud.com/help/en/sdk/developer-reference/v2-manage-access-credentials?spm=a2c63.p38356.0.0.cc196072Z9j9AY.
            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.
                    .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                    // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured.
                    .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            // Specify the VPC address of the instance as the endpoint. Example: kst-hzz65f176a0ogplgq****.cryptoservice.kms.aliyuncs.com
            config.endpoint = "<VPC address of the instance>";
            // Specify the content of the CA certificate of the instance
            config.ca = "<CA certificate of the instance>";
            return new com.aliyun.kms20160120.Client(config);
        }
  2. Invoke GetSecretValue to retrieve the secret value.

    // This file is auto-generated, don't edit it. Thanks.
    package com.aliyun.sample;
    
    import com.aliyun.tea.*;
    
    public class Sample {
    
      public static com.aliyun.kms20160120.Client createClient() throws Exception {
            // If the project code is leaked, the AccessKey pair may be leaked and resources in your account become insecure. The following code is for reference only.
            // We recommend that you use Security Token Service (STS) tokens, which provide higher security. For information about credential-based authentication methods, see the topic at the following URL: https://www.alibabacloud.com/help/en/sdk/developer-reference/v2-manage-access-credentials?spm=a2c63.p38356.0.0.cc196072Z9j9AY.
            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.
                    .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                    // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured.
                    .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            // Specify the VPC address of the instance as the endpoint. Example: kst-hzz65f176a0ogplgq****.cryptoservice.kms.aliyuncs.com
            config.endpoint = "<VPC address of the instance>";
            // Specify the content of the CA certificate of the instance
            config.ca = "<CA certificate of the instance>";
            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.GetSecretValueRequest getSecretValueRequest = new com.aliyun.kms20160120.models.GetSecretValueRequest()
                    .setSecretName("<SecretName>");
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            try {
                // Write your code to print the response of the API operation if necessary
                client.getSecretValueWithOptions(getSecretValueRequest, runtime);
            } catch (TeaException error) {
                // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided only for reference.
                // Obtain an error message
                System.out.println(error.getMessage());
                // Provide the URL for troubleshooting
                System.out.println(error.getData().get("Recommend"));
                com.aliyun.teautil.Common.assertAsString(error.message);
            } catch (Exception _error) {
                TeaException error = new TeaException(_error.getMessage(), _error);
                // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided only for reference.
                // Obtain an error message
                System.out.println(error.getMessage());
                // Provide the URL for troubleshooting
                System.out.println(error.getData().get("Recommend"));
                com.aliyun.teautil.Common.assertAsString(error.message);
            }        
        }
    }