Function Repository Resource:

Fernet

Source Notebook

Cryptographic utility function for encrypting and decrypting messages

Contributed by: Arnoud Buzing

ResourceFunction["Fernet"]["GenerateKey"]

generates a key for use with Fernet encryption and decryption.

ResourceFunction["Fernet"][{"Encrypt",key},message]

encrypts message using key.

ResourceFunction["Fernet"][{"Decrypt",key},data]

decrypts data using key.

Details

ResourceFunction["Fernet"] implements a simple, secure, symmetric (secret key) authenticated cryptographic method.
A generated ResourceFunction["Fernet"] key is a byte array that is URL-safe and "BASE64" encoded. This key must be kept safe.
ResourceFunction["Fernet"] encrypted data can be decrypted only with the orginal key.
The encryption key is in ByteArray format, but its equivalent string representation, from ByteArrayToString, is also supported.
ResourceFunction["Fernet"] requires Python. For help configuring the Python evaluator, see Configure Python for ExternalEvaluate.

Examples

Basic ExamplesFernet

Generate a cryptographic key for use with Fernet:

In[1]:=
key = ResourceFunction["Fernet"]["GenerateKey"]
Out[1]=

Encrypt a message using the cryptographic key:

In[2]:=
ba = ResourceFunction["Fernet"][{"Encrypt", key}, "This is a secret message! 😀"]
Out[2]=

The encrypted data has a "BASE64" compatible string format, so it can be used in URL requests:

In[3]:=
ba // ByteArrayToString
Out[3]=

Decrypt the message with the same key:

In[4]:=
ResourceFunction["Fernet"][{"Decrypt", key}, ba]
Out[4]=

Possible Issues (3) 

You can only decrypt data with the original Fernet key:

In[5]:=
key1 = ResourceFunction["Fernet"]["GenerateKey"];
ba = ResourceFunction["Fernet"][{"Encrypt", key1}, "Secret message"];

key2 = ResourceFunction["Fernet"]["GenerateKey"];
ResourceFunction["Fernet"][{"Decrypt", key2}, ba]
Out[4]=

You can not use arbitrary byte arrays as the encryption key:

In[6]:=
ResourceFunction[
 "Fernet"][{"Encrypt", ByteArray[{1, 2, 3}]}, "Secret message"]
Out[6]=

Generated keys should be stored securely. One method of secure persistent storage is provided by SystemCredential:

In[7]:=
key = ResourceFunction["Fernet"]["GenerateKey"];
SystemCredential["my-secret-key"] = ByteArrayToString[key]; (* store the key as a base64 string *)
SystemCredential["my-secret-key"]
Out[9]=

Encrypt using the key stored in SystemCredential:

In[10]:=
ba = ResourceFunction[
  "Fernet"][{"Encrypt", SystemCredential["my-secret-key"]}, "Secret message"]
Out[10]=

Decrypt using the key stored in SystemCredential:

In[11]:=
ResourceFunction[
 "Fernet"][{"Decrypt", SystemCredential["my-secret-key"]}, ba]
Out[11]=

Publisher

WolframExternalFunctions

Requirements

Wolfram Language 13.0 (December 2021) or above

Version History

  • 1.0.0 – 10 June 2024

Source Metadata

Related Resources

License Information