加密解密示例
更新時(shí)間:
初始化KMS實(shí)例SDK客戶端后,您可以通過客戶端調(diào)用Encrypt和Decrypt接口對數(shù)據(jù)進(jìn)行加密解密。本文介紹加密解密的代碼示例。
完整代碼示例
集成KMS進(jìn)行對稱加密解密包含三個(gè)步驟:
初始化調(diào)用KMS接口的客戶端。
使用客戶端調(diào)用Encrypt接口對數(shù)據(jù)進(jìn)行加密。
使用客戶端調(diào)用Decrypt接口對密文數(shù)據(jù)進(jìn)行解密。
源碼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內(nèi)容方式
* 示例:
* 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實(shí)例Client對象
private static Client client = null;
public static void main(String[] args) {
try {
// 構(gòu)建加密服務(wù)實(shí)例Client對象
initClient();
// 使用加密服務(wù)實(shí)例進(jìn)行加解密示例
encryptDecryptSample();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void initClient() throws Exception {
// 連接協(xié)議請?jiān)O(shè)置為"https"。KMS實(shí)例服務(wù)僅允許通過HTTPS協(xié)議訪問。
Config config = new Config();
config.setProtocol("https");
// Client Key。
config.setClientKeyFile("<your-client-key-file>");
// Client Key口令。
config.setPassword("<your-password>");
// 設(shè)置endpoint為<your KMS Instance Id>.cryptoservice.kms.aliyuncs.com。
config.setEndpoint("<your-endpoint>");
// KMS實(shí)例的CA證書,可通過文件路徑或直接設(shè)置內(nèi)容。
config.setCaFilePath("<path/to/yourCaCert>");
// 或者,設(shè)置為KMS實(shí)例的CA證書內(nèi)容
//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) {
// 構(gòu)建加密請求
EncryptRequest encryptRequest = new EncryptRequest();
encryptRequest.setKeyId(keyId);
encryptRequest.setPlaintext(plaintext.getBytes(StandardCharsets.UTF_8));
try {
// 調(diào)用加密接口進(jìn)行加密
// 如需忽略服務(wù)端證書,可使用此處注釋代碼方式調(diào)用
//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) {
// 構(gòu)建解密請求對象
DecryptRequest decryptRequest = new DecryptRequest();
decryptRequest.setKeyId(aesEncryptContext.getKeyId());
decryptRequest.setCiphertextBlob(aesEncryptContext.getCiphertextBlob());
decryptRequest.setAlgorithm(aesEncryptContext.getAlgorithm());
decryptRequest.setIv(aesEncryptContext.getIv());
try {
// 調(diào)用解密接口進(jìn)行解密
// 如需忽略服務(wù)端證書,可使用此處注釋代碼方式調(diào)用
//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;
}
}
}
代碼示例解析
初始化客戶端
關(guān)于初始化客戶端的詳細(xì)介紹,請參見初始化客戶端。
import com.aliyun.dkms.gcs.openapi.models.Config;
import com.aliyun.dkms.gcs.sdk.Client;
public static void initClient() throws Exception {
// 連接協(xié)議請?jiān)O(shè)置為"https"。KMS實(shí)例服務(wù)僅允許通過HTTPS協(xié)議訪問。
Config config = new Config();
config.setProtocol("https");
// Client Key。
config.setClientKeyFile("<your-client-key-file>");
// Client Key口令。
config.setPassword("<your-password>");
// 設(shè)置endpoint為<your KMS Instance Id>.cryptoservice.kms.aliyuncs.com。
config.setEndpoint("<your-endpoint>");
// KMS實(shí)例的CA證書,可通過文件路徑或直接設(shè)置內(nèi)容。
config.setCaFilePath("<path/to/yourCaCert>");
// 或者,設(shè)置為KMS實(shí)例的CA證書內(nèi)容
//config.setCa("<your-ca-certificate-content");
client = new Client(config);
}
調(diào)用Encrypt接口使用對稱密鑰對數(shù)據(jù)加密
您調(diào)用Encrypt進(jìn)行數(shù)據(jù)加密后,除需要保存數(shù)據(jù)密文(CiphertextBlob),還需要保存KMS返回的密鑰ID(KeyId)、Iv、加密算法(Algorithm)參數(shù)。
// 加密示例
private static AesEncryptContext encryptSample(String keyId, String plaintext) {
// 構(gòu)建加密請求
EncryptRequest encryptRequest = new EncryptRequest();
encryptRequest.setKeyId(keyId);
encryptRequest.setPlaintext(plaintext.getBytes(StandardCharsets.UTF_8));
try {
// 調(diào)用加密接口進(jìn)行加密
// 如需忽略服務(wù)端證書,可使用此處注釋代碼方式調(diào)用
//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);
}
}
調(diào)用Decrypt接口使用對稱密鑰解密密文
// 解密示例
private static String decryptSample(final AesEncryptContext aesEncryptContext) {
// 構(gòu)建解密請求對象
DecryptRequest decryptRequest = new DecryptRequest();
decryptRequest.setKeyId(aesEncryptContext.getKeyId());
decryptRequest.setCiphertextBlob(aesEncryptContext.getCiphertextBlob());
decryptRequest.setAlgorithm(aesEncryptContext.getAlgorithm());
decryptRequest.setIv(aesEncryptContext.getIv());
try {
// 調(diào)用解密接口進(jìn)行解密
// 如需忽略服務(wù)端證書,可使用此處注釋代碼方式調(diào)用
//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);
}
}
文檔內(nèi)容是否對您有幫助?