I am trying to create an encrypted token that is to be sent as an REST API response. The end user then can send the same token during next request to this api, and I can parse it and get some context info (of the previous one).
Since I'm new to cryptography, I felt it's better to pick up Google tink
instead of writing the encryption/decryption code by myself. However I'm not able to decrypt correctly.
I am doing the encryption/decryption like the following:
public class CipherUtils {
public static byte[] encrypt(byte[] plainText,
byte[] associatedData) throws GeneralSecurityException {
KeysetHandle keysetHandle = KeysetHandle.generateNew(AeadKeyTemplates.AES128_GCM);
Aead aead = keysetHandle.getPrimitive(Aead.class);
return aead.encrypt(plainText, associatedData);
}
public static byte[] decrypt(byte[] cipherText,
byte[] associatedData) throws GeneralSecurityException {
KeysetHandle keysetHandle = KeysetHandle.generateNew(AeadKeyTemplates.AES128_GCM);
Aead aead = keysetHandle.getPrimitive(Aead.class);
return aead.decrypt(cipherText, associatedData);
}
}
Here's how I am generating the token:
String associatedData = "somethingUnique";
String data = "tokenToBeEncrypted";
byte[] ciphered = CipherUtils.encrypt(data.getBytes(), associatedData.getBytes());
String finalToken = Base64.getEncoder().encodeToString(ciphered);
This finalToken
is sent back as response and also retrieved from next request.
Here's I am trying to decrypt:
String associatedData = "somethingUnique"; // same one used for encrypting
String token = // retrieved from http request
byte[] decodedText = Base64.getDecoder().decode(token);
byte[] deciphered = CipherUtils.decrypt(decodedText, associatedData.getBytes());
This always results in the following exception:
java.security.GeneralSecurityException: decryption failed
at com.google.crypto.tink.aead.AeadWrapper$WrappedAead.decrypt(AeadWrapper.java:82)
at CipherUtils.decrypt(CipherUtils.java:22)
What am I missing here?
P.S: I'm using tink
version 1.3.0-rc1