gpt4 book ai didi

java - python 中的 Fernet 类加密和 java 中的解密不起作用

转载 作者:行者123 更新时间:2023-11-30 01:48:02 26 4
gpt4 key购买 nike

我正在尝试编写一个用 Python 加密并用 Java 解密的代码,但出现错误。

我在 python 中使用 cryptography.fernet 来加密文件,当我使用 Fernet Java 进行解密时,它显示错误。

这是我的Python代码:

from cryptography.fernet import Fernet


key = Fernet.generate_key()
cipher_suite = Fernet(key)


with open("key.txt", "wb") as f:
f.write(key)

with open("read_plain_text_from_here.txt", "r") as f:
encoded_text = f.read().encode()
cipher_text = cipher_suite.encrypt(encoded_text)

with open("write_cipher_text_here.txt", "wb") as f:
f.write(cipher_text)

with open("write_cipher_text_here.txt", "rb") as f:
cipher_text = f.read()

with open("key.txt", "rb") as f:
decryption_key = f.read()

with open("write_plain_text_here.txt", "wb") as f:
cipher_suite = Fernet(decryption_key)
f.write(cipher_suite.decrypt(cipher_text))

这是我的java代码:

package encryptapp;
import com.macasaet.fernet.*;


public class Decrypt
{
public static void main(String args[])
{
final Key key = new Key("***key i got from python**");
final Token token = Token.fromString("***cipher text i got from python***");
final Validator<String> validator = new StringValidator() {};
final String payload = token.validateAndDecrypt(key, validator);
System.out.println("Payload is " + payload);
}
}

我得到的 Java 错误是:

Exception in thread "main" com.macasaet.fernet.TokenExpiredException: Token is expired
at com.macasaet.fernet.Token.validateAndDecrypt(Token.java:240)
at com.macasaet.fernet.Validator.validateAndDecrypt(Validator.java:104)
at com.macasaet.fernet.Token.validateAndDecrypt(Token.java:218)
at encryptapp.Decrypt.main(Decrypt.java:60)

文档链接:

Python:https://cryptography.io/en/latest/

Java:https://github.com/l0s/fernet-java8/blob/master/README.md

最佳答案

fernet-java8类没有像 python 类那样用于解密的显式 TTL 参数。相反,它的默认值为 60 秒。您需要重写 Validator 接口(interface)的 getTimeToLive() 方法来指定自定义 TTL。如果要将 TTL 设置为“永远”(相当于 python fernet 中的关键字参数 ttl=None),请执行以下操作:

import java.time.Duration;
import java.time.Instant;
.
.
.
@Override
final Validator < String > validator = new StringValidator() {
public TemporalAmount getTimeToLive() {
return Duration.ofSeconds(Instant.MAX.getEpochSecond());
}
};

关于java - python 中的 Fernet 类加密和 java 中的解密不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57221652/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com