全部产品
Search
文档中心

Key Management Service:Contoh kode untuk enkripsi dan dekripsi

更新时间:Jul 02, 2025

Setelah menginisialisasi SDK client instance KMS, Anda dapat menggunakannya untuk memanggil API Encrypt dan Decrypt guna melakukan enkripsi dan dekripsi data. Topik ini menyediakan contoh kode untuk keperluan tersebut.

Contoh lengkap

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;

/**
 * Parameter ClientKey mendukung tiga metode berikut:
 * 1. Dengan menentukan path ke file ClientKey.json.
 * Contoh:
 * String clientKeyFile = "<CLIENT_KEY_FILE_PATH>";
 * String password = "<CLIENT_KEY_PASSWORD>";
 * Config cfg = new Config();
 * cfg.setClientKeyFile(clientKeyFile);
 * cfg.setPassword(password);
 * <p>
 * 2. Dengan menentukan isi dari ClientKey.
 * Contoh:
 * String clientKeyContent = "<CLIENT_KEY_CONTENT>";
 * String password = "<CLIENT_KEY_PASSWORD>";
 * Config cfg = new Config();
 * cfg.setClientKeyContent(clientKeyContent);
 * cfg.setPassword(password);
 * <p>
 * 3. Dengan menentukan private key dan AccessKeyId.
 * Contoh:
 * String accessKeyId = "<CLIENT_KEY_KEYID>";
 * String privateKey = "<PARSE_FROM_CLIENT_KEY_PRIVATEKEY_DATA>";
 * Config cfg = new Config();
 * cfg.setAccessKeyId(accessKeyId);
 * cfg.setPrivateKey(privateKey);
 */
public class AesEncryptDecryptSample {

    // Objek Client instance KMS.
    private static Client client = null;

    public static void main(String[] args) {
        try {
            // Konstruksi objek Client instance layanan enkripsi.
            initClient();

            // Gunakan instance layanan enkripsi untuk contoh enkripsi dan dekripsi.
            encryptDecryptSample();

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

    public static void initClient() throws Exception {
        // Protokol koneksi. Atur nilainya menjadi https. Layanan instance KMS hanya mengizinkan akses melalui protokol HTTPS.
        Config config = new Config();
        config.setProtocol("https");
    
        // Client Key.
        config.setClientKeyFile("<CLIENT_KEY_FILE>");
     
         // Password Client Key.
        config.setPassword("<PASSWORD>");
       
         // Titik akhir instance KMS Anda. Atur nilainya dalam format berikut: <KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com.
        config.setEndpoint("<ENDPOINT>");
        
        // Sertifikat otoritas sertifikat (CA) instance KMS. Anda dapat menentukan path ke file sertifikat CA atau memasukkan isi dari sertifikat CA.
        config.setCaFilePath("<CA_CERTIFICATE_PATH>");
        // Sebagai alternatif, atur isi sertifikat CA instance KMS
        //config.setCa("<CA_CERTIFICATE_CONTENT");
        client = new Client(config);
    }

    // Contoh enkripsi dan dekripsi.
    private static void encryptDecryptSample() {
        String keyId = "<KEY_ID>";
        String plaintext = "<PLAINTEXT>";
        final AesEncryptContext aesEncryptContext = encryptSample(keyId, plaintext);
        String decryptResult = decryptSample(aesEncryptContext);
        if (!plaintext.equals(decryptResult)) {
            System.out.println("Data hasil dekripsi tidak sesuai dengan teks biasa");
        }
    }

    // Contoh enkripsi.
    private static AesEncryptContext encryptSample(String keyId, String plaintext) {
        // Konstruksi permintaan enkripsi.
        EncryptRequest encryptRequest = new EncryptRequest();
        encryptRequest.setKeyId(keyId);
        encryptRequest.setPlaintext(plaintext.getBytes(StandardCharsets.UTF_8));
        try {
            // Panggil antarmuka enkripsi untuk mengenkripsi.
            // Untuk mengabaikan sertifikat server, Anda dapat menggunakan kode yang dikomentari di sini untuk memanggil.
            //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("err enkripsi: %s%n", e.getMessage());
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    // Contoh dekripsi.
    private static String decryptSample(final AesEncryptContext aesEncryptContext) {
        // Konstruksi objek permintaan dekripsi.
        DecryptRequest decryptRequest = new DecryptRequest();
        decryptRequest.setKeyId(aesEncryptContext.getKeyId());
        decryptRequest.setCiphertextBlob(aesEncryptContext.getCiphertextBlob());
        decryptRequest.setAlgorithm(aesEncryptContext.getAlgorithm());
        decryptRequest.setIv(aesEncryptContext.getIv());
        try {
            // Panggil antarmuka dekripsi untuk mendekripsi.
            // Untuk mengabaikan sertifikat server, Anda dapat menggunakan kode yang dikomentari di sini untuk memanggil.
            //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("err dekripsi: %s%n", e.getMessage());
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * Konteks enkripsi AES mungkin disimpan.
     */
    static class AesEncryptContext implements Serializable {
        public String keyId;
        public byte[] ciphertextBlob;
        public byte[] iv;
        /**
         * Gunakan nilai algoritma default, jika nilai tidak diatur.
         */
        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;
        }

    }
}

Penjelasan contoh

Inisialisasi client

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

                           
 public static void initClient() throws Exception {

        // Protokol koneksi. Setel nilainya menjadi https. Layanan instance KMS hanya mengizinkan akses melalui protokol HTTPS.
        Config config = new Config();
        config.setProtocol("https");
    
        // Client key.
        config.setClientKeyFile("<CLIENT_KEY_FILE>");
     
         // Password client key.
        config.setPassword("<PASSWORD>");
       
         // Titik akhir instance KMS Anda. Setel nilainya dalam format berikut: <KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com.
        config.setEndpoint("<ENDPOINT>");
        
        // Sertifikat otoritas sertifikat (CA) instance KMS. Anda dapat menentukan path ke file sertifikat CA atau memasukkan isi dari sertifikat CA.
        config.setCaFilePath("<CA_CERTIFICATE_PATH>");
        // Sebagai alternatif, setel isi sertifikat CA instance KMS.
        //config.setCa("<CA_CERTIFICATE_CONTENT");
        client = new Client(config);
    }

Panggil API Encrypt untuk mengenkripsi data menggunakan kunci simetris

Saat menggunakan Encrypt untuk mengamankan data, pastikan menyimpan ciphertext yang dihasilkan (CiphertextBlob), ID kunci (KeyId), Iv, dan parameter algoritma enkripsi (Algorithm).

 // Contoh enkripsi.
    private static AesEncryptContext encryptSample(String keyId, String plaintext) {
        // Konstruksi permintaan enkripsi.
        EncryptRequest encryptRequest = new EncryptRequest();
        encryptRequest.setKeyId(keyId);
        encryptRequest.setPlaintext(plaintext.getBytes(StandardCharsets.UTF_8));
        try {
            // Panggil antarmuka enkripsi untuk mengenkripsi.
            // Untuk mengabaikan sertifikat server, Anda dapat menggunakan kode yang dikomentari di sini untuk memanggil.
            //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("err enkripsi: %s%n", e.getMessage());
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

Panggil Decrypt API untuk mendekripsi ciphertext menggunakan kunci simetris

     // Contoh dekripsi.
    private static String decryptSample(final AesEncryptContext aesEncryptContext) {
        // Konstruksi objek permintaan dekripsi.
        DecryptRequest decryptRequest = new DecryptRequest();
        decryptRequest.setKeyId(aesEncryptContext.getKeyId());
        decryptRequest.setCiphertextBlob(aesEncryptContext.getCiphertextBlob());
        decryptRequest.setAlgorithm(aesEncryptContext.getAlgorithm());
        decryptRequest.setIv(aesEncryptContext.getIv());
        try {
            // Panggil antarmuka dekripsi untuk mendekripsi.
            // Untuk mengabaikan sertifikat server, Anda dapat menggunakan kode yang dikomentari di sini untuk memanggil.
            //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("err dekripsi: %s%n", e.getMessage());
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }