Im new to Cloud KMS, and I started following exactly what's written here
I encrypted my data file which is saved in UTF-8 format by running this command
gcloud kms encrypt --location global --keyring ring --key key --plaintext-file /path_to_file --ciphertext-file /path_to_enc --project myProject
then as a result my encrypted data has been presented in this format in my new created encrypted file
$�]ˋLݿ���yHI�lS�`&�Nt�b{%�U�� �&�A���XaL��d
here is how I read the encrypted file data:
static Properties properties = new Properties();
static {
try {
InputStream in = new Credentials().getClass().getResourceAsStream("path_to_enc_file");
byte[] encryptedData = IOUtils.toByteArray(in);
byte[] decryptedBytes = decrypt(EnvironmentVariable.getProjectId(), "global", "ring", "key", encryptedData);
ByteArrayInputStream bis = new ByteArrayInputStream(decryptedBytes);
properties.load(bis);
in.close();
bis.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
and now whenever I try to decrypt it by this function:
public static byte[] decrypt(
String projectId, String locationId, String keyRingId, String cryptoKeyId, byte[] ciphertext)
throws IOException {
// Create the KeyManagementServiceClient using try-with-resources to manage client cleanup.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the cryptoKey
String resourceName = CryptoKeyName.format(projectId, locationId, keyRingId, cryptoKeyId);
// Decrypt the ciphertext with Cloud KMS.
DecryptResponse response = client.decrypt(resourceName, ByteString.copyFrom(ciphertext));
// Extract the plaintext from the response.
return response.getPlaintext().toByteArray();
}
}
it throw this
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Decryption failed: the ciphertext is invalid.",
"reason" : "badRequest"
} ],
"message" : "Decryption failed: the ciphertext is invalid.",
"status" : "INVALID_ARGUMENT"
}
the key type is: Symmetric encrypt/decrypt
Default Algorithm: Google symmetric key
the ring location: global
Can you plz help me out and tell me what's missing in google docs?
Update: As bdhess says in the comment, this is probably due to Maven being "helpful" and corrupting the data during the build process. See the Maven docs for how to avoid this.
The solution below also works, but is less straightforward.
Tamer and I chatted for a while and got a workaround:
gcloud
in base64 before including it in a file in src/main/resources
.java.util.Base64
.For some reason the bytes were getting corrupted between creating the file with gcloud
and reading the bytes in with getResourceAsStream()
. From the code above I can't see where the corruption would be happening, and it seems like reading in binary resources should be totally supported. But something is breaking somewhere in Tamer's case.
I'll try to reproduce it sometime this week.