0

I'm trying to fetch the encryption key from the KMS for encrypting or decrypting data from a database. And the error suggests that the key purpose is wrong. What should be the actual key purpose for my use case?

FAILED_PRECONDITION: Operation requested for Key projects/myproject67567/locations/global/keyRings/test/cryptoKeys/test/cryptoKeyVersions/1 has incorrect key purpose: ENCRYPT_DECRYPT

Please help

public PublicKey fetchKey() {
  try {
      KeyManagementServiceSettings keyManagementServiceSettings =
              KeyManagementServiceSettings.newBuilder()
                      .setCredentialsProvider(FixedCredentialsProvider.create(GoogleCredentials.getApplicationDefault()
                              .createScoped(Collections.singleton("https://www.googleapis.com/auth/cloudkms"))))
                      .build();

      KeyManagementServiceClient client =
              KeyManagementServiceClient.create(keyManagementServiceSettings);

        CryptoKeyVersionName keyVersionName =
                CryptoKeyVersionName.of("myproject67567", "global", "test",
                        "test", "1");

    // Get the public key.
    PublicKey publicKey = client.getPublicKey(keyVersionName);
    return publicKey;

  }catch (Exception e){
      throw new Exception(e);
  }
}
  • Symmetric keys do not have a public key. Although asymmetric keys (RSA, Ed25519, etc), which do have private and public keys, can be used to encrypt small amounts of data, symmetric keys are normally used. – John Hanley Nov 16 '22 at 09:05
  • Oh so the encryption key cannot be fetched? – BefuddledBarberian Nov 16 '22 at 09:11
  • Yes, you can. However, your code is trying to fetch a key type that does not exist. Symmetric keys do not have a public key. – John Hanley Nov 16 '22 at 09:15
  • Got it. I'll try another way – BefuddledBarberian Nov 16 '22 at 09:20
  • Hello sir, I could not find find a way to fetch the symmetric key. The `KeyManagementServiceClient` through `getCryptoKey` provides only metadata of the key and not the key itself. Can you please give me the name of the class or function with which I can fetch symmetric keys? – BefuddledBarberian Nov 16 '22 at 10:46

1 Answers1

4

Symmetric keys are internal to KMS and can't be exported. The reason you see this error is that you are trying to export a public key (asymmetric) from a symmetric key (with purpose ENCRYPT_DECRYPT).

metemad
  • 56
  • 3