Python基础第10课-Python加密解密

安装加解密模块
pip3 install pycryptodome -i https://pypi.tuna.tsinghua.edu.cn/simple
 
库参考文档:
密码学概述:
    对称加密Symmetric:
        流密码:
            ChaCha20 、 Salsa20、RC4……
        块密码:
            DES,3DES,AES……
    非对称加密:
        RSA,ECC……
    哈希Hash
        MD5,SHA1,SHA2,SHA256……
AES加密算法:
AES加密模式:
 
AES类与使用:
 
 
AES函数库:
首先要new一个AES加密(或解密)对象,传入密钥,加密模式,初始向量等
 AES.new(key, AES.MODE_CFB, iv)
然后,加密
cipher.encrypt(str)
注意点:
    1.AES是块加密,加密前要pad一下,解密后要unpad一下
    2.AES字节加密,Bytes串传入底层C模块,要从String转换一下
 
附上自写的加解密模块代码
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Hash import SHA256


class MyAesEncrypt:
cipher = None

# 初始化 ,传入Key,用keysha256AES密钥,再取密钥的前**位的哈希作初始向量
def __init__(self, key, iv=None):
key = bytes(key, encoding="UTF-8")
key = SHA256.new(data=key).digest()
if (iv == None):
iv = SHA256.new(data=key).digest()[:AES.block_size]
# self.peepBytes(key, "key")
# self.peepBytes(iv, "iv")
self.cipher = AES.new(key, AES.MODE_CFB, iv)

# 静态方法,查看密钥
@staticmethod
def peepBytes(a, str="peepBytes"):
print(str, end=":")
for i in a:
print("%02x" % i, end="")
print("")

# 加密方法
def Encrypt(self, str):
str = bytes(str, encoding="UTF-8")
str = pad(str, AES.block_size)
return self.cipher.encrypt(str)


class MyAesDecrypt:
uncipher = None

def __init__(self, key, iv=None):
key = bytes(key, encoding="UTF-8")
key = SHA256.new(data=key).digest()
if (iv == None):
iv = SHA256.new(data=key).digest()[:AES.block_size]
self.uncipher = AES.new(key, AES.MODE_CFB, iv)

# 解密方法
def Decrypt(self, byte_str):
str = unpad(self.uncipher.decrypt(byte_str), AES.block_size)
return str.decode("UTF-8")


if __name__ == "__main__":
a = MyAesEncrypt("hello")
str = a.Encrypt("你好hello world")

b = MyAesDecrypt("hello")
print(b.Decrypt(str))
 
 
 
 

<wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">





原文地址:https://www.cnblogs.com/MarmaladeCat/p/62e365fd71aa50eff2bb6aebde637d81.html