0

我想通过使用加密和解密儿子值,google cloud kms我使用此代码作为示例https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/kms/src/main/java/com/example/ CryptFile.java

try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {

  // The resource name of the cryptoKey
  String resourceName = CryptoKeyName.format(projectId, locationId, keyRingId, cryptoKeyId);

  // Encrypt the plaintext with Cloud KMS.
  EncryptResponse response = client.encrypt(resourceName, ByteString.copyFrom(plaintext));

  // Extract the ciphertext from the response.
  return response.getCiphertext().toByteArray();
}

当代码执行该行时client.encrypt(resourceName, ByteString.copyFrom(plaintext));,它会冻结,我没有得到任何响应。

如果我使用gcloud命令加密/解密它可以工作。

我在App Engine标准(运行时 java8)上运行我的应用程序,我使用的依赖项是

   <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-kms</artifactId>
        <version>1.29.0</version>
    </dependency>

我对代码进行了一些更改以获取凭据:

    AppIdentityService appIdentityService = AppIdentityServiceFactory.getAppIdentityService();
    GoogleCredentials credentials = AppEngineCredentials.newBuilder().setScopes(Arrays.asList("https://www.googleapis.com/auth/cloudkms")).
            setAppIdentityService(appIdentityService).build();

    FixedCredentialsProvider credentialsProvider = FixedCredentialsProvider.create(credentials);
    KeyManagementServiceSettings kmsSettings = KeyManagementServiceSettings.newBuilder().setCredentialsProvider(credentialsProvider).build();

    try (KeyManagementServiceClient client = KeyManagementServiceClient.create(kmsSettings)) {

但我总是得到“未经身份验证:计算凭证元数据失败”。

有什么帮助吗?如果我在这里遗漏了什么,请告诉我。

问候

4

1 回答 1

0

同样的事情,在调用 encrypt 时运行 example hags 中的代码

Json auth 文件设置为环境 export GOOGLE_APPLICATION_CREDENTIALS="../my.json"

根据文档 Cloud KMS CryptoKey Encrypter/Decrypter 授予用户正确的权限

在调试器中验证所有 4 个参数都正确:projectId、locationId、keyRingId、cryptoKeyId

此代码挂起

try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {

            final String resourceName = CryptoKeyName.format(projectId, locationId, keyRingId, cryptoKeyId);

            // Always Hangs here!!!!
            final EncryptResponse response = client.encrypt(resourceName, ByteString.copyFromUtf8(data));

            return response.getCiphertext().toString();
        } 
于 2020-11-11T23:48:30.930 回答