简体   繁体   中英

Symmetric Encryption on java with Fernet

I want to encrypt and decrypt messages between python and java with the Fernet module. But I don't understand the example they're giving.

Deserialise an existing key:

final Key key = new Key("cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4=");

Create a token:

final Token token = Token.generate(random, key, "secret message");

Deserialise an existing token:

final Token token = Token.fromString("gAAAAAAdwJ6wAAECAwQFBgcICQoLDA0ODy021cpGVWKZ_eEwCGM4BLLF_5CV9dOPmrhuVUPgJobwOz7JcbmrR64jVmpU4IwqDA==");

Why do you need a random parameter to encrypt the secret message? I've implemented the fermet encryption in python and it never asked for any source of randomness.

>>> from cryptography.fernet import Fernet
>>> key = Fernet.generate_key()
>>> f = Fernet(key)
>>> token = f.encrypt(b"my deep dark secret")
>>> token
b'...'
>>> f.decrypt(token)
b'my deep dark secret

How can I get the same encryption standard as in python so I can use the same encryption key?

With the same key the implementations in Python and Java will be perfectly compatible. But on both sides you have to use the same one, of course. If you use the Python code as the base, do a print(key) and copy that same key to the Java variant (it will be a urlsafebase64 string, so no transport issues). In Java when generating the token, use a SecureRandom() instance. It's only used for the IV and that's part of the token anyway, so will be available for the decryption code in whatever language. Fernet Python uses good random automatically (it's transparant, you don't have to choose it). But whatever choice of random you pick in Java when generating tokens, will have no effect on the decryption code at all, just use the same key-string in both instances.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM