Setelah menginisialisasi SDK klien instance KMS, Anda dapat menggunakannya untuk memanggil API GetSecretValue guna mengambil nilai rahasia. Topik ini menyediakan contoh kode untuk proses tersebut.
Contoh lengkap
Penjelasan contoh
Inisialisasi klien
import com.aliyun.dkms.gcs.openapi.models.Config;
import com.aliyun.dkms.gcs.sdk.Client;
public static void initClient() throws Exception {
// Protokol koneksi. Atur nilainya ke https. Layanan instance KMS hanya mengizinkan akses melalui protokol HTTPS.
Config config = new Config();
config.setProtocol("https");
// Kunci klien.
config.setClientKeyFile("<CLIENT_KEY_FILE>");
// Kata sandi kunci klien.
config.setPassword("<PASSWORD>");
// Endpoint instance KMS Anda. Atur nilainya dalam format berikut: <KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com.
config.setEndpoint("<ENDPOINT>");
// Sertifikat otoritas sertifikat (CA) dari instance KMS. Anda dapat menentukan jalur ke file sertifikat CA atau memasukkan konten sertifikat CA.
config.setCaFilePath("<CA_CERTIFICATE_PATH>");
// Sebagai alternatif, atur konten sertifikat CA dari instance KMS.
//config.setCa("<CA_CERTIFICATE_CONTENT");
client = new Client(config);
}Panggil API GetSecretValue
/**
* Contoh pengambilan nilai rahasia.
* @param secretName
*/
private static void getSecretValueSample(String secretName) {
GetSecretValueRequest request = new GetSecretValueRequest()
.setSecretName(secretName);
try {
// Jika Anda perlu mengabaikan sertifikat server, Anda dapat menggunakan kode yang dikomentari di sini untuk memanggil
//RuntimeOptions runtimeOptions = new RuntimeOptions();
//runtimeOptions.setIgnoreSSL(true);
//GetSecretValueResponse getSecretValueResponse = client.getSecretValueWithOptions(request, runtimeOptions);
GetSecretValueResponse getSecretValueResponse = client.getSecretValue(request);
System.out.printf("Nama Rahasia: %s%n", getSecretValueResponse.getSecretName());
// System.out.printf("Data Rahasia: %s%n", getSecretValueResponse.getSecretData());
System.out.printf("Tahap Versi: %s%n", getSecretValueResponse.getVersionStages());
System.out.printf("ID Permintaan: %s%n", getSecretValueResponse.getRequestId());
} catch (Exception e) {
if (e instanceof TeaException) {
System.out.printf("Kode: %s%n", ((TeaException) e).getCode());
System.out.printf("Pesan: %s%n", ((TeaException) e).getMessage());
System.out.printf("HttpCode: %s%n", ((TeaException) e).getData().get("httpCode"));
System.out.printf("HostId: %s%n", ((TeaException) e).getData().get("hostId"));
System.out.printf("RequestId: %s%n", ((TeaException) e).getData().get("requestId"));
}
e.printStackTrace();
}
}
}