python3 3des des aes 加密 PKCS7 填充

首先感谢 孤影惆怅 大佬的文章 得以完美安装好了PyCrypto
文章地址:http://blog.csdn.net/a624806998/article/details/78596543

使用PyCrypto包的 AES 加密
3des des 和 aes 没什么差别
把 import的 AES改成 3DES 或者你想要的加密方式 记得把加密mode 改了

from Crypto.Cipher import AES
import base64
BS = AES.block_size


def pad(s): 
    return s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
#定义 padding 即 填充 为PKCS7

def unpad(s): 
    return s[0:-ord(s[-1])]


class prpcrypt():  
    def __init__(self, key):
        self.key = key
        self.mode = AES.MODE_CBC
    # AES的加密模式为CBC
    def encrypt(self, text):
        text = pad(text)
        cryptor = AES.new(self.key, self.mode, self.key)
        #第二个self.key 为 IV 即偏移量
        x = len(text) % 8
        if x != 0:
            text = text + '\0' * (8 - x)  # 不满16,32,64位补0
        print(text)
        self.ciphertext = cryptor.encrypt(text)
        return base64.standard_b64encode(self.ciphertext).decode("utf-8")

    def decrypt(self, text):
        cryptor = AES.new(self.key, self.mode, self.key)
        de_text = base64.standard_b64decode(text)
        plain_text = cryptor.decrypt(de_text)
        st = str(plain_text.decode("utf-8")).rstrip('\0')
        out = unpad(st)
        return out


pc = prpcrypt('ningbozhihuirend')  # 自己设定的密钥
e = pc.encrypt("hello")  # 加密内容
d = pc.decrypt(e)
print("加密后%s,解密后%s" % (e, d))

3DES DES 可以参照 stackoverflow 上大佬的给的解决方案
用的不是pycrypto 而是pydes

https://stackoverflow.com/questions/2435283/using-des-3des-with-python

猜你喜欢

转载自blog.csdn.net/qq_33042187/article/details/78921355