Hardcoding sensitive information such as database passwords and API keys in your application can lead to credential leaks. Key Management Service (KMS) Credential Manager allows you to centrally store and encrypt sensitive data. Applications can dynamically retrieve credentials through the VPC network using SDKs, eliminating the need to embed sensitive data in code. This topic describes how to create a credential and integrate it into your application.
Credential types
KMS provides full lifecycle management for credentials, including creation, update, rotation, and deletion. Applications dynamically retrieve credential values through SDKs to avoid hardcoding sensitive data in code.
Credential type | Scenario | Description |
Generic credential | Store any sensitive data in key-value pair or plain text format | Suitable for API keys, connection strings, certificate text, and more. Sensitive data must be up to 30,720 bytes (30 KB) in length. |
RAM credential | Manage AccessKey pairs of RAM users | Select an existing RAM user to manage its AccessKey pair. The credential name is automatically generated based on the RAM username. Supports automatic rotation. |
Database credential (RDS) | Manage RDS database accounts and passwords | Associate with an RDS instance to manage database accounts. Supports dual-account mode for seamless rotation without connection interruption. |
Database credential (PolarDB) | Manage PolarDB database accounts and passwords | Associate with PolarDB MySQL/PostgreSQL instances. Supports only dual-account mode and one-click account creation. |
Database credential (Redis) | Manage Redis/Tair instance accounts and passwords | Associate with Redis or Tair instances. Supports only dual-account mode. KMS automatically creates two accounts with identical permissions in the database. |
ECS credential | Manage logon passwords or SSH key pairs for ECS instances | Associate with ECS instances and system users. Supports both password and SSH key pair formats. |
Prerequisites
A symmetric key is created in your KMS instance for encrypting credentials. The key and the credential must belong to the same KMS instance. For more information, see Create a key.
Step 1: Create a credential
You can enable automatic rotation when creating a credential. KMS will periodically update the credential value to reduce the risk of credential leaks. The following describes how to create each type of credential.
Generic credential
Generic credentials do not support setting rotation at creation time. To rotate a generic credential, see Rotate a generic secret.
Log on to the Key Management Service console. In the top navigation bar, select a region. In the left-side navigation pane, choose .
On the Customer-managed Secrets tab, click the Type tab, and then click Generic Secrets.
Click Create Generic Secret at the upper part of the list on the right. Complete the following configuration, and then click OK.
Parameter
Description
Secret Name
A custom credential name. Must be unique within the current region.
Secret Value
Select Secret Key/Value or Plain Text and enter the sensitive data to store. The value must be up to 30,720 bytes (30 KB) in length.
Initial Version
The initial version number. Default value: v1. Custom values are supported.
CMK
Select the symmetric key used to encrypt the credential value. The key and the credential must belong to the same KMS instance.
ImportantThe key and the secret must belong to the same KMS instance, and the key must be a symmetric key. For more information about the symmetric keys supported by KMS, see Key types and specifications.
A RAM user or RAM role must have permissions to call the GenerateDataKey operation by using a customer master key (CMK).
Description
An optional description of the credential for identification and management.
Set the access policy for the credential to control which RAM users or roles can read or modify it.
You can select the default policy first and modify it later as needed.
RAM credential
Log on to the Key Management Service console. In the top navigation bar, select a region. In the left-side navigation pane, choose .
On the Customer-managed Secrets tab, click the Type tab, and then click RAM Secrets.
Click Create RAM Secret at the upper part of the list on the right. Complete the following configuration, and then click OK.
Parameter
Description
Select RAM User
Select the RAM user whose credential you want to manage. The user must have at least one AccessKey pair. The credential name is automatically generated based on the RAM username.
If the user does not have an AccessKey pair, create one first.
Secret Value
Enter the AccessKey secret. The value must be up to 30,720 bytes (30 KB) in length.
CMK
Select the symmetric key used to encrypt the credential value. The key and the credential must belong to the same KMS instance.
ImportantThe key and the secret must belong to the same KMS instance, and the key must be a symmetric key. For more information about the symmetric keys supported by KMS, see Key types and specifications.
A RAM user or RAM role must have permissions to call the GenerateDataKey operation by using a customer master key (CMK).
Automatic Rotation
Select whether to enable automatic rotation. When enabled, KMS periodically updates the credential value to reduce the risk of credential leaks.
Days (7 Days to 365 Days)
Set this parameter only when automatic rotation is enabled. Specifies the rotation interval.
Description
An optional description of the credential for identification and management.
Set the access policy for the credential to control which RAM users or roles can read or modify it.
You can select the default policy first and modify it later as needed.
Database credential (RDS)
Only Create Single Secret is supported.
Log on to the Key Management Service console. In the top navigation bar, select a region. In the left-side navigation pane, choose .
On the Customer-managed Secrets tab, click the Type tab, and then click Database Secrets.
Click Create Database Secret > Create Single Secret at the upper part of the list on the right. Complete the following configuration, and then click OK.
Parameter
Description
Database Type
Select ApsaraDB RDS Secrets.
Secret Name
A custom credential name. Must be unique within the current region.
ApsaraDB RDS Instance
Select an RDS instance under your Alibaba Cloud account.
Account Management
Manage Dual Accounts (Recommended): Suitable for programmatic database access. KMS manages two accounts with identical permissions to avoid connection interruption during rotation.
Click Create Account to configure the account name, select a database, and specify permissions.
NoteOne-click creation and authorization does not immediately create the new account. The account is created after you review and confirm the credential information.
For RDS PostgreSQL, you cannot obtain the database name during creation. You must manually set the DBName.
Click Import Existing Accounts to select a username and configure the password.
NoteWe recommend that you set the password to the one used when creating the RDS instance user account. If the imported username and password do not match, you can obtain the correct account and password after the first credential rotation.
Manage Single Account: Suitable for privileged accounts or manual O&M account hosting scenarios. The current credential version may be temporarily unavailable immediately after password reset.
Click Create Account to configure the account name and select the account type.
Supports Standard Account and Privileged Account. When you select Standard Account, you must also select a database and specify permissions.
Click the Import Existing Accounts tab to select a username and configure the password.
CMK
Select the symmetric key used to encrypt the credential value. The key and the credential must belong to the same KMS instance.
ImportantThe key and the secret must belong to the same KMS instance, and the key must be a symmetric key. For more information about the symmetric keys supported by KMS, see Key types and specifications.
A RAM user or RAM role must have permissions to call the GenerateDataKey operation by using a customer master key (CMK).
Automatic Rotation
Select whether to enable automatic rotation. When enabled, KMS periodically updates the credential value to reduce the risk of credential leaks.
Rotation Period
Set this parameter only when automatic rotation is enabled. Valid values: 6 hours to 365 days.
Specifies the rotation interval. KMS periodically updates the credential value based on this setting.
Description
An optional description of the credential for identification and management.
Set the access policy for the credential to control which RAM users or roles can read or modify it.
You can select the default policy first and modify it later as needed.
Database credential (PolarDB)
Only Create Single Secret is supported, and only for PolarDB MySQL/PostgreSQL with Create Account and Manage Dual Accounts. Import Existing Accounts and Manage Single Account are not supported.
Log on to the Key Management Service console. In the top navigation bar, select a region. In the left-side navigation pane, choose .
On the Customer-managed Secrets tab, click the Type tab, and then click Database Secrets.
Click Create Database Secret > Create Single Secret at the upper part of the list on the right. Complete the following configuration, and then click OK.
Parameter
Description
Database Type
Select PolarDB Secret.
Secret Name
A custom credential name. Must be unique within the current region.
PolarDB Cluster
Select a PolarDB instance under your Alibaba Cloud account.
Account Management
Manage Dual Accounts: Suitable for programmatic database access. KMS creates two standard accounts with identical permissions to avoid connection interruption during rotation.
Create Account: Configure the account name and permissions. Only Standard Account is supported. For MySQL, you must also select a database and specify permissions.
NoteOne-click creation and authorization does not immediately create the new account. The account is created after you review and confirm the credential information.
The account name must be unique. If the account name already exists, it cannot be hosted as a credential.
CMK
Select the symmetric key used to encrypt the credential value. The key and the credential must belong to the same KMS instance.
ImportantThe key and the secret must belong to the same KMS instance, and the key must be a symmetric key. For more information about the symmetric keys supported by KMS, see Key types and specifications.
A RAM user or RAM role must have permissions to call the GenerateDataKey operation by using a customer master key (CMK).
Automatic Rotation
Select whether to enable automatic rotation. When enabled, KMS periodically updates the credential value to reduce the risk of credential leaks.
Rotation Period
Set this parameter only when automatic rotation is enabled. Valid values: 6 hours to 365 days.
Specifies the rotation interval. KMS periodically updates the credential value based on this setting.
Description
An optional description of the credential for identification and management.
Set the access policy for the credential to control which RAM users or roles can read or modify it.
You can select the default policy first and modify it later as needed.
Database credential (Redis)
Both Create Single Secret and Create Bulk Secrets are supported. The following example uses Create single secret.
Log on to the Key Management Service console. In the top navigation bar, select a region. In the left-side navigation pane, choose .
On the Customer-managed Secrets tab, click the Type tab, and then click Database Secrets.
Click Create Database Secret > Create Single Secret at the upper part of the list on the right. Complete the following configuration, and then click OK.
Parameter
Description
Database Type
Select ApsaraDB for Redis/Tair Instance.
Secret Name
A custom credential name. Must be unique within the current region.
ApsaraDB for Redis/Tair Instance
Select a Redis instance or Tair instance under your Alibaba Cloud account.
Account Management
Only Manage Dual Accounts is supported.
Secret Value
Only new accounts are supported. Existing Redis/Tair accounts cannot be hosted.
Account Name: Specify a username prefix. KMS creates two database accounts with identical permissions by calling an API. For example, if you specify
user, KMS createsuseranduser_clone.Permissions: Set to Read/Write or Read-Only. Both new accounts have the same permissions.
CMK
Select the symmetric key used to encrypt the credential value. The key and the credential must belong to the same KMS instance.
ImportantThe key and the secret must belong to the same KMS instance, and the key must be a symmetric key. For more information about the symmetric keys supported by KMS, see Key types and specifications.
A RAM user or RAM role must have permissions to call the GenerateDataKey operation by using a customer master key (CMK).
Automatic Rotation
Select whether to enable automatic rotation. When enabled, KMS periodically updates the credential value to reduce the risk of credential leaks.
Rotation Period
Set this parameter only when automatic rotation is enabled. Valid values: 6 hours to 365 days.
Specifies the rotation interval. KMS periodically updates the credential value based on this setting.
Description
An optional description of the credential for identification and management.
Set the access policy for the credential to control which RAM users or roles can read or modify it.
You can select the default policy first and modify it later as needed.
ECS credential
Log on to the Key Management Service console. In the top navigation bar, select a region. In the left-side navigation pane, choose .
On the Customer-managed Secrets tab, click the Type tab, and then click ECS Secrets.
Click Create ECS Secret at the upper part of the list on the right. Complete the following configuration, and then click OK.
Parameter
Description
Secret Name
A custom credential name. Must be unique within the current region.
Managed Instance
Select an ECS instance under your Alibaba Cloud account.
Managed User
Enter the username of an existing user on the ECS instance, such as
root(Linux) orAdministrator(Windows).Initial Secret Value
The credential value must be up to 30,720 bytes (30 KB) in length.
Password: The logon password of the user on the ECS instance.
Key pair: The SSH key pair used to log on to the ECS instance.
NoteThe credential value must be correctly configured. If the credential value is incorrect, the password or key pair retrieved from KMS cannot be used to log on to the ECS instance until the credential is first rotated.
CMK
Select the symmetric key used to encrypt the credential value. The key and the credential must belong to the same KMS instance.
ImportantThe key and the secret must belong to the same KMS instance, and the key must be a symmetric key. For more information about the symmetric keys supported by KMS, see Key types and specifications.
A RAM user or RAM role must have permissions to call the GenerateDataKey operation by using a customer master key (CMK).
Automatic Rotation
Select whether to enable automatic rotation. When enabled, KMS periodically updates the credential value to reduce the risk of credential leaks.
Rotation Period
Set this parameter only when automatic rotation is enabled. Valid values: 1 hour to 365 days.
Specifies the rotation interval. KMS periodically updates the credential value based on this setting.
Description
An optional description of the credential for identification and management.
Set the access policy for the credential to control which RAM users or roles can read or modify it.
You can select the default policy first and modify it later as needed.
After the credential is created, it appears in the credential list. Verify that the credential name and type are correct and that the status is "Enabled".
Step 2: Retrieve the credential in your application
This example uses the Alibaba Cloud SDK for Java to dynamically retrieve a credential.
Preparation
Prepare the SDK runtime environment.
Requirement: Java 8 or later is installed.
Verification: Run
java -versionin a terminal to confirm the version.Install the SDK. Add the following Maven dependency to your project using Alibaba Cloud SDK V2.0.
ImportantWe recommend that you use the latest version. Visit kms-20160120 for the latest version and source code information.
<dependency> <groupId>com.aliyun</groupId> <artifactId>kms20160120</artifactId> <version>1.4.0</version> </dependency>Create an authentication credential. The Alibaba Cloud SDK supports multiple authentication methods. This example uses the AccessKey pair of a RAM user.
Create an AccessKey pair for a RAM user in the RAM console. Skip this step if you already have an AccessKey pair.
Grant the RAM user permissions to access KMS. To retrieve credential values, attach the
AliyunKMSSecretUserAccessandAliyunKMSCryptoUserAccesssystem policies. For more information, see Configure policies.NoteKMS provides two access permission configuration methods:
Identity-based policies: Control access by associating identities with corresponding permissions. For more information, see Identity-based policy configuration.
Resource-based policies: Include key policies and credential policies that are directly associated with resources to define access rules for specific resources. For more information, see Key policy configuration and Credential policy configuration.
Obtain the CA certificate for your KMS instance.
On the Instances page, click the Software Key Management or Hardware Key Management tab, and then select the target KMS instance.
Click the instance ID or click Details in the Actions column. On the Details page, in the Instance CA Certificate section, click Download and save the certificate securely.
NoteThe downloaded CA certificate file is named
PrivateKmsCA_kst-******.pemby default.
Obtain the VPC endpoint of your KMS instance.
On the Instances page, click the Software Key Management or Hardware Key Management tab, and then select the target KMS instance.
Click the instance ID to go to the details page and view the Instance VPC Endpoint.
Retrieve the credential
Initialize the SDK client.
NoteBefore running the sample code, replace the following placeholders with actual values:
<VPC endpoint>: Replace with the VPC endpoint of your KMS instance.<CA certificate>: Replace with the actual content of the KMS instance CA certificate.<SecretName>: Replace with the credential name created in Step 1.
public static com.aliyun.kms20160120.Client createClient() throws Exception { // Code leaks may cause AccessKey compromise and threaten the security of all resources under your account. The following sample code is for reference only. // We recommend that you use STS for more secure 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 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")); // Enter the VPC endpoint of your KMS instance, for example, kst-hzz65f176a0ogplgq****.cryptoservice.kms.aliyuncs.com config.endpoint = "<VPC endpoint>"; // Enter the CA certificate content of your KMS instance config.ca = "<CA certificate>"; return new com.aliyun.kms20160120.Client(config); }Call the
GetSecretValueoperation to retrieve the credential 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 { // Code leaks may cause AccessKey compromise and threaten the security of all resources under your account. The following sample code is for reference only. // We recommend that you use STS for more secure 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 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")); // Enter the VPC endpoint of your KMS instance, for example, kst-hzz65f176a0ogplgq****.cryptoservice.kms.aliyuncs.com config.endpoint = "<VPC endpoint>"; // Enter the CA certificate content of your KMS instance config.ca = "<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.GetSecretValueRequest getSecretValueRequest = new com.aliyun.kms20160120.models.GetSecretValueRequest() .setSecretName("<SecretName>"); com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions(); try { // Replace with your own logic to process the API response client.getSecretValueWithOptions(getSecretValueRequest, runtime); } catch (TeaException error) { // Print for demonstration only. Handle exceptions carefully in production. // Error message System.out.println(error.getMessage()); // Diagnostic 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); // Print for demonstration only. Handle exceptions carefully in production. // Error message System.out.println(error.getMessage()); // Diagnostic URL System.out.println(error.getData().get("Recommend")); com.aliyun.teautil.Common.assertAsString(error.message); } } }
After a successful call, the SDK returns a response object containing fields such as SecretName and SecretData. Print response.body.secretData to view the credential value, and use it in your application to access the corresponding service to verify connectivity.