Encryption and decryption with Python

Use PyCrypto for AES format encryption

$ pip install pycrypto

aes_cipher.py


import base64
from Crypto import Random
from Crypto.Cipher import AES

class AESCipher(object):
    def __init__(self, key, block_size=32):
        self.bs = block_size
        if len(key) >= len(str(block_size)):
            self.key = key[:block_size]
        else:
            self.key = self._pad(key)

    def encrypt(self, raw):
        raw = self._pad(raw)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(raw))

    def decrypt(self, enc):
        enc = base64.b64decode(enc)
        iv = enc[:AES.block_size]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return self._unpad(cipher.decrypt(enc[AES.block_size:]))

    def _pad(self, s):
        return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)

    def _unpad(self, s):
        return s[:-ord(s[len(s)-1:])]

After that, create a key for authentication.

$ python -c "import string, random; print(''.join([random.choice(string.ascii_letters + string.digits) for i in range(50)]))"

>>> PkDv17c6xxiqXPrvG2cUiq90VIrERfthHuViKapv6E1F7E0IgP

usage

cipher = AESCipher("PkDv17c6xxiqXPrvG2cUiq90VIrERfthHuViKapv6E1F7E0IgP")

#encryption
password = cipher.encrypt("hogefuga")
print(password) # -> H/LfZg82FOdHhnructCHzfYnVgCOvjgEUGXXDFpjiYLBHw4Zflk/m2N9zEVwz6eC

#Decryption
print(cipher.decrypt(password)) # -> hogefuga

Postscript

I registered with PyPI because it is a little stocked and there seems to be demand.

$ pip install Simple-AES-Cipher

See Github for more information.

reference

Advanced Encryption Standard Encrypt with PyCrypto

Recommended Posts

Encryption and decryption with Python
pycrypto encryption and decryption
Programming with Python and Tkinter
Python and hardware-Using RS232C with Python-
python with pyenv and venv
Works with Python and R
Encryption / decryption with GPG command
AES-CBC encryption and decryption Node.js version with Python will also be added.
Communicate with FX-5204PS with Python and PyUSB
Shining life with Python and OpenCV
Robot running with Arduino and python
Install Python 2.7.9 and Python 3.4.x with pip.
Neural network with OpenCV 3 and Python 3
AM modulation and demodulation with python
[Python] font family and font with matplotlib
Scraping with Node, Ruby and Python
Scraping with Python, Selenium and Chromedriver
Scraping with Python and Beautiful Soup
JSON encoding and decoding with python
Hadoop introduction and MapReduce with Python
[GUI with Python] PyQt5-Drag and drop-
Reading and writing NetCDF with Python
I played with PyQt5 and Python3
Reading and writing CSV with Python
Multiple integrals with Python and Sympy
Coexistence of Python2 and 3 with CircleCI (1.0)
Easy modeling with Blender and Python
Sugoroku game and addition game with python
FM modulation and demodulation with Python
Try encryption / decryption using OpenSSL key with Python3 pow function
Communicate between Elixir and Python with gRPC
Data pipeline construction with Python and Luigi
Calculate and display standard weight with python
FizzBuzz with Python3
Scraping with Python
Monitor Mojo outages with Python and Skype
Statistics with python
FM modulation and demodulation with Python Part 3
[Automation] Manipulate mouse and keyboard with Python
Scraping with Python
Passwordless authentication with RDS and IAM (Python)
Python with Go
Python installation and package management with pip
Using Python and MeCab with Azure Databricks
POST variously with Python and receive with Flask
Capturing images with Pupil, python and OpenCV
Twilio with Python
Fractal to make and play with Python
A memo with Python2.7 and Python3 on CentOS
Integrate with Python
Play with 2016-Python
Use PIL and Pillow with Cygwin Python
AES256 with python
Tested with Python
Create and decrypt Caesar cipher with python
python starts with ()
CentOS 6.4 with Python 2.7.3 with Apache with mod_wsgi and Django
Reading and writing JSON files with Python
Dealing with "years and months" in Python
with syntax (Python)
I installed and used Numba with Python3.5