すべてのプロダクト
Search
ドキュメントセンター

Key Management Service:暗号化と復号化のサンプルコード

最終更新日:Feb 07, 2025

暗号化と復号化は、共有ゲートウェイまたは専用ゲートウェイのいずれかを介して実行できるビジネス操作です。 このトピックでは、Alibaba Cloud SDKで暗号化および復号化に対称キーを使用する方法について説明します。

関連するOpenAPI

  • 暗号化: 対称キーを使用してデータを暗号化します。

  • Decrypt: 対称キーを使用して暗号文データを復号します。

共有ゲートウェイと専用ゲートウェイの構成の違い

共有ゲートウェイと専用ゲートウェイの使用の唯一の違いは、クライアント初期化の設定です。

パラメーター

共有ゲートウェイ

専用ゲートウェイ

endpoint

共有ゲートウェイエンドポイントは、次のいずれかの形式で設定する必要があります。

  • パブリックネットワークドメイン名: kms.<REGION_ID>.aliyuncs.com

  • VPCドメイン名: kms-vpc.<REGION_ID>.aliyuncs.com

専用ゲートウェイエンドポイントは、<KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.comの形式で設定する必要があります。

ca

不要。

  • Alibaba Cloud SDK V2.0: CA証明書の設定が必要です。

  • Alibaba Cloud SDK V1.0: 証明書をサポートしていません。 代わりに、HTTPSInsecureランタイムパラメーターをtrueに設定する必要があります: client.SetHTTPSInsecure(true)

共有ゲートウェイを介した暗号化と復号化

完全な例

暗号化

package com.aliyun.sample;

import com.aliyun.tea.*;

public class Sample {

    /**
     * <b>description</b> :
     * <p>Use your AccessKey ID and AccessKey secret to initialize the client.</p>
     * @return Client
     * 
     * @throws Exception
     */
    public static com.aliyun.kms20160120.Client createClient() throws Exception {
        // If the project code is leaked, the AccessKey pair may be leaked and resources in your account become insecure. The following code is for reference only.
        // We recommend that you use Security Token Service (STS) tokens, which provide higher security. For more information about authentication methods, see https://www.alibabacloud.com/help/en/sdk/developer-reference/v2-manage-access-credentials.
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // For information about the endpoint, see https://api.alibabacloud.com/product/Kms.
        config.endpoint = "kms.ap-southeast-1.aliyuncs.com";
        return new com.aliyun.kms20160120.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.kms20160120.Client client = Sample.createClient();
        com.aliyun.kms20160120.models.EncryptRequest encryptRequest = new com.aliyun.kms20160120.models.EncryptRequest()
                .setPlaintext("MzcyOTI5MTk5MTEyNDU3****")
                .setKeyId("key-hzz65f17868e6cl0n****");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // If you copy and run the sample code, write your own code to display the response of the API operation if necessary
            client.encryptWithOptions(encryptRequest, runtime);
        } catch (TeaException error) {
            // In this example, errors are printed. In your actual project, process errors based on your business requirements.
            // Print error messages
            System.out.println(error.getMessage());
            // Provide the URL for troubleshooting
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // In this example, errors are printed. In your actual project, process errors based on your business requirements.
            // Print error messages
            System.out.println(error.getMessage());
            // Provide the URL for troubleshooting
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }        
    }
}

解読

package com.aliyun.sample;

import com.aliyun.tea.*;

public class Sample {

    /**
     * <b>description</b> :
     * <p>Use your AccessKey ID and AccessKey secret to initialize the client.</p>
     * @return Client
     * 
     * @throws Exception
     */
    public static com.aliyun.kms20160120.Client createClient() throws Exception {
        // If the project code is leaked, the AccessKey pair may be leaked and resources in your account become insecure. The following code is for reference only.
        // We recommend that you use Security Token Service (STS) tokens, which provide higher security. For more information about authentication methods, see https://www.alibabacloud.com/help/en/sdk/developer-reference/v2-manage-access-credentials.
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // For information about the endpoint, see https://api.alibabacloud.com/product/Kms.
        config.endpoint = "kms.ap-southeast-1.aliyuncs.com";
        return new com.aliyun.kms20160120.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.kms20160120.Client client = Sample.createClient();
        com.aliyun.kms20160120.models.DecryptRequest decryptRequest = new com.aliyun.kms20160120.models.DecryptRequest()
                .setCiphertextBlob("a2V5LWh6ejY1Zj****");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // If you copy and run the sample code, write your own code to display the response of the API operation if necessary
            client.decryptWithOptions(decryptRequest, runtime);
        } catch (TeaException error) {
            // In this example, errors are printed. In your actual project, process errors based on your business requirements.
            // Print error messages
            System.out.println(error.getMessage());
            // Provide the URL for troubleshooting
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // In this example, errors are printed. In your actual project, process errors based on your business requirements.
            // Print error messages
            System.out.println(error.getMessage());
            // Provide the URL for troubleshooting
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }        
    }
}

サンプル分析

クライアントの初期化

    public static com.aliyun.kms20160120.Client createClient() throws Exception {
        // If the project code is leaked, the AccessKey pair may be leaked and resources in your account become insecure. The following code is for reference only.
        // We recommend that you use Security Token Service (STS) tokens, which provide higher security. For more information about authentication methods, see https://www.alibabacloud.com/help/en/sdk/developer-reference/v2-manage-access-credentials..
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // For information about the endpoint, see https://api.alibabacloud.com/product/Kms.
        config.endpoint = "kms.ap-southeast-1.aliyuncs.com";
        return new com.aliyun.kms20160120.Client(config);
    }

対称キーを使用してデータを暗号化するEncrypt操作の呼び出し

この例で提供されているPlaintextとKeyIdの値は参照用です。 ビジネスニーズに基づいて実際のものと交換してください。

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.kms20160120.Client client = Sample.createClient();
        com.aliyun.kms20160120.models.EncryptRequest encryptRequest = new com.aliyun.kms20160120.models.EncryptRequest()
                .setPlaintext("MzcyOTI5MTk5MTEyNDU****")
                .setKeyId("key-hzz65f17868e6cl0n****");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // If you copy and run the sample code, write your own code to display the response of the API operation if necessary
            client.encryptWithOptions(encryptRequest, runtime);
        } catch (TeaException error) {
            // In this example, errors are printed. In your actual project, process errors based on your business requirements.
            // Print error messages
            System.out.println(error.getMessage());
            // Provide the URL for troubleshooting
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // In this example, errors are printed. In your actual project, process errors based on your business requirements.
            // Print error messages
            System.out.println(error.getMessage());
            // Provide the URL for troubleshooting
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }        
    }

対称キーを使用して暗号文を復号化するためのDecrypt操作の呼び出し

この例で提供されているCiphertextBlobの値は参照用です。 ビジネスニーズに基づいて実際のものと交換してください。

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.kms20160120.Client client = Sample.createClient();
        com.aliyun.kms20160120.models.DecryptRequest decryptRequest = new com.aliyun.kms20160120.models.DecryptRequest()
                .setCiphertextBlob("a2V5LWh6ejY1Zj****");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // If you copy and run the sample code, write your own code to display the response of the API operation if necessary
            client.decryptWithOptions(decryptRequest, runtime);
        } catch (TeaException error) {
            // In this example, errors are printed. In your actual project, process errors based on your business requirements.
            // Print error messages
            System.out.println(error.getMessage());
            // Provide the URL for troubleshooting
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // In this example, errors are printed. In your actual project, process errors based on your business requirements.
            // Print error messages
            System.out.println(error.getMessage());
            // Provide the URL for troubleshooting
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }        
    }

暗号化と専用ゲートウェイを介した復号化

完全な例

暗号化

package com.aliyun.sample;

import com.aliyun.tea.*;

public class Sample {

    /**
     * <b>description</b> :
     * <p>Use your AccessKey ID and AccessKey secret to initialize the client.</p>
     * @return Client
     * 
     * @throws Exception
     */
    public static com.aliyun.kms20160120.Client createClient() throws Exception {
        // If the project code is leaked, the AccessKey pair may be leaked and resources in your account become insecure. The following code is for reference only.
        // We recommend that you use Security Token Service (STS) tokens, which provide higher security. For more information about authentication methods, see https://www.alibabacloud.com/help/en/sdk/developer-reference/v2-manage-access-credentials.
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Dedicated gateway endpoint 
        config.endpoint = "kst-hzz65f176a0ogplgq****.cryptoservice.kms.aliyuncs.com";
        //KMS instance CA certificate
        config.ca = "-----BEGIN CERTIFICATE-----MIIDuzCCAqOgAwIBAgIJALTKwWAjvbMiMA0GCS****";
        return new com.aliyun.kms20160120.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.kms20160120.Client client = Sample.createClient();
        com.aliyun.kms20160120.models.EncryptRequest encryptRequest = new com.aliyun.kms20160120.models.EncryptRequest()
                .setPlaintext("MzcyOTI5MTk5MTEyNDU3****")
                .setKeyId("key-hzz65f17868e6cl0n****");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // If you copy and run the sample code, write your own code to display the response of the API operation if necessary
            client.encryptWithOptions(encryptRequest, runtime);
        } catch (TeaException error) {
            // In this example, errors are printed. In your actual project, process errors based on your business requirements.
            // Print error messages
            System.out.println(error.getMessage());
            // Provide the URL for troubleshooting
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // In this example, errors are printed. In your actual project, process errors based on your business requirements.
            // Print error messages
            System.out.println(error.getMessage());
            // Provide the URL for troubleshooting
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }        
    }
}

解読

package com.aliyun.sample;

import com.aliyun.tea.*;

public class Sample {

    /**
     * <b>description</b> :
     * <p>Use your AccessKey ID and AccessKey secret to initialize the client.</p>
     * @return Client
     * 
     * @throws Exception
     */
    public static com.aliyun.kms20160120.Client createClient() throws Exception {
        // If the project code is leaked, the AccessKey pair may be leaked and resources in your account become insecure. The following code is for reference only.
        // We recommend that you use Security Token Service (STS) tokens, which provide higher security. For more information about authentication methods, see https://www.alibabacloud.com/help/en/sdk/developer-reference/v2-manage-access-credentials.
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Dedicated gateway endpoint 
        config.endpoint = "kst-hzz65f176a0ogplgq****.cryptoservice.kms.aliyuncs.com";
        //KMS instance CA certificate
        config.ca = "-----BEGIN CERTIFICATE-----MIIDuzCCAqOgAwIBAgIJALTKwWAjvbMiMA0GCS****";
        return new com.aliyun.kms20160120.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.kms20160120.Client client = Sample.createClient();
        com.aliyun.kms20160120.models.DecryptRequest decryptRequest = new com.aliyun.kms20160120.models.DecryptRequest()
                .setCiphertextBlob("a2V5LWh6ejY1Zj****");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // If you copy and run the sample code, write your own code to display the response of the API operation if necessary
            client.decryptWithOptions(decryptRequest, runtime);
        } catch (TeaException error) {
            // In this example, errors are printed. In your actual project, process errors based on your business requirements.
            // Print error messages
            System.out.println(error.getMessage());
            // Provide the URL for troubleshooting
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // In this example, errors are printed. In your actual project, process errors based on your business requirements.
            // Print error messages
            System.out.println(error.getMessage());
            // Provide the URL for troubleshooting
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }        
    }
}

サンプル分析

クライアントの初期化

    public static com.aliyun.kms20160120.Client createClient() throws Exception {
        // If the project code is leaked, the AccessKey pair may be leaked and resources in your account become insecure. The following code is for reference only.
        // We recommend that you use Security Token Service (STS) tokens, which provide higher security. For more information about authentication methods, see https://www.alibabacloud.com/help/en/sdk/developer-reference/v2-manage-access-credentials.
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Dedicated gateway endpoint 
        config.endpoint = "kst-hzz65f176a0ogplgq****.cryptoservice.kms.aliyuncs.com";
        //KMS instance CA certificate
        config.ca = "-----BEGIN CERTIFICATE-----MIIDuzCCAqOgAwIBAgIJALTKwWAjvbMiMA0GCS****";
        return new com.aliyun.kms20160120.Client(config);
    }

対称キーを使用してデータを暗号化するEncrypt操作の呼び出し

この例で提供されているPlaintextとKeyIdの値は参照用です。 ビジネスニーズに基づいて実際のものと交換してください。

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.kms20160120.Client client = Sample.createClient();
        com.aliyun.kms20160120.models.EncryptRequest encryptRequest = new com.aliyun.kms20160120.models.EncryptRequest()
                .setPlaintext("MzcyOTI5MTk5MTEyNDU****")
                .setKeyId("key-hzz65f17868e6cl0n****");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // If you copy and run the sample code, write your own code to display the response of the API operation if necessary
            client.encryptWithOptions(encryptRequest, runtime);
        } catch (TeaException error) {
            // In this example, errors are printed. In your actual project, process errors based on your business requirements.
            // Print error messages
            System.out.println(error.getMessage());
            // Provide the URL for troubleshooting
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // In this example, errors are printed. In your actual project, process errors based on your business requirements.
            // Print error messages
            System.out.println(error.getMessage());
            // Provide the URL for troubleshooting
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }        
    }

対称キーを使用して暗号文を復号化するためのDecrypt操作の呼び出し

この例で提供されているCiphertextBlobの値は参照用です。 ビジネスニーズに基づいて実際のものと交換してください。

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.kms20160120.Client client = Sample.createClient();
        com.aliyun.kms20160120.models.DecryptRequest decryptRequest = new com.aliyun.kms20160120.models.DecryptRequest()
                .setCiphertextBlob("a2V5LWh6ejY1Zj****");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // If you copy and run the sample code, write your own code to display the response of the API operation if necessary
            client.decryptWithOptions(decryptRequest, runtime);
        } catch (TeaException error) {
            // In this example, errors are printed. In your actual project, process errors based on your business requirements.
            // Print error messages
            System.out.println(error.getMessage());
            // Provide the URL for troubleshooting
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // In this example, errors are printed. In your actual project, process errors based on your business requirements.
            // Print error messages
            System.out.println(error.getMessage());
            // Provide the URL for troubleshooting
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }        
    }