The following code is a minimal example for string encryption with Fernet Java 8 and has no propper error handling, as well I didn't check what encryption algorithm, mode or key length is in use.
To encrypt more complex data structures please refer to https://github.com/l0s/fernet-java8.
In the first encryption/decryption part a fresh new key is generated and a new token is produced. This token has a (default) duration of 60 seconds that can be changed. The decryption is done immediately so it is not expired.
The second decryption takes an old token (from GitHub readme.md) and when trying to decrypt you receive a "TokenExpiredException".
Console:
key: j2v_wwTtEanOKF4-OqXtJ8ECi9UGOD72uGuJLJqZUuE=
token: gAAAAABfEJkmA7qy6voW6-xZMz4wYqcies156jEBXbqkk585aerDwKRlQAuFOkSv94Ac503WSk222ayQMvPmweDp9IRakq3mBMrBY7zyRt9ou5luqpTXs8HDWvCjpJ0y66-hboULhyut
token timestamp: 2020-07-16T18:15:02.456832100Z
decryptedtext: this is my data that needs encryption
token2 timestamp: 1985-10-26T08:20:00Z
Exception in thread "main" com.macasaet.fernet.TokenExpiredException: Token is expired
at com.macasaet.fernet.Token.validateAndDecrypt(Token.java:250)
at com.macasaet.fernet.Validator.validateAndDecrypt(Validator.java:104)
at com.macasaet.fernet.Token.validateAndDecrypt(Token.java:228)
at Unable_to_perform_Encryption_using_Fernet_Java.Main.main(Main.java:27)
Code:
import com.macasaet.fernet.Key;
import com.macasaet.fernet.StringValidator;
import com.macasaet.fernet.Token;
import com.macasaet.fernet.Validator;
// get Fernet_Java here: https://mvnrepository.com/artifact/com.macasaet.fernet/fernet-java8
// version used: 1.42
public class Main {
static final Validator<String> validator = new StringValidator() {
};
public static void main(String[] args) {
System.out.println("https://stackoverflow.com/questions/62939044/unable-to-perform-encryption-using-fernet-java-in-android-studio\n");
// generate a key
Key key = Key.generateKey();
System.out.println("key: " + key.serialise());
// encrypt
String plaintext = "this is my data that needs encryption";
Token token = Token.generate(key, plaintext);
System.out.println("token: " + token.serialise());
// decrypt
System.out.println("token timestamp: " + token.getTimestamp());
String decryptedtext = token.validateAndDecrypt(key, validator);
System.out.println("decryptedtext: " + decryptedtext);
// old token
Token token2 = Token.fromString("gAAAAAAdwJ6wAAECAwQFBgcICQoLDA0ODy021cpGVWKZ_eEwCGM4BLLF_5CV9dOPmrhuVUPgJobwOz7JcbmrR64jVmpU4IwqDA==");
System.out.println("token2 timestamp: " + token2.getTimestamp());
String decryptedtext2 = token2.validateAndDecrypt(key, validator);
System.out.println("decryptedtext2: " + decryptedtext2);
}
}