0

I've created a runnable JAR file which has a class with this code:

static KeysetHandle keysetHandle = null;

public String encrypt(String plainText){

    Config.register(AeadConfig.TINK_1_1_0);

       // GENERATE key
       // key generated using tink library
       keysetHandle = KeysetHandle.generateNew(AeadKeyTemplates.AES256_GCM);
}

public String decrypt(String cipherText){

    //using the key generated during encryption to decrypt
                 Aead aeadDecryption = AeadFactory.getPrimitive(keysetHandle);

} 

In my other Java application I've imported this JAR file as an external JAR file and am trying to run these methods:

import core.Crypto;

public class Sample {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Crypto crypto = new Crypto();
        System.out.println(crypto.encrypt("sampleText"));
        System.out.println(crypto.decrypt("XXX"));
    }
}

The encrypt function works as expected, but the decrypt returns a NullPointerException because keysetHandle is null. How do I get the updated value for keysetHandle?

sibster
  • 23
  • 4
  • 1
    You should provide more details about how keysetHandle is getting initialized? Is it based on a certain condition? Also an observation, why are you depending on initialization of static variable from non-static method? The approach isn't correct. – CuriousMind Nov 19 '18 at 04:15
  • Added more detail to the code. I'm using static variable so that I can access it from both methods. Is there a better way? – sibster Nov 19 '18 at 16:44
  • It doesn't have to be static. You can still access it from both methods. – DodgyCodeException Nov 19 '18 at 16:50
  • You should have a look at `generateNew` method and figure out under what circumstances it can return a null value. That will provide a clue about your problem. – CuriousMind Nov 20 '18 at 04:27
  • @CuriousMind https://github.com/google/tink/blob/master/java/src/main/java/com/google/crypto/tink/KeysetHandle.java shows that `generateNew` never returns null. It's more likely another thread is setting the static field to null. – DodgyCodeException Nov 20 '18 at 09:40
  • Not sure what happened, but why do you have to use a static variable? Here's an example of how to generate and persist the keyset handle properly: https://github.com/google/tink/blob/master/examples/helloworld/java/src/main/java/com/helloworld/Commands.java. Hope that helps, Thai. – Thai Duong Jan 17 '19 at 22:58

0 Answers0