初始化KMS实例SDK客户端后,您可以通过客户端调用GetSecretValue接口获取凭据值。本文介绍获取凭据值的代码示例。
完整代码示例
调用GetSecretValue接口获取凭据值。
源码github地址:GetSecretValueSample.java
代码示例解析
初始化客户端
关于初始化客户端的详细介绍,请参见初始化客户端。
import com.aliyun.dkms.gcs.openapi.models.Config;
import com.aliyun.dkms.gcs.sdk.Client;
                           
 public static void initClient() throws Exception {
        // 连接协议请设置为"https"。KMS实例服务仅允许通过HTTPS协议访问。
        Config config = new Config();
        config.setProtocol("https");
    
        // Client Key。
        config.setClientKeyFile("<your-client-key-file>");
     
         // Client Key口令。
        config.setPassword("<your-password>");
       
         // 设置endpoint为<your KMS Instance Id>.cryptoservice.kms.aliyuncs.com。
        config.setEndpoint("<your-endpoint>");
        
        // KMS实例的CA证书,可通过文件路径或直接设置内容。
        config.setCaFilePath("<path/to/yourCaCert>");
        // 或者,设置为KMS实例的CA证书内容
        //config.setCa("<your-ca-certificate-content");
        client = new Client(config);
    }调用GetSecretValue接口获取凭据值
    /**
     * 获取凭据示例
     * @param secretName
     */
    private static void getSecretValueSample(String secretName) {
        GetSecretValueRequest request = new GetSecretValueRequest()
                .setSecretName(secretName);
        try {
            // 如需忽略服务端证书,可使用此处注释代码方式调用
            //RuntimeOptions runtimeOptions = new RuntimeOptions();
            //runtimeOptions.setIgnoreSSL(true);
            //GetSecretValueResponse getSecretValueResponse = client.getSecretValueWithOptions(request, runtimeOptions);
            GetSecretValueResponse getSecretValueResponse = client.getSecretValue(request);
            System.out.printf("SecretName: %s%n", getSecretValueResponse.getSecretName());
         // System.out.printf("SecretData: %s%n", getSecretValueResponse.getSecretData());
            System.out.printf("VersionStages: %s%n", getSecretValueResponse.getVersionStages());
            System.out.printf("RequestId: %s%n", getSecretValueResponse.getRequestId());
        } catch (Exception e) {
            if (e instanceof TeaException) {
                System.out.printf("Code: %s%n", ((TeaException) e).getCode());
                System.out.printf("Message: %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();
        }
    }
}该文章对您有帮助吗?