Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views9 pages

Python Cryptography Readme

Python Cryptography Readme

Uploaded by

svanwellness
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views9 pages

Python Cryptography Readme

Python Cryptography Readme

Uploaded by

svanwellness
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

5/22/2021 How to Use AES-256 Cipher: Python Cryptography Examples | Hacker Noon

How to Use AES-256 Cipher: Python


Cryptography Examples
February 23rd 2020  10,340 reads 

@wagslane
Lane Wagner

Bitcoinist, libertarian, atheist, cryptography fan, and founder of http://qvault.io

https://hackernoon.com/how-to-use-aes-256-cipher-python-cryptography-examples-6tbh37cr 1/9
5/22/2021 How to Use AES-256 Cipher: Python Cryptography Examples | Hacker Noon

Need to encrypt some text with a password or private key in Python? You certainly came to
the right place. AES-256 is a solid symmetric cipher that is commonly used to encrypt data

for oneself. In other words, the same person who is encrypting the data is typically
decrypting it as well (think password manager).

Dependencies Search...  
Never clean messy spreadsheets again
For this tutorial, we will be using Python 3, so make sure you install pycryptodome, which
Howustoaccess
will give Use AES-256 Cipher: Python
to an implementation Cryptography Examples by @wagslane
of AES-256:

pip3 install pycryptodomex

Padding - Handled by GCM

AES-256 typically requires that the data to be encrypted is supplied in 16-byte blocks, and
you may have seen that on other sites or tutorials. AES-256 in GCM mode, however, doesn't
require any special padding to be done by us manually.

Encrypting

Now we create a simple encrypt(plain text, password) function. This function uses the
https://hackernoon.com/how-to-use-aes-256-cipher-python-cryptography-examples-6tbh37cr 2/9
5/22/2021 How to Use AES-256 Cipher: Python Cryptography Examples | Hacker Noon
Now we create a simple encrypt(plain_text, password) function. This function uses the
password to encrypt the plain text. Therefore, anyone with access to the encrypted text and
the password will be able to decrypt it.

def encrypt(plain_text, password):


# generate a random salt
salt = get_random_bytes(AES.block_size)

# use the Scrypt KDF to get a private key from the password
private_key = hashlib.scrypt(
password.encode(), salt=salt, n=2**14, r=8, p=1, dklen=32)

# create cipher config


cipher_config = AES.new(private_key, AES.MODE_GCM)

# return a dictionary with the encrypted text


cipher_text, tag = cipher_config.encrypt_and_digest(bytes(plain_text, 'utf-
8'))
return {
'cipher_text': b64encode(cipher_text).decode('utf-8'),
'salt': b64encode(salt).decode('utf-8'),
'nonce': b64encode(cipher_config.nonce).decode('utf-8'),
'tag': b64encode(tag).decode('utf-8')
}

Notes on encrypt() function

1. Nonce: A random nonce (arbitrary value) must be a random and unique value for each
time our encryption function is used with the same key. Think of it as a random salt for a
cipher. The library supplies us with a secure nonce.
2. Scrypt: Scrypt is used to generate a secure private key from the password. This will make
it harder for an attacker to brute-force our encryption.
3 Salt: A new random salt is used for each run of our encryption This makes it impossible
https://hackernoon.com/how-to-use-aes-256-cipher-python-cryptography-examples-6tbh37cr 3/9
5/22/2021 How to Use AES-256 Cipher: Python Cryptography Examples | Hacker Noon
3. Salt: A new random salt is used for each run of our encryption. This makes it impossible
for an attacker to use precomputed hashes in an attempt to crack the cipher. (see rainbow
table)
4. Scrypt parameters:

1. N is the cost factor. It must be a power of two, and the higher it is the more secure the
key, but the more resources it requires to run.
2. R is the block size.
3. P is the parallelization factor, useful for running on multiple cores.

1. Base64: We encode all of our bytes-type data into base64 a convenient string
representation
2. Tag: The tag is used to authenticate the data when using AES in GCM mode. This
ensures no one can change our data without us knowing about it when we decrypt.

Decrypting

def decrypt(enc_dict, password):


# decode the dictionary entries from base64
salt = b64decode(enc_dict['salt'])
cipher_text = b64decode(enc_dict['cipher_text'])
nonce = b64decode(enc_dict['nonce'])
tag = b64decode(enc_dict['tag'])

# generate the private key from the password and salt


private_key = hashlib.scrypt(
password.encode(), salt=salt, n=2**14, r=8, p=1, dklen=32)

# create the cipher config


cipher = AES.new(private_key, AES.MODE_GCM, nonce=nonce)

# decrypt the cipher text


decrypted = cipher.decrypt_and_verify(cipher_text, tag)

return decrypted

https://hackernoon.com/how-to-use-aes-256-cipher-python-cryptography-examples-6tbh37cr 4/9
5/22/2021 How to Use AES-256 Cipher: Python Cryptography Examples | Hacker Noon

Notes on decrypt() function

The decrypt() function needs the same salt, nonce, and tag that we used for encryption. We
used a dictionary for convenience in parsing, but if we instead wanted one string of
ciphertext we could have used a scheme like salt.nonce.tag.cipher_textThe configuration
parameters on the Scrypt and AES functions need to be the same as the encrypt function.

Give Me The Full Code!

You probably want to see it all work in an example script. Look no further!

# AES 256 encryption/decryption using pycryptodome library

from base64 import b64encode, b64decode


import hashlib
from Cryptodome.Cipher import AES
import os
from Cryptodome.Random import get_random_bytes

def encrypt(plain_text, password):


# generate a random salt
salt = get_random_bytes(AES.block_size)

# use the Scrypt KDF to get a private key from the password
private_key = hashlib.scrypt(
password.encode(), salt=salt, n=2**14, r=8, p=1, dklen=32)

# create cipher config


https://hackernoon.com/how-to-use-aes-256-cipher-python-cryptography-examples-6tbh37cr 5/9
5/22/2021 How to Use AES-256 Cipher: Python Cryptography Examples | Hacker Noon

cipher_config = AES.new(private_key, AES.MODE_GCM)

# return a dictionary with the encrypted text


cipher_text, tag = cipher_config.encrypt_and_digest(bytes(plain_text, 'utf-
8'))
return {

'cipher_text': b64encode(cipher_text).decode('utf-8'),
'salt': b64encode(salt).decode('utf-8'),
'nonce': b64encode(cipher_config.nonce).decode('utf-8'),
'tag': b64encode(tag).decode('utf-8')
}

def decrypt(enc_dict, password):


# decode the dictionary entries from base64
salt = b64decode(enc_dict['salt'])
cipher_text = b64decode(enc_dict['cipher_text'])
nonce = b64decode(enc_dict['nonce'])
tag = b64decode(enc_dict['tag'])

# generate the private key from the password and salt


private_key = hashlib.scrypt(
password.encode(), salt=salt, n=2**14, r=8, p=1, dklen=32)

# create the cipher config


cipher = AES.new(private_key, AES.MODE_GCM, nonce=nonce)

# decrypt the cipher text


decrypted = cipher.decrypt_and_verify(cipher_text, tag)

return decrypted

def main():
password = input("Password: ")

# First let us encrypt secret message


encrypted = encrypt("The secretest message here", password)
print(encrypted)

# Let us decrypt using our original password


decrypted = decrypt(encrypted, password)
print(bytes.decode(decrypted))

https://hackernoon.com/how-to-use-aes-256-cipher-python-cryptography-examples-6tbh37cr 6/9
5/22/2021 How to Use AES-256 Cipher: Python Cryptography Examples | Hacker Noon

main()

Thanks For Reading

Lane on Twitter: @wagslane


Lane on Dev.to: wagslane
Download Qvault: https://qvault.io

By Lane Wagner

by Lane Wagner @wagslane. Bitcoinist, libertarian, atheist, cryptography fan, and


founder of http://qvault.io

 Follow Lane On Twitter

Related Stories

Subject Matter

Enter The Decentralized Internet Writing Contest by @HackerNoon+FreeTON

#promoted
#promoted

How To Make Correct Line Endings by @wagslane

#crlf

Top 5 React Native Starter Kits to Try | Review Guide 2021 by @katarinaharbuzawa
https://hackernoon.com/how-to-use-aes-256-cipher-python-cryptography-examples-6tbh37cr 7/9
5/22/2021 How to Use AES-256 Cipher: Python Cryptography Examples | Hacker Noon

#react-native-starter-kit

A Guide to Python Advanced Features by @faizan4it

#python-programming

Types of Cross-Site Scripting(XSS) Attacks by @obetomuniz

#security

How to Do Speech Recognition in Python by @miketechgame

#python

How to Use Lerna to Create a Monorepo for Multiple Node Packages by @aspecto

#tutorial

TAGS

#cryptography #programming #python #security #tutorial #aes-256

#software-development #password-security

Join Hacker Noon 


􏔰
The Hacker Noon Newsletter
Create your free account to unlock your custom reading experience.

Quality Weekly Reads About Technology Infiltrating Everything

[email protected]

Subscribefree

Yes, I agree to receive emails about tech eating the world.

ABOUT
Careers
Contact
Cookies
https://hackernoon.com/how-to-use-aes-256-cipher-python-cryptography-examples-6tbh37cr 8/9
5/22/2021 How to Use AES-256 Cipher: Python Cryptography Examples | Hacker Noon
Cookies
Help
Privacy
Terms

READ
Archive
Leaderboard
Signup
Tech Brief
Tech Tags
Top Stories

WRITE
Distribution
Editor Tips
Guidelines
New Story
Perks
Why Write

SPONSOR
Brand Publishing
Case Studies
Niche Marketing
Newsletter
Sitewide Billboard
Writing Contests

https://hackernoon.com/how-to-use-aes-256-cipher-python-cryptography-examples-6tbh37cr 9/9

You might also like