I am building a Java SDK for which I need to write a service to decrypt cipher text using initialVector, authenticationTag and secretKey. I am taking reference from equivalent node SDK. The JavaScript code is as follows using the crypt package of Node.js.
export const decryptSymmetric128BitHexKeyUTF8 = ({ ciphertext, iv, tag, key }: IDecryptSymmetric128BitHexKeyUTF8Input) => {
const ALGORITHM = 'aes-256-gcm';
const decipher = crypto.createDecipheriv(
ALGORITHM,
key,
Buffer.from(iv, 'base64')
);
decipher.setAuthTag(Buffer.from(tag, 'base64'));
let cleartext = decipher.update(ciphertext, 'base64', 'utf8');
cleartext += decipher.final('utf8');
return cleartext;
}
I am trying to write equivalent Java code, but I am struggling for the same as I don't know how to use authentication tags in Java during decryption. I am using Java 8. How can I write Java code for the same?
Here is the test data.
cipherText: 2LPVwa7s4+xyd8KF94r07TOCaOdf4X90NWqhHQCpoJGT+T3TYjKCWf3V+A==
iv: S4/yimaF8bu0jQW9uagIJA==
tag: L6BtTic18dd4fNL2maytFA==
key: password1232asdfpassword1232asdf
expectedPlainText: The quick brown fox jumps over the lazy dog
try this:
also make sure to have the Java Cryptography Extension (JCE) installed in your Java runtime environment, as the "AES/GCM/NoPadding" transformation requires it.
The decryptSymmetric128BitHexKeyUTF8 method takes the ciphertext, iv, tag, and key as input parameters and returns the decrypted plaintext as a string. It decodes the Base64-encoded inputs, initializes the cipher with the secret key and parameters, updates the associated authenticated data (tag), and performs the decryption using doFinal. Finally, it converts the decrypted bytes back to a UTF-8 encoded string.
In the main method, you can test the decryption by providing the test data you provided. The decrypted text should match the expected plain text you mentioned.
Hope this work fine with you...