Signature and verification examples

更新时间:
复制 MD 格式

Use the Alibaba Cloud SDK to generate and verify digital signatures with an asymmetric key stored in KMS. The SDK supports access to both shared and dedicated gateways.

Related OpenAPI

Gateway configuration differences

The only difference between shared and dedicated gateway usage is how you initialize the client:

ParameterShared gatewayDedicated gateway
endpointPublic network: kms.<REGION_ID>.aliyuncs.com<br>VPC: kms-vpc.<REGION_ID>.aliyuncs.com<br>See shared gateway endpoints.<KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com<br>See dedicated gateway endpoints.
caNot required.SDK V2.0: Set a CA certificate.<br>SDK V1.0: Does not support certificates. Set HTTPSInsecure to true via client.SetHTTPSInsecure(true).

Sign and verify through a shared gateway

Signature generation

package com.aliyun.sample;

import com.aliyun.tea.*;

public class Sample {

    public static com.aliyun.kms20160120.Client createClient() throws Exception {
        // Store credentials in environment variables to avoid hardcoding them in source code.
        // For higher security, use Security Token Service (STS) tokens instead of long-term AccessKey credentials.
        // 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()
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Shared gateway 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.AsymmetricSignRequest asymmetricSignRequest =
                new com.aliyun.kms20160120.models.AsymmetricSignRequest()
                        .setKeyId("key-hzz678f09e1tkzqh1****")
                        .setKeyVersionId("key-hzz678f09e1tkzqh1****-p62byk****")
                        .setAlgorithm("RSA_PKCS1_SHA_256")
                        .setDigest("ZOyIygCyaOW6GjVnihtTFtIS9PNmskdyMlNKiuy****=");
        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.asymmetricSignWithOptions(asymmetricSignRequest, runtime);
        } catch (TeaException error) {
            System.out.println(error.getMessage());
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            System.out.println(error.getMessage());
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}

Signature verification

package com.aliyun.sample;

import com.aliyun.tea.*;

public class Sample {

    public static com.aliyun.kms20160120.Client createClient() throws Exception {
        // Store credentials in environment variables to avoid hardcoding them in source code.
        // For higher security, use Security Token Service (STS) tokens instead of long-term AccessKey credentials.
        // 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()
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Shared gateway 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.AsymmetricVerifyRequest asymmetricVerifyRequest =
                new com.aliyun.kms20160120.models.AsymmetricVerifyRequest()
                        .setKeyId("key-hzz678f09e1tkzqh1****")
                        .setKeyVersionId("key-hzz678f09e1tkzqh1****-p62byk****")
                        .setAlgorithm("RSA_PKCS1_SHA_256")
                        .setDigest("ZOyIygCyaOW6GjVnihtTFtIS9PNmskdyMlNKiuy****=")
                        .setValue("M2CceNZH00ZgL9ED/ZHFp21YRAvYe****");
        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.asymmetricVerifyWithOptions(asymmetricVerifyRequest, runtime);
        } catch (TeaException error) {
            System.out.println(error.getMessage());
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            System.out.println(error.getMessage());
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}

Code walkthrough

Initialize the client

public static com.aliyun.kms20160120.Client createClient() throws Exception {
    com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
            .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
            .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
    config.endpoint = "kms.ap-southeast-1.aliyuncs.com";
    return new com.aliyun.kms20160120.Client(config);
}

Credentials are read from environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET. Replace the endpoint with the endpoint for your region.

Call AsymmetricSign to generate a signature

Replace the KeyId, KeyVersionId, Algorithm, and Digest values with your own.

com.aliyun.kms20160120.models.AsymmetricSignRequest asymmetricSignRequest =
        new com.aliyun.kms20160120.models.AsymmetricSignRequest()
                .setKeyId("key-hzz678f09e1tkzqh1****")
                .setKeyVersionId("key-hzz678f09e1tkzqh1****-p62byk****")
                .setAlgorithm("RSA_PKCS1_SHA_256")
                .setDigest("ZOyIygCyaOW6GjVnihtTFtIS9PNmskdyMlNKiuy****=");
client.asymmetricSignWithOptions(asymmetricSignRequest, runtime);

Call AsymmetricVerify to verify a signature

Replace the KeyId, KeyVersionId, Algorithm, Digest, and Value parameters with your own. The Value parameter is the signature returned by AsymmetricSign.

com.aliyun.kms20160120.models.AsymmetricVerifyRequest asymmetricVerifyRequest =
        new com.aliyun.kms20160120.models.AsymmetricVerifyRequest()
                .setKeyId("key-hzz678f09e1tkzqh1****")
                .setKeyVersionId("key-hzz678f09e1tkzqh1****-p62byk****")
                .setAlgorithm("RSA_PKCS1_SHA_256")
                .setDigest("ZOyIygCyaOW6GjVnihtTFtIS9PNmskdyMlNKiuy****=")
                .setValue("M2CceNZH00ZgL9ED/ZHFp21YRAvYe****");
client.asymmetricVerifyWithOptions(asymmetricVerifyRequest, runtime);

Sign and verify through a dedicated gateway

The dedicated gateway examples differ from the shared gateway examples only in client initialization: the endpoint uses the KMS instance ID format and a CA certificate is required.

Signature generation

package com.aliyun.sample;

import com.aliyun.tea.*;

public class Sample {

    public static com.aliyun.kms20160120.Client createClient() throws Exception {
        // Store credentials in environment variables to avoid hardcoding them in source code.
        // For higher security, use Security Token Service (STS) tokens instead of long-term AccessKey credentials.
        // 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()
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                .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.AsymmetricSignRequest asymmetricSignRequest =
                new com.aliyun.kms20160120.models.AsymmetricSignRequest()
                        .setKeyId("key-hzz678f09e1tkzqh1****")
                        .setKeyVersionId("key-hzz678f09e1tkzqh1****-p62byk****")
                        .setAlgorithm("RSA_PKCS1_SHA_256")
                        .setDigest("ZOyIygCyaOW6GjVnihtTFtIS9PNmskdyMlNKiuy****=");
        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.asymmetricSignWithOptions(asymmetricSignRequest, runtime);
        } catch (TeaException error) {
            System.out.println(error.getMessage());
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            System.out.println(error.getMessage());
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}

Signature verification

package com.aliyun.sample;

import com.aliyun.tea.*;

public class Sample {

    public static com.aliyun.kms20160120.Client createClient() throws Exception {
        // Store credentials in environment variables to avoid hardcoding them in source code.
        // For higher security, use Security Token Service (STS) tokens instead of long-term AccessKey credentials.
        // 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()
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                .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.AsymmetricVerifyRequest asymmetricVerifyRequest =
                new com.aliyun.kms20160120.models.AsymmetricVerifyRequest()
                        .setKeyId("key-hzz678f09e1tkzqh1****")
                        .setKeyVersionId("key-hzz678f09e1tkzqh1****-p62byk****")
                        .setAlgorithm("RSA_PKCS1_SHA_256")
                        .setDigest("ZOyIygCyaOW6GjVnihtTFtIS9PNmskdyMlNKiuy****=")
                        .setValue("M2CceNZH00ZgL9ED/ZHFp21YRAvYe****");
        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.asymmetricVerifyWithOptions(asymmetricVerifyRequest, runtime);
        } catch (TeaException error) {
            System.out.println(error.getMessage());
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            System.out.println(error.getMessage());
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}

Code walkthrough

Initialize the client

public static com.aliyun.kms20160120.Client createClient() throws Exception {
    com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
            .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
            .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);
}

Replace the endpoint with your KMS instance ID and set config.ca to your KMS instance's CA certificate.

Call AsymmetricSign and AsymmetricVerify

The API call parameters are the same as in the shared gateway example. Only the client initialization differs.