Skip to content
Advertisement

Fernet class encryption in python and decryption in java not working

I am trying to write a code for encryption in Python and decryption in Java but I am getting an error.

I am using cryptography.fernet in python to encrypt a file and when I use Fernet Java for decryption it shows an error.

Here is my python code:

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))

Here is my java code:

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);
    }
  }

The error in Java that I get is:

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)

LINKS for docs:

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

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

Advertisement

Answer

The fernet-java8 class does not have an explicit TTL argument for decryption like the python class does. Instead, it has a default of 60 seconds. You need to override the getTimeToLive() method of the Validator interface to specify a custom TTL. If you want to set the TTL to “forever”, which is equivalent to the keyword argument ttl=None in python fernet, do something like this:

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