Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中的Fernet类加密和java中的解密不起作用_Java_Python_Python 3.x_Cryptography - Fatal编程技术网

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

python中的Fernet类加密和java中的解密不起作用,java,python,python-3.x,cryptography,Java,Python,Python 3.x,Cryptography,我试图用Python编写加密代码,用Java编写解密代码,但我遇到了一个错误 我在python中使用cryptography.fernet对文件进行加密,当我使用fernetjava进行解密时,会显示一个错误 以下是我的python代码: from cryptography.fernet import Fernet key = Fernet.generate_key() cipher_suite = Fernet(key) with open("key.txt", "wb") as f:

我试图用Python编写加密代码,用Java编写解密代码,但我遇到了一个错误

我在python中使用
cryptography.fernet
对文件进行加密,当我使用
fernetjava
进行解密时,会显示一个错误

以下是我的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);
    }
  }
文档链接:

Python:

Java:

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

import java.time.Duration;
导入java.time.Instant;
.
.
.
@凌驾
最终验证器<字符串>验证器=新的StringValidator(){
公共临时山{
返回持续时间.of秒(Instant.MAX.getEpochSecond());
}
};

它成功了。你是对的,它需要超越TTL。与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)