Utilisez le client SDK d'instance KMS pour appeler les API Encrypt et Decrypt afin de chiffrer et de déchiffrer des données à l'aide d'une clé symétrique.
Prérequis
Avant de commencer, assurez-vous d'avoir :
Initialisé un client SDK d'instance KMS. Pour obtenir des instructions, consultez la page Initialiser le client
Une clé symétrique KMS (
KeyId)
Exemple complet
Présentation détaillée de l'exemple
Initialiser le client
Configurez l'objet Config avec le protocole HTTPS, les identifiants de la clé cliente, le point de terminaison de l'instance KMS et le certificat d'autorité de certification (CA), puis transmettez-le à l'objet Client. Le service d'instance KMS n'accepte que les connexions via HTTPS. Pour plus de détails sur l'initialisation, consultez la page Initialiser le client.
import com.aliyun.dkms.gcs.openapi.models.Config;
import com.aliyun.dkms.gcs.sdk.Client;
public static void initClient() throws Exception {
// The connection protocol. Set the value to https. The KMS instance service only allows access through the HTTPS protocol.
Config config = new Config();
config.setProtocol("https");
// Client key.
config.setClientKeyFile("<CLIENT_KEY_FILE>");
// Client key password.
config.setPassword("<PASSWORD>");
// The endpoint of your KMS instance. Set the value in the following format: <KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com.
config.setEndpoint("<ENDPOINT>");
// The certificate authority (CA) certificate of the KMS instance. You can specify the path to the CA certificate file or enter the content of the CA certificate.
config.setCaFilePath("<CA_CERTIFICATE_PATH>");
// Alternatively, set the content of the CA certificate of the KMS instance.
//config.setCa("<CA_CERTIFICATE_CONTENT");
client = new Client(config);
}
Chiffrer les données
Appelez l'API Encrypt pour chiffrer un texte en clair à l'aide d'une clé symétrique.
Une fois l'appel réussi, stockez les valeurs CiphertextBlob, KeyId, Iv et Algorithm renvoyées dans la réponse. Vous devez fournir ces quatre champs lors de l'appel à l'API Decrypt.
// Encryption example.
private static AesEncryptContext encryptSample(String keyId, String plaintext) {
// Construct the encryption request.
EncryptRequest encryptRequest = new EncryptRequest();
encryptRequest.setKeyId(keyId);
encryptRequest.setPlaintext(plaintext.getBytes(StandardCharsets.UTF_8));
try {
// Call the encryption interface to encrypt.
// To ignore the server certificate, you can use the commented code here to call.
//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);
}
}
Déchiffrer le texte chiffré
Appelez l'API Decrypt pour récupérer le texte en clair d'origine. Transmettez les valeurs KeyId, CiphertextBlob, Algorithm et Iv renvoyées par l'appel à l'API Encrypt.
// Decryption example.
private static String decryptSample(final AesEncryptContext aesEncryptContext) {
// Construct the decryption request object.
DecryptRequest decryptRequest = new DecryptRequest();
decryptRequest.setKeyId(aesEncryptContext.getKeyId());
decryptRequest.setCiphertextBlob(aesEncryptContext.getCiphertextBlob());
decryptRequest.setAlgorithm(aesEncryptContext.getAlgorithm());
decryptRequest.setIv(aesEncryptContext.getIv());
try {
// Call the decryption interface to decrypt.
// To ignore the server certificate, you can use the commented code here to call.
//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);
}
}