(转)python的一个封装好的对称加密模块,可以直接拿来用。

首先对称加密以及单向加密需要有一定的了解。

        我们所说的加密方式,都是对二进制编码的格式进行加密的,对应到Python中,则是我们的Bytes。所以当我们在Python中进行加密操作的时候,要确保我们操作的是Bytes,否则就会报错,将字符串和Bytes互相转换可以使用encode()decode()方法。

单向加密:传输中以及使用一直都是以加密进行。并且理论上是无解的。或者很难解开,不需要key等。例如MD5(信息-摘要算法),uuid,

双向加密:使用key,传输过程中是密文,但是使用的时候可以自己进行解密。比较灵活。

base64(但是这个一般不用于加密重要,很多地方不把这个当做一种加密方式,主要是太容易破解了。)

再就是PyCrypto,但是在2012年后没有维护了,导致python3后面不能用。幸好有一个该项目的分支PyCrytodome 取代了 PyCrypto。本文就是pycrytodome的使用。

 

import os

import Crypto.Cipher.AES
import Crypto.Random
import base64
import binascii

import django


# 安装pip install pycryptodome
class Cipher_AES:
    pad_default = lambda x, y: x + (y - len(x) % y) * " ".encode("utf-8")
    unpad_default = lambda x: x.rstrip()

    pad_user_defined = lambda x, y, z: x + (y - len(x) % y) * z.encode("utf-8")
    unpad_user_defined = lambda x, z: x.rstrip(z)

    pad_pkcs5 = lambda x, y: x + (y - len(x) % y) * chr(y - len(x) % y).encode("utf-8")
    unpad_pkcs5 = lambda x: x[:-ord(x[-1])]

    def __init__(self, key="单独的key16位字母数字", iv=Crypto.Random.new().read(Crypto.Cipher.AES.block_size)):
        self.__key = key
        self.__iv = iv

    def set_key(self, key):
        self.__key = key

    def get_key(self):
        return self.__key

    def set_iv(self, iv):
        self.__iv = iv

    def get_iv(self):
        return self.__iv

    def Cipher_MODE_ECB(self):
        self.__x = Crypto.Cipher.AES.new(self.__key.encode("utf-8"), Crypto.Cipher.AES.MODE_ECB)

    def Cipher_MODE_CBC(self):
        self.__x = Crypto.Cipher.AES.new(self.__key.encode("utf-8"), Crypto.Cipher.AES.MODE_CBC,
                                         self.__iv.encode("utf-8"))

    def encrypt(self, text, cipher_method, pad_method="", code_method=""):
        if cipher_method.upper() == "MODE_ECB":
            self.Cipher_MODE_ECB()
        elif cipher_method.upper() == "MODE_CBC":
            self.Cipher_MODE_CBC()
        cipher_text = b"".join([self.__x.encrypt(i) for i in self.text_verify(text.encode("utf-8"), pad_method)])
        if code_method.lower() == "base64":
            return base64.encodebytes(cipher_text).decode("utf-8").rstrip()
        elif code_method.lower() == "hex":
            return binascii.b2a_hex(cipher_text).decode("utf-8").rstrip()
        else:
            return cipher_text.decode("utf-8").rstrip()

    def decrypt(self, cipher_text, cipher_method, pad_method="", code_method=""):
        if cipher_method.upper() == "MODE_ECB":
            self.Cipher_MODE_ECB()
        elif cipher_method.upper() == "MODE_CBC":
            self.Cipher_MODE_CBC()
        if code_method.lower() == "base64":
            cipher_text = base64.decodebytes(cipher_text.encode("utf-8"))
        elif code_method.lower() == "hex":
            cipher_text = binascii.a2b_hex(cipher_text.encode("utf-8"))
        else:
            cipher_text = cipher_text.encode("utf-8")
        return self.unpad_method(self.__x.decrypt(cipher_text).decode("utf-8"), pad_method)

    def text_verify(self, text, method):
        while len(text) > len(self.__key):
            text_slice = text[:len(self.__key)]
            text = text[len(self.__key):]
            yield text_slice
        else:
            if len(text) == len(self.__key):
                yield text
            else:
                yield self.pad_method(text, method)

    def pad_method(self, text, method):
        if method == "":
            return Cipher_AES.pad_default(text, len(self.__key))
        elif method == "PKCS5Padding":
            return Cipher_AES.pad_pkcs5(text, len(self.__key))
        else:
            return Cipher_AES.pad_user_defined(text, len(self.__key), method)

    def unpad_method(self, text, method):
        if method == "":
            return Cipher_AES.unpad_default(text)
        elif method == "PKCS5Padding":
            return Cipher_AES.unpad_pkcs5(text)
        else:
            return Cipher_AES.unpad_user_defined(text, method)


# 解密
def dencryption(text):
    key = "16位数字字母"
    iv = key[::-1]
    cipher_method = "MODE_CBC"
    pad_method = "PKCS5Padding"
    code_method = "base64"
    text2 = Cipher_AES(key, iv).decrypt(text, cipher_method, pad_method, code_method)
    return text2


# 加密
def encryption(text):
    key = "和解密的key保持一致"
    iv = key[::-1]
    cipher_method = "MODE_CBC"
    pad_method = "PKCS5Padding"
    code_method = "base64"
    cipher_text = Cipher_AES(key, iv).encrypt(text, cipher_method, pad_method, code_method)
    return cipher_text

使用方法在上面了。直接复制粘贴就能用了,注意key的更改。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值