加密解密示例

初始化KMS实例SDK客户端后,您可以通过客户端调用Encrypt和Decrypt接口对数据进行加密解密。本文介绍加密解密的代码示例。

完整代码示例

集成KMS进行对称加密解密包含三个步骤:

  1. 初始化调用KMS接口的客户端。

  2. 使用客户端调用Encrypt接口对数据进行加密。

  3. 使用客户端调用Decrypt接口对密文数据进行解密。

源码github地址:AesEncryptDecryptSample.java

加密解密完整代码示例

package com.aliyun.dkms.gcs.sdk.example;

import com.aliyun.dkms.gcs.openapi.models.Config;
import com.aliyun.dkms.gcs.openapi.util.models.RuntimeOptions;
import com.aliyun.dkms.gcs.sdk.Client;
import com.aliyun.dkms.gcs.sdk.models.DecryptRequest;
import com.aliyun.dkms.gcs.sdk.models.DecryptResponse;
import com.aliyun.dkms.gcs.sdk.models.EncryptRequest;
import com.aliyun.dkms.gcs.sdk.models.EncryptResponse;
import com.aliyun.tea.TeaException;

import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * ClientKey传参支持以下三种方式:
 * 1、通过指定ClientKey.json文件路径方式
 * 示例:
 * String clientKeyFile = "<your client key file path>";
 * String password = "<your client key password>";
 * Config cfg = new Config();
 * cfg.setClientKeyFile(clientKeyFile);
 * cfg.setPassword(password);
 * <p>
 * 2、通过指定ClientKey内容方式
 * 示例:
 * String clientKeyContent = "<your client key content>";
 * String password = "<your client key password>";
 * Config cfg = new Config();
 * cfg.setClientKeyContent(clientKeyContent);
 * cfg.setPassword(password);
 * <p>
 * 3、通过指定私钥和AccessKeyId
 * 示例:
 * String accessKeyId = "<your client key KeyId>";
 * String privateKey = "<parse from your client key PrivateKeyData>";
 * Config cfg = new Config();
 * cfg.setAccessKeyId(accessKeyId);
 * cfg.setPrivateKey(privateKey);
 */
public class AesEncryptDecryptSample {

    // KMS实例Client对象
    private static Client client = null;

    public static void main(String[] args) {
        try {
            // 构建加密服务实例Client对象
            initClient();

            // 使用加密服务实例进行加解密示例
            encryptDecryptSample();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void initClient() throws Exception {
        // 连接协议请设置为"https"。KMS实例服务仅允许通过HTTPS协议访问。
        Config config = new Config();
        config.setProtocol("https");
    
        // Client Key。
        config.setClientKeyFile("<your-client-key-file>");
     
         // Client Key口令。
        config.setPassword("<your-password>");
       
         // 设置endpoint为<your KMS Instance Id>.cryptoservice.kms.aliyuncs.com。
        config.setEndpoint("<your-endpoint>");
        
        // KMS实例的CA证书,可通过文件路径或直接设置内容。
        config.setCaFilePath("<path/to/yourCaCert>");
        // 或者,设置为KMS实例的CA证书内容
        //config.setCa("<your-ca-certificate-content");
        client = new Client(config);
    }

    // 加解密示例
    private static void encryptDecryptSample() {
        String keyId = "<your-key-id>";
        String plaintext = "<your-plaintext>";
        final AesEncryptContext aesEncryptContext = encryptSample(keyId, plaintext);
        String decryptResult = decryptSample(aesEncryptContext);
        if (!plaintext.equals(decryptResult)) {
            System.out.println("Decrypt data not match the plaintext");
        }
    }

    // 加密示例
    private static AesEncryptContext encryptSample(String keyId, String plaintext) {
        // 构建加密请求
        EncryptRequest encryptRequest = new EncryptRequest();
        encryptRequest.setKeyId(keyId);
        encryptRequest.setPlaintext(plaintext.getBytes(StandardCharsets.UTF_8));
        try {
            // 调用加密接口进行加密
            // 如需忽略服务端证书,可使用此处注释代码方式调用
            //RuntimeOptions runtimeOptions = new RuntimeOptions();
            //runtimeOptions.setIgnoreSSL(true);
            //EncryptResponse encryptResponse = client.encryptWithOptions(encryptRequest, runtimeOptions);
            EncryptResponse encryptResponse = client.encrypt(encryptRequest);
            System.out.printf("KeyId: %s%n", encryptResponse.getKeyId());
            System.out.printf("CiphertextBlob: %s%n", Arrays.toString(encryptResponse.getCiphertextBlob()));
            System.out.printf("Iv: %s%n", Arrays.toString(encryptResponse.getIv()));
            return new AesEncryptContext(encryptResponse.getKeyId(), encryptResponse.getCiphertextBlob(), encryptResponse.getIv(), encryptResponse.getAlgorithm());
        } catch (TeaException e) {
            System.out.printf("code: %s%n", ((TeaException) e).getCode());
            System.out.printf("message: %s%n", e.getMessage());
            System.out.printf("requestId: %s%n", ((TeaException) e).getData().get("requestId"));
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (Exception e) {
            System.out.printf("encrypt err: %s%n", e.getMessage());
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    // 解密示例
    private static String decryptSample(final AesEncryptContext aesEncryptContext) {
        // 构建解密请求对象
        DecryptRequest decryptRequest = new DecryptRequest();
        decryptRequest.setKeyId(aesEncryptContext.getKeyId());
        decryptRequest.setCiphertextBlob(aesEncryptContext.getCiphertextBlob());
        decryptRequest.setAlgorithm(aesEncryptContext.getAlgorithm());
        decryptRequest.setIv(aesEncryptContext.getIv());
        try {
            // 调用解密接口进行解密
            // 如需忽略服务端证书,可使用此处注释代码方式调用
            //RuntimeOptions runtimeOptions = new RuntimeOptions();
            //runtimeOptions.setIgnoreSSL(true);
            //DecryptResponse decryptResponse = client.decryptWithOptions(decryptRequest, runtimeOptions);
            DecryptResponse decryptResponse = client.decrypt(decryptRequest);
            System.out.printf("KeyId: %s%n", decryptResponse.getKeyId());
            System.out.printf("Plaintext: %s%n", new String(decryptResponse.getPlaintext()));
            System.out.printf("RequestId: %s%n", decryptResponse.getRequestId());
            return new String(decryptResponse.getPlaintext());
        } catch (TeaException e) {
            System.out.printf("code: %s%n", ((TeaException) e).getCode());
            System.out.printf("message: %s%n", e.getMessage());
            System.out.printf("requestId: %s%n", ((TeaException) e).getData().get("requestId"));
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (Exception e) {
            System.out.printf("decrypt err: %s%n", e.getMessage());
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * The aes encrypt context may be stored.
     */
    static class AesEncryptContext implements Serializable {
        public String keyId;
        public byte[] ciphertextBlob;
        public byte[] iv;
        /**
         * Use default algorithm value,if the value is not set.
         */
        public String algorithm;

        public AesEncryptContext() {
        }

        public AesEncryptContext(String keyId, byte[] ciphertextBlob, byte[] iv, String algorithm) {
            this.keyId = keyId;
            this.ciphertextBlob = ciphertextBlob;
            this.iv = iv;
            this.algorithm = algorithm;
        }

        public String getKeyId() {
            return keyId;
        }

        public void setKeyId(String keyId) {
            this.keyId = keyId;
        }

        public byte[] getCiphertextBlob() {
            return ciphertextBlob;
        }

        public void setCiphertextBlob(byte[] ciphertextBlob) {
            this.ciphertextBlob = ciphertextBlob;
        }

        public byte[] getIv() {
            return iv;
        }

        public void setIv(byte[] iv) {
            this.iv = iv;
        }

        public String getAlgorithm() {
            return algorithm;
        }

        public void setAlgorithm(String algorithm) {
            this.algorithm = algorithm;
        }

    }
}

代码示例解析

初始化客户端

关于初始化客户端的详细介绍,请参见初始化客户端

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

                           
 public static void initClient() throws Exception {

        // 连接协议请设置为"https"。KMS实例服务仅允许通过HTTPS协议访问。
        Config config = new Config();
        config.setProtocol("https");
    
        // Client Key。
        config.setClientKeyFile("<your-client-key-file>");
     
         // Client Key口令。
        config.setPassword("<your-password>");
       
         // 设置endpoint为<your KMS Instance Id>.cryptoservice.kms.aliyuncs.com。
        config.setEndpoint("<your-endpoint>");
        
        // KMS实例的CA证书,可通过文件路径或直接设置内容。
        config.setCaFilePath("<path/to/yourCaCert>");
        // 或者,设置为KMS实例的CA证书内容
        //config.setCa("<your-ca-certificate-content");
        client = new Client(config);
    }

调用Encrypt接口使用对称密钥对数据加密

您调用Encrypt进行数据加密后,除需要保存数据密文(CiphertextBlob),还需要保存KMS返回的密钥ID(KeyId)、Iv、加密算法(Algorithm)参数。

 // 加密示例
    private static AesEncryptContext encryptSample(String keyId, String plaintext) {
        // 构建加密请求
        EncryptRequest encryptRequest = new EncryptRequest();
        encryptRequest.setKeyId(keyId);
        encryptRequest.setPlaintext(plaintext.getBytes(StandardCharsets.UTF_8));
        try {
            // 调用加密接口进行加密
            // 如需忽略服务端证书,可使用此处注释代码方式调用
            //RuntimeOptions runtimeOptions = new RuntimeOptions();
            //runtimeOptions.setIgnoreSSL(true);
            //EncryptResponse encryptResponse = client.encryptWithOptions(encryptRequest, runtimeOptions);
            EncryptResponse encryptResponse = client.encrypt(encryptRequest);
            System.out.printf("KeyId: %s%n", encryptResponse.getKeyId());
            System.out.printf("CiphertextBlob: %s%n", Arrays.toString(encryptResponse.getCiphertextBlob()));
            System.out.printf("Iv: %s%n", Arrays.toString(encryptResponse.getIv()));
            return new AesEncryptContext(encryptResponse.getKeyId(), encryptResponse.getCiphertextBlob(), encryptResponse.getIv(), encryptResponse.getAlgorithm());
        } catch (TeaException e) {
            System.out.printf("code: %s%n", ((TeaException) e).getCode());
            System.out.printf("message: %s%n", e.getMessage());
            System.out.printf("requestId: %s%n", ((TeaException) e).getData().get("requestId"));
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (Exception e) {
            System.out.printf("encrypt err: %s%n", e.getMessage());
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

调用Decrypt接口使用对称密钥解密密文

     // 解密示例
    private static String decryptSample(final AesEncryptContext aesEncryptContext) {
        // 构建解密请求对象
        DecryptRequest decryptRequest = new DecryptRequest();
        decryptRequest.setKeyId(aesEncryptContext.getKeyId());
        decryptRequest.setCiphertextBlob(aesEncryptContext.getCiphertextBlob());
        decryptRequest.setAlgorithm(aesEncryptContext.getAlgorithm());
        decryptRequest.setIv(aesEncryptContext.getIv());
        try {
            // 调用解密接口进行解密
            // 如需忽略服务端证书,可使用此处注释代码方式调用
            //RuntimeOptions runtimeOptions = new RuntimeOptions();
            //runtimeOptions.setIgnoreSSL(true);
            //DecryptResponse decryptResponse = client.decryptWithOptions(decryptRequest, runtimeOptions);
            DecryptResponse decryptResponse = client.decrypt(decryptRequest);
            System.out.printf("KeyId: %s%n", decryptResponse.getKeyId());
            System.out.printf("Plaintext: %s%n", new String(decryptResponse.getPlaintext()));
            System.out.printf("RequestId: %s%n", decryptResponse.getRequestId());
            return new String(decryptResponse.getPlaintext());
        } catch (TeaException e) {
            System.out.printf("code: %s%n", ((TeaException) e).getCode());
            System.out.printf("message: %s%n", e.getMessage());
            System.out.printf("requestId: %s%n", ((TeaException) e).getData().get("requestId"));
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (Exception e) {
            System.out.printf("decrypt err: %s%n", e.getMessage());
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }