[PYTHON] pycrypto encryption and decryption

import string
import random

#pip install pycrypto
from Crypto.Cipher import AES


key = ''.join(
    random.choice(string.ascii_letters) for _ in range(AES.block_size)) #Comprehension notation

iv = ''.join(
    random.choice(string.ascii_letters) for _ in range(AES.block_size)) #Comprehension notation

plaintext = 'fdsfsdgsgsfgs'
cipher = AES.new(key, AES.MODE_CBC, iv)
padding_length = AES.block_size - len(plaintext) % AES.block_size #Calculate the length of the padding string
plaintext += chr(padding_length) * padding_length #padding
cipher_text = cipher.encrypt(plaintext) #encryption
print(cipher_text)

cipher2 = AES.new(key, AES.MODE_CBC, iv)
decrypted_text = cipher2.decrypt(cipher_text) #Decryption
print(decrypted_text[:-decrypted_text[-1]]) #Display with the padded character string removed
b'\xba\xb5\xf6\x0f\x87\xe0N\xa1?I\xf6O\x1d\x96]\x88'
b'fdsfsdgsgsfgs'

Recommended Posts

pycrypto encryption and decryption
Encryption and decryption with Python
PyCryptodome AES encryption and decryption process memo
Encryption / decryption with GPG command
AES-CBC encryption and decryption Node.js version with Python will also be added.
Private methods and fields in python [encryption]