generate access token using crypto library in python

To generate an access token using the cryptography library in Python, you can follow these steps:

  1. Install the cryptography library using pip:
main.py
pip install cryptography
25 chars
2 lines
  1. Import the required modules:
main.py
from cryptography.fernet import Fernet
39 chars
2 lines
  1. Generate a key for encryption:
main.py
key = Fernet.generate_key()
28 chars
2 lines
  1. Save the key to a file or environment variable for later use:
main.py
with open('key.key', 'wb') as key_file:
    key_file.write(key)
64 chars
3 lines
  1. Encrypt the access token using the key:
main.py
# Create a Fernet object with the key
fernet = Fernet(key)
 
# Encode the access token before encryption
token = b"my_access_token"
encoded_token = token.encode()
 
# Encrypt the access token
encrypted_token = fernet.encrypt(encoded_token)
240 chars
10 lines
  1. Save the encrypted access token to a file or database for later use:
main.py
with open('encrypted.token', 'wb') as token_file:
    token_file.write(encrypted_token)
88 chars
3 lines

You can decrypt the access token using the same key to retrieve the original value:

main.py
# Read the key and encrypted access token from files
with open('key.key', 'rb') as key_file:
    key = key_file.read()
 
with open('encrypted.token', 'rb') as token_file:
    encrypted_token = token_file.read()
 
# Create a Fernet object with the key
fernet = Fernet(key)
 
# Decrypt the access token
decrypted_token = fernet.decrypt(encrypted_token)
 
# Decode and print the decrypted token
print(decrypted_token.decode())
424 chars
16 lines

gistlibby LogSnag