import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class PFMDecryption {
public static String decryptResponse(String ciphertext, String key, String iv) {
try {
// Decode the Base64 encoded key and IV
byte[] encryptionKey = Base64.getDecoder().decode(key);
byte[] encryptionIv = Base64.getDecoder().decode(iv);
// Decode the encrypted response
byte[] encryptedBytes = Base64.getUrlDecoder().decode(ciphertext);
// Setup AES-GCM decryption
SecretKeySpec keySpec = new SecretKeySpec(encryptionKey, "AES");
GCMParameterSpec gcmSpec = new GCMParameterSpec(128, encryptionIv);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmSpec);
// Decrypt and return
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, "UTF-8");
} catch (javax.crypto.AEADBadTagException e) {
throw new RuntimeException("Authentication tag verification failed! Wrong key, IV, or corrupted data.", e);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Invalid Base64URL format in ciphertext.", e);
} catch (Exception e) {
throw new RuntimeException("Decryption failed: " + e.getMessage(), e);
}
}
}