Search code examples
javajpabouncycastle

BouncyCastle: mac check in GCM failed


I have the following class defined in an application:

@Entity
@Table(name = "SETTINGS")
public class Settings {

    @Id
    public int id;

    private String sharedSecret;

    @Transient
    private SecretKey key;

    public SecretKey getKey() {
         return key;
    }

    public void genKey() throws NoSuchAlgorithmException {
        key = KeyGenerator.getInstance("AES").generateKey();
        sharedSecret = Base64.toBase64String(key.getEncoded());
    }

    @PostLoad
    private void init() {
        byte[] encodedKey = Base64.decode(sharedSecret);
        key = new SecretKeySpec(encodedKey,0,encodedKey.length,"AES");
    }
}

I'm using javax.security and BouncyCastle package. The idea is that using JPA, the application will persist the Base64 encoded string to the application's database, and then when using that persisted value to recreate the key when needed. However, I am running into an error when I am performing a decryption, which is

com.nimbusds.jose.JOSEException: Couldn't validate GCM authentication tag: mac check in GCM failed

The research I've done seems to indicate the key being read from the database isn't the same persisted value, but I am not sure what more I can do to correctly encode and decode the key.


Solution

  • The issue had nothing to do with the class, but with how the ciphertext was being reading.