创建密钥属于管控类操作,仅支持通过共享网关调用。本文介绍如何使用阿里云SDK通过共享网关创建密钥。
涉及的OpenAPI
CreateKey:创建密钥。
完整代码示例
代码示例解析
初始化客户端
public static com.aliyun.kms20160120.Client createClient() throws Exception {
// 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// Endpoint 请参考 https://api.aliyun.com/product/Kms
config.endpoint = "kms.cn-hangzhou.aliyuncs.com";
return new com.aliyun.kms20160120.Client(config);
}
调用CreateKey接口创建密钥
示例中的KeyUsage、Origin、EnableAutomaticRotation、DKMSInstanceId取值仅为参考,使用时请以您的实际业务为准。
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.CreateKeyRequest createKeyRequest = new com.aliyun.kms20160120.models.CreateKeyRequest()
.setKeyUsage("ENCRYPT/DECRYPT")
.setOrigin("Aliyun_KMS")
.setEnableAutomaticRotation(false)
.setDKMSInstanceId("kst-hzz65f176a0ogplgq****");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// 复制代码运行请自行打印 API 的返回值
client.createKeyWithOptions(createKeyRequest, runtime);
} catch (TeaException error) {
// 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
// 错误 message
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);
// 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
// 错误 message
System.out.println(error.getMessage());
// 诊断地址
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
该文章对您有帮助吗?
- 本页导读 (1)
- 涉及的OpenAPI
- 完整代码示例
- 代码示例解析
- 初始化客户端
- 调用CreateKey接口创建密钥