Dedicated KMS SDK for Java allows you to call the API operations of Dedicated Key Management Service (KMS) in a convenient manner. Dedicated KMS SDK for Java is suitable for business scenarios such as data encryption, data decryption, signature generation, signature verification, and secret value queries. This topic describes how to initialize an SDK and how to call API operations to encrypt and decrypt data, generate and verify signatures, and obtain secret information.

Background information

You can visit the open source code repository to view the source code and sample code of Dedicated KMS SDK. You are welcome to share your comments or provide your sample code.

Prerequisites

  • A dedicated KMS instance is purchased and connected to a hardware security module (HSM) cluster. A customer master key (CMK) and an application access endpoint (AAP) are created for the instance, and the client key and certification authority (CA) certificate of the instance are saved. For more information, see Connect applications to the dedicated KMS instance of the Standard edition.
    Note The downloaded CA certificate is named in the PrivateKmsCA_kst-******.pem format and the downloaded client key file is named in the ClientKey_******.json format.
  • The virtual private cloud (VPC) address that is used to access the dedicated KMS instance is obtained. The VPC address must meet the following requirements:
    • The VPC address is specified when the HSM cluster is activated.
    • The VPC address can be accessed from your computer.

    For more information, see Query a dedicated KMS instance of the Standard edition.

Install Dedicated KMS SDK

Add the alibabacloud-dkms-gcs-sdk dependency to your project. Then, a published Java package of Dedicated KMS SDK is automatically downloaded from the Maven repository.

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>alibabacloud-dkms-gcs-sdk</artifactId>
  <version>x.x.x</version>
</dependency>
Note To obtain the latest version of Dedicated KMS SDK, visit Dedicated KMS SDK for Java.

Initialize Dedicated KMS SDK

You can create a Java client for a dedicated KMS instance to call the resources that are managed by the dedicated KMS instance. For example, you can use the client to perform cryptographic operation and obtain secret information. Before you can use Dedicated KMS SDK for Java to initiate an API request, you must create a client.

Dedicated KMS SDK for Java 0.2.7 and later (recommended)

Create a client.
import com.aliyun.dkms.gcs.openapi.models.Config;
import com.aliyun.dkms.gcs.sdk.Client;

// The connection protocol between the dedicated KMS instance and the client. Set the value to https.
String protocol = "https";
// The VPC address of the dedicated KMS instance. The VPC address excludes the scheme https.
String endpoint = "<service_id>.cryptoservice.kms.aliyuncs.com";

// DKMS Client Key
String clientKeyFilePath = "<your client key file path>";
//String clientKey = "<your client key>";

// The password that is used to decrypt the client key of the dedicated KMS instance.
String clientKeyPass = "<your client key password>";

String caCertPath = "<path/to/DKMSInstanceCACertificates>";
//String caCert = "<The DKMS instance CA certificates content>";

Client client = new Client(new Config()
                           .setProtocol(protocol)
                           .setEndpoint(endpoint)
                           .setCaFilePath(caCertPath) // The path to the CA certificate file or the content of the CA certificate. Configure this parameter based on your business requirements. 
                           //.setCa(caCert) // The content of the CA certificate. 
                           .setClientKeyFile(clientKeyFilePath)// The path to the client key file or the content of the client key file. Configure this parameter based on your business requirements. 
                           //.setClientKeyContent(clientKey)// The content of the client key file. 
                           .setPassword(clientKeyPass));
In the development environment, you can use RuntimeOptions to temporarily ignore the verification of a trusted certificate. Sample code:
import com.aliyun.dkms.gcs.openapi.util.models.RuntimeOptions;

RuntimeOptions runtimeOptions = new RuntimeOptions();
runtimeOptions.setIgnoreSSL(true);
...
client.encryptWithOptions(encryptRequest, runtimeOptions);

Dedicated KMS SDK for Java 0.2.6 and earlier

  1. Configure a CA certificate.
    To ensure that secure connections are established in the production environment, configure a Java-trusted certificate.
    1. Split the CA certificate file into two files.
      A CA certificate consists of two files, and each file starts with ------BEGIN CERTIFICATE -------- and ends with ------END CERTIFICATE --------. By default, the first file contains the content of rootca.pem and the second file contains the content of subca.pem.
      • File 1: rootca.pem
        -----BEGIN CERTIFICATE-----
        <Root CA Certificate BASE64 Content>
        -----END CERTIFICATE-----
      • File 2: subca.pem
        -----BEGIN CERTIFICATE-----
        <Sub CA Certificate BASE64 Content>
        -----END CERTIFICATE-----
    2. Import the two files to the JAVA_HOME/jre/lib/security/cacerts directory by using keytool commands.
      • Import File 1: rootca.pem
        keytool -importcert -alias PrivateKmsCA_RootCA -keystore $JAVA_HOME/jre/lib/security/cacerts -storepass changeit -file rootca.pem
      • Import File 2: subca.pem
        keytool -importcert -alias PrivateKmsCA_SubCA -keystore $JAVA_HOME/jre/lib/security/cacerts -storepass changeit -file subca.pem
    3. Verify code.
      URL serviceUrl = new URL("https://<service_id>.cryptoservice.kms.aliyuncs.com");
      serviceUrl.openConnection().connect();
      Note If javax.net.ssl.SSLHandshakeException is not reported, the configuration is valid.
      In the development environment, you can use RuntimeOptions to temporarily ignore the verification of a trusted certificate. Sample code:
      import com.aliyun.dkms.gcs.openapi.util.models.RuntimeOptions;
      
      RuntimeOptions runtimeOptions = new RuntimeOptions();
      runtimeOptions.setIgnoreSSL(true);
      ...
      client.encryptWithOptions(encryptRequest, runtimeOptions);
  2. Create a client for the dedicated KMS instance.
    import com.aliyun.dkms.gcs.openapi.models.Config;
    import com.aliyun.dkms.gcs.sdk.Client;
    
    // The connection protocol between the dedicated KMS instance and the client. Set the value to https. 
    String protocol = "https";
    // The VPC address of the dedicated KMS instance. The VPC address excludes the scheme https. 
    String endpoint = "<service_id>.cryptoservice.kms.aliyuncs.com";
    // The client key of the dedicated KMS instance. 
    String clientKey = "<your client key>";
    // The password that is used to decrypt the client key of the dedicated KMS instance. 
    String clientKeyPass = "<your client key password>";
    
    Client client = new Client(new Config()
                               .setProtocol(protocol)
                               .setEndpoint(endpoint)
                               .setClientKeyContent(clientKey)
                               .setPassword(clientKeyPass));

Examples

  • Use the client of a dedicated KMS instance to call the Encrypt operation to encrypt data by using a symmetric CMK.

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

    import com.aliyun.dkms.gcs.sdk.Client;
    import com.aliyun.dkms.gcs.sdk.models.*;
    
    // The ID or alias of the symmetric CMK of the dedicated KMS instance. 
    String cipherKeyId = "<your cipher key id>";
    // The data that you want to encrypt. 
    byte[] originData = <your origin data to encrypt>;
    
    EncryptRequest encryptRequest = new EncryptRequest();
    encryptRequest.setKeyId(cipherKeyId);
    encryptRequest.setPlaintext(originData);
    
    EncryptResponse encryptResponse = client.encrypt(encryptRequest);
    // The ciphertext. 
    byte[] cipherData = encryptResponse.getCiphertextBlob();
    // The initial vector of Cipher that is used to decrypt data. 
    byte[] iv = encryptResponse.getIv();
    // The ID of the request. 
    String requestId = encryptResponse.getRequestId();
  • Use the client of a dedicated KMS instance to call the Decrypt operation to decrypt the ciphertext by using a symmetric CMK.

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

    import com.aliyun.dkms.gcs.sdk.Client;
    import com.aliyun.dkms.gcs.sdk.models.*;
    
    // The ID or alias of the symmetric CMK of the dedicated KMS instance. 
    String cipherKeyId = "<your cipher key id>";
    // The ciphertext that you want to decrypt. 
    byte[] cipherData = <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. 
    byte[] iv = <IV value>;
    
    DecryptRequest decryptRequest = new DecryptRequest();
            decryptRequest.setKeyId(cipherKeyId);
            decryptRequest.setCiphertextBlob(cipherData);
            decryptRequest.setIv(iv);
    
    DecryptResponse decryptResponse = client.decrypt(decryptRequest);
    // The plaintext. 
    byte[] originData = decryptResponse.getPlaintext();
    // The ID of the request. 
    String requestId = decryptResponse.getRequestId();
  • Use the client of a dedicated KMS instance to call the Sign operation to generate a signature by using an asymmetric CMK.

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

    import com.aliyun.dkms.gcs.sdk.Client;
    import com.aliyun.dkms.gcs.sdk.models.*;
    
    // The ID or alias of the symmetric CMK of the dedicated KMS instance. 
    String signerKeyId = "<the signer key id>";
    // The data to sign. 
    byte[] message = <the data to sign>;
    
    SignRequest signRequest = new SignRequest();
    signRequest.setKeyId(signKeyId);
    signRequest.setMessage(message);
    
    SignResponse signResponse = client.sign(signRequest);
    // The signature value. 
    byte[] signature = signResponse.getSignature();
    // The ID of the request. 
    String requestId = signResponse.getRequestId();
  • Use the client of a dedicated KMS instance to call the Verify operation to verify a signature by using an asymmetric CMK.

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

    import com.aliyun.dkms.gcs.sdk.Client;
    import com.aliyun.dkms.gcs.sdk.models.*;
    
    // The ID or alias of the symmetric CMK of the dedicated KMS instance. 
    String signerKeyId = "<the signer key id>";
    // The data for which you want to verify the signature. 
    byte[] message = <the data to sign>;
    
    VerifyRequest verifyRequest = new VerifyRequest();
    verifyRequest.setKeyId(signerKeyId);
    verifyRequest.setMessage(message);
    verifyRequest.setSignature(signature);
    
    VerifyResponse verifyResponse = client.verify(verifyRequest);
    // The verification result. 
    boolean valid = verifyResponse.getValue();
    // The ID of the request. 
    String requestId = verifyResponse.getRequestId();
  • Use the client of a dedicated KMS instance to call the GetSecretValue operation to query a secret value.

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

    Note Dedicated KMS SDK for Java 0.2.6 and later support the GetSecretValue operation.
    import com.aliyun.dkms.gcs.sdk.Client;
    import com.aliyun.dkms.gcs.sdk.models.*;
    
    // The secret name. 
    String secretName = "<your-secret-name>";
    
    GetSecretValueRequest request = new GetSecretValueRequest()
                    .setSecretName(secretName);
    
    GetSecretValueResponse getSecretValueResponse = client.getSecretValue(request);
    // The secret value.
    String secretData = getSecretValueResponse.getSecretData();
    // The ID of the request.
    String requestId = getSecretValueResponse.getRequestId();