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, digital signature generation, and digital signature verification.

Prerequisites

Make sure that the following requirements are met:
  1. A dedicated KMS instance is created and connected to an HSM cluster. The dedicated KMS instance is in the Connected state. For more information, see Step 2: Configure a dedicated KMS instance.
  2. A symmetric customer master key (CMK) is created for the dedicated KMS instance in the KMS console. For more information, see Step 3: Create a CMK for a dedicated KMS instance.
  3. The endpoint of the dedicated KMS instance is obtained and can be accessed.
    • The endpoint of the dedicated KMS instance is the endpoint of the VPC to access the dedicated KMS instance. The endpoint of the VPC is specified when you activate the HSM cluster.
    • The endpoint of the dedicated KMS instance can be accessed from your computer.

    For more information, see Query a dedicated KMS instance.

  4. An Application Access Point (AAP) is created for the dedicated KMS instance, and the client key is obtained. For more information, see Create an AAP.

Background information

You can visit the open source code repository to view the source code and sample code of Dedicated KMS SDK. Your comments and code examples are greatly appreciated.

Install Dedicated KMS SDK

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

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>alibabacloud-dkms-gcs-sdk</artifactId>
  <version>x.x.x</version>
</dependency>
Note The latest version of Dedicated KMS SDK is 0.2.1. For more information about the latest version, see Dedicated KMS SDK for Java.

Initialize Dedicated KMS SDK

You can initialize a Java client for a dedicated KMS instance to call resources that are managed by the dedicated KMS instance. For example, you can use the client to call the keys that are managed by the instance. Before you can use Dedicated KMS SDK for Java to initiate an API request, you must create a client instance and modify the default configuration items of Config based on your business requirements.

  1. Configure a CA certificate.

    To ensure secure communications in the production environment, you must configure a Java-trusted certificate. The following steps describe how to configure a Java-trusted certificate:

    1. Download the CA certificate of the dedicated KMS instance.

      For more information, see Obtain a CA certificate of a dedicated KMS instance.

      The file is named PrivateKmsCA_kst-xxxxxx.pem. The following example shows the file content:

      -----BEGIN CERTIFICATE-----
      <Root CA Certificate BASE64 Content>
      -----END CERTIFICATE-----
      -----BEGIN CERTIFICATE-----
      <Sub CA Certificate BASE64 Content>
      -----END CERTIFICATE-----
    2. Create a JAVA_HOME directory as the Java installation directory.
    3. Split the downloaded CA certificate file into two files.
      • 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-----
    4. Import the CA certificate to the JAVA_HOME/lib/security/cacerts file by using keytool commands.
      • Import file 1: rootca.pem
        keytool -importcert -alias PrivateKmsCA_RootCA -keystore cacerts -storepass changeit -file rootca.pem
      • Import file 2: subca.pem
        keytool -importcert -alias PrivateKmsCA_SubCA -keystore cacerts -storepass changeit -file subca.pem
    5. 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 correct.

    In the development environment, you can use the RuntimeOptions command 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.

    When you create a client for a dedicated KMS instance, you must specify the endpoint of the instance. The endpoint of a dedicated KMS instance excludes the scheme https. For more information about the endpoint of a dedicated KMS instance, see Query a dedicated KMS instance.

    import com.aliyun.dkms.gcs.openapi.models.Config;
    import com.aliyun.dkms.gcs.sdk.Client;
    
    // The connection protocol. Set the value to HTTPS. 
    String protocol = "https";
    // The endpoint of the dedicated KMS instance. When you specify this parameter, exclude the scheme https of the endpoint. 
    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.
    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. The CMK is used for encryption. 
    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 data after encryption. 
    byte[] cipherData = encryptResponse.getCiphertextBlob();
    // The initial vector of Cipher, which 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 ciphertext.
    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. The CMK is used for decryption. 
    String cipherKeyId = "<your cipher key id>";
    // The data 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);
    // The raw data. 
    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 digital signature.
    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. The CMK is used for signature generation and verification. 
    String signerKeyId = "<the signer key id>";
    // The preprocessed data, or the digest of the data that you want to sign. 
    byte[] digest = <the digest or ZA-Value of the data to sign>;
    
    SignRequest signRequest = new SignRequest();
    signRequest.setKeyId(signKeyId);
    signRequest.setMessage(digest);
    signRequest.setMessageType("DIGEST");
    
    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 digital signature.
    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. The CMK is used for signature generation and verification. 
    String signerKeyId = "<the signer key id>";
    // The preprocessed data, or the digest of the data that you want to sign. 
    byte[] digest = <the digest or sm2-signature-pretreatment-value of the plaintext to sign>;
    
    VerifyRequest verifyRequest = new VerifyRequest();
    verifyRequest.setKeyId(signerKeyId);
    verifyRequest.setMessage(digest);
    verifyRequest.setMessageType("DIGEST");
    verifyRequest.setSignature(signature);
    
    VerifyResponse verifyResponse = client.verify(verifyRequest);
    // The verification result. 
    boolean valid = verifyResponse.getValue();
    // The ID of the request. 
    String requestId = verifyResponse.getRequestId();