全部产品
Search
文档中心

Key Management Service:Contoh kode untuk enkripsi dan dekripsi

更新时间:Jul 02, 2025

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

Contoh lengkap

<?php

if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}

use AlibabaCloud\Dkms\Gcs\OpenApi\Util\Models\RuntimeOptions;
use AlibabaCloud\Dkms\Gcs\Sdk\Client as AlibabaCloudDkmsGcsSdkClient;
use AlibabaCloud\Dkms\Gcs\OpenApi\Models\Config as AlibabaCloudDkmsGcsOpenApiConfig;
use AlibabaCloud\Dkms\Gcs\Sdk\Models\DecryptRequest;
use AlibabaCloud\Dkms\Gcs\Sdk\Models\EncryptRequest;
use AlibabaCloud\Tea\Utils\Utils as AlibabaCloudTeaUtils;

/**
 * Parameter ClientKey mendukung tiga metode berikut:
 * 1. Dengan menentukan jalur 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);
 *
 * 2. Dengan menentukan konten ClientKey.
 * Contoh:
 *      String clientKeyContent = "<CLIENT_KEY_CONTENT>";
 *      String password = "<CLIENT_KEY_PASSWORD>";
 *      Config cfg = new Config();
 *      cfg.setClientKeyContent(clientKeyContent);
 *      cfg.setPassword(password);
 *
 * 3. Dengan menentukan kunci privat 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);
 *
 */

// Isi jalur file ClientKey yang Anda peroleh dari manajemen aplikasi KMS.
// $clientKeyFile = '<CLIENT_KEY_FILE_PATH>';

// Atau, isi konten file ClientKey yang Anda peroleh dari manajemen aplikasi KMS.
$clientKeyContent = '<CLIENT_KEY_CONTENT>';

// Isi kata sandi enkripsi yang Anda masukkan saat membuat ClientKey di manajemen aplikasi KMS.
$password = getenv('CLIENT_KEY_PASSWORD');

// Isi alamat VPC instance KMS Anda.
$endpoint = '<DKMS_INSTANCE_SERVICE_ADDRESS>';

// Isi ID kunci utama yang Anda buat di KMS.
$keyId = '<CMK_ID>';

// Algoritma enkripsi dan dekripsi.
$algorithm = '<ENCRYPT_ALGORITHM>';

// Plaintext yang akan dienkripsi.
$plaintext = '<ENCRYPT_PLAINTEXT>';

// Objek Client SDK instance KMS.
$client = getDkmsGcsSdkClient();
if (is_null($client)) exit(1);

// Contoh penggunaan KMS untuk enkripsi dan dekripsi kunci simetris.
aesEncryptDecryptSample();

/**
 * Contoh penggunaan instance KMS untuk enkripsi dan dekripsi.
 * @return void
 */
function aesEncryptDecryptSample()
{
    global $client, $keyId, $plaintext, $algorithm;

    $cipherCtx = aesEncryptSample($client, $keyId, $plaintext, $algorithm);
    if ($cipherCtx !== null) {
        $decryptResult = AlibabaCloudTeaUtils::toString(aesDecryptSample($client, $cipherCtx));
        if ($plaintext !== $decryptResult) {
            echo 'hasil dekripsi tidak sesuai dengan plaintext' . PHP_EOL;
        } else {
            echo 'aesEncryptDecryptSample berhasil' . PHP_EOL;
        }
    }
}

/**
 * Contoh enkripsi.
 * @param AlibabaCloudDkmsGcsSdkClient $client
 * @param string $keyId
 * @param string $plaintext
 * @param string $algorithm
 * @return AesEncryptContext
 */
function aesEncryptSample($client, $keyId, $plaintext, $algorithm)
{
    // Membuat permintaan enkripsi.
    $encryptRequest = new EncryptRequest();
    $encryptRequest->keyId = $keyId;
    $encryptRequest->algorithm = $algorithm;
    $encryptRequest->plaintext = AlibabaCloudTeaUtils::toBytes($plaintext);
    $runtimeOptions = new RuntimeOptions();
    // Abaikan sertifikat server.
    //$runtimeOptions->ignoreSSL = true;

    try {
        // Panggil API enkripsi untuk mengenkripsi.
        $encryptResponse = $client->encryptWithOptions($encryptRequest, $runtimeOptions);
        // Key ID.
        $keyId = $encryptResponse->keyId;
        // Saat kunci utama adalah kunci simetris, API decrypt memerlukan Iv yang dikembalikan oleh enkripsi.
        $iv = $encryptResponse->iv;
        // Data ciphertext.
        $cipher = $encryptResponse->ciphertextBlob;
        // Algoritma enkripsi.
        $algorithm = $encryptResponse->algorithm;
        var_dump($encryptResponse->toMap());
        return new AesEncryptContext([
            'keyId' => $keyId,
            'iv' => $iv,
            'ciphertextBlob' => $cipher,
            'algorithm' => $algorithm
        ]);
    } catch (\Exception $error) {
        if ($error instanceof \AlibabaCloud\Tea\Exception\TeaError) {
            var_dump($error->getErrorInfo());
        }
        var_dump($error->getMessage());
        var_dump($error->getTraceAsString());
    }
    return null;
}

/**
 * Contoh dekripsi.
 * @param AlibabaCloudDkmsGcsSdkClient $client
 * @param AesEncryptContext $ctx
 * @return int[]|null
 */
function aesDecryptSample($client, $ctx)
{
    // Membuat objek permintaan dekripsi.
    $decryptRequest = new DecryptRequest();
    $decryptRequest->keyId = $ctx->keyId;
    $decryptRequest->ciphertextBlob = $ctx->ciphertextBlob;
    $decryptRequest->algorithm = $ctx->algorithm;
    $decryptRequest->iv = $ctx->iv;
    $runtimeOptions = new RuntimeOptions();
    // Abaikan sertifikat.
    //$runtimeOptions->ignoreSSL = true;

    try {
        // Panggil API dekripsi untuk mendekripsi.
        $decryptResponse = $client->decryptWithOptions($decryptRequest, $runtimeOptions);
        var_dump($decryptResponse->toMap());
        return $decryptResponse->plaintext;
    } catch (Exception $error) {
        if ($error instanceof \AlibabaCloud\Tea\Exception\TeaError) {
            var_dump($error->getErrorInfo());
        }
        var_dump($error->getMessage());
        var_dump($error->getTraceAsString());
    }
    return null;
}

/**
 * Konstruksi objek Client SDK instance KMS.
 * @return AlibabaCloudDkmsGcsSdkClient
 */
function getDkmsGcsSdkClient()
{
    global $clientKeyContent, $password, $endpoint;

    // Konstruksi konfigurasi Client SDK instance KMS.
    $config = new AlibabaCloudDkmsGcsOpenApiConfig();
    // Setel protokol koneksi ke "https". Layanan instance KMS hanya mengizinkan akses melalui protokol HTTPS.
    $config->protocol = 'https';
    // Client Key.
    $config->clientKeyContent = $clientKeyContent;
    // Kata sandi Client Key.
    $config->password = $password;
    // Setel endpoint ke <your KMS Instance Id>.cryptoservice.kms.aliyuncs.com.
    $config->endpoint = $endpoint;
    // Sertifikat CA instance.
    $config->caFilePath = 'path/to/caCert.pem';

    // Konstruksi objek Client SDK instance KMS.
    return new AlibabaCloudDkmsGcsSdkClient($config);
}


/**
 * Konteks enkripsi AES mungkin disimpan.
 */
class AesEncryptContext
{
    public function __construct($config = [])
    {
        if (!empty($config)) {
            foreach ($config as $k => $v) {
                $this->{$k} = $v;
            }
        }
    }
    /**
     * @var string
     */
    public $keyId;

    /**
     * @var int[]
     */
    public $iv;

    /**
     * @var int[]
     */
    public $ciphertextBlob;

    /**
     * @var string
     * Gunakan nilai algoritma default, jika nilainya tidak disetel.
     */
    public $algorithm;
}

Penjelasan contoh

Inisialisasi client

<?php

use AlibabaCloud\Dkms\Gcs\Sdk\Client as AlibabaCloudDkmsGcsSdkClient;
use AlibabaCloud\Dkms\Gcs\OpenApi\Models\Config as AlibabaCloudDkmsGcsOpenApiConfig;


function getDkmsGcsSdkClient()
{
    global $clientKeyContent, $password, $endpoint;

    // Konstruksi konfigurasi client SDK instance KMS.
    $config = new AlibabaCloudDkmsGcsOpenApiConfig();
    // Protokol koneksi. Setel nilainya ke https. Layanan instance KMS hanya mengizinkan akses melalui protokol HTTPS.
    $config->protocol = 'https';
    // Client Key.
    $config->clientKeyContent = $clientKeyContent;
    // Token keamanan Client Key.
    $config->password = $password;
    // Endpoint instance KMS Anda. Setel nilainya dalam format berikut: <ID instance KMS Anda>.cryptoservice.kms.aliyuncs.com.
    $config->endpoint = $endpoint;
    // Sertifikat CA instance.
    $config->caFilePath = 'path/to/caCert.pem';

    // Konstruksi objek client SDK instance KMS.
    return new AlibabaCloudDkmsGcsSdkClient($config);
}

Panggil API Encrypt untuk mengenkripsi data menggunakan kunci simetris

/**
 * Contoh enkripsi
 * @param AlibabaCloudDkmsGcsSdkClient $client
 * @param string $keyId
 * @param string $plaintext
 * @param string $algorithm
 * @return AesEncryptContext
 */
function aesEncryptSample($client, $keyId, $plaintext, $algorithm)
{
    // Membuat permintaan enkripsi
    $encryptRequest = new EncryptRequest();
    $encryptRequest->keyId = $keyId;
    $encryptRequest->algorithm = $algorithm;
    $encryptRequest->plaintext = AlibabaCloudTeaUtils::toBytes($plaintext);
    $runtimeOptions = new RuntimeOptions();
    // Abaikan sertifikat server
    //$runtimeOptions->ignoreSSL = true;

    try {
        // Panggil API enkripsi untuk mengenkripsi
        $encryptResponse = $client->encryptWithOptions($encryptRequest, $runtimeOptions);
        // Key ID
        $keyId = $encryptResponse->keyId;
        // Saat kunci utama adalah kunci simetris, API decrypt memerlukan Iv yang dikembalikan oleh enkripsi
        $iv = $encryptResponse->iv;
        // Data ciphertext
        $cipher = $encryptResponse->ciphertextBlob;
        // Algoritma enkripsi
        $algorithm = $encryptResponse->algorithm;
        var_dump($encryptResponse->toMap());
        return new AesEncryptContext([
            'keyId' => $keyId,
            'iv' => $iv,
            'ciphertextBlob' => $cipher,
            'algorithm' => $algorithm
        ]);
    } catch (\Exception $error) {
        if ($error instanceof \AlibabaCloud\Tea\Exception\TeaError) {
            var_dump($error->getErrorInfo());
        }
        var_dump($error->getMessage());
        var_dump($error->getTraceAsString());
    }
    return null;
}

Panggil API Decrypt untuk mendekripsi ciphertext menggunakan kunci simetris

/**
 * Contoh dekripsi
 * @param AlibabaCloudDkmsGcsSdkClient $client
 * @param AesEncryptContext $ctx
 * @return int[]|null
 */
function aesDecryptSample($client, $ctx)
{
    // Membuat objek permintaan dekripsi
    $decryptRequest = new DecryptRequest();
    $decryptRequest->keyId = $ctx->keyId;
    $decryptRequest->ciphertextBlob = $ctx->ciphertextBlob;
    $decryptRequest->algorithm = $ctx->algorithm;
    $decryptRequest->iv = $ctx->iv;
    $runtimeOptions = new RuntimeOptions();
    // Abaikan sertifikat
    //$runtimeOptions->ignoreSSL = true;

    try {
        // Panggil API dekripsi untuk mendekripsi
        $decryptResponse = $client->decryptWithOptions($decryptRequest, $runtimeOptions);
        var_dump($decryptResponse->toMap());
        return $decryptResponse->plaintext;
    } catch (Exception $error) {
        if ($error instanceof \AlibabaCloud\Tea\Exception\TeaError) {
            var_dump($error->getErrorInfo());
        }
        var_dump($error->getMessage());
        var_dump($error->getTraceAsString());
    }
    return null;
}