以下代码是使用Fernet Java 8 进行字符串加密的最小示例,并且没有适当的错误处理,而且我没有检查正在使用的加密算法、模式或密钥长度。
要加密更复杂的数据结构,请参考https://github.com/l0s/fernet-java8。
在第一个加密/解密部分中,生成一个新的密钥并生成一个新的令牌。此令牌的(默认)持续时间为 60 秒,可以更改。解密立即完成,因此不会过期。
第二次解密需要一个旧令牌(来自 GitHub readme.md),当尝试解密时,您会收到“TokenExpiredException”。
安慰:
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)
代码:
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);
}
}