当前位置: 首页 > 后端技术 > Python

Python使用Crypto库实现加解密

时间:2023-03-26 14:53:47 Python

一:安装crypto库中的pycrypto,pycryptodome是crypto的第三方库,pycrypto已经停止更新三年了,所以不建议安装这个库;pycryptodome是pycrypto的扩展版,用法和pycrypto完全一样;所以你只需要安装pycryptodomepipinstallpycryptodome2:python使用crypto1:crypto的加解密组件des.py#!/usr/bin/envpython#-*-coding:utf-8-*-fromCrypto.CipherimportDESfrombinasciiimportb2a_hex,a2b_hexclassMyDESCrypt:#自己实现的DES加密类def__init__(self,key=''):#密钥长度必须是64位,即如果key不是''则为8字节:self.key=key.encode('utf-8')else:self.key='12345678'.encode('utf-8')self.mode=DES.MODE_CBC#加密函数,如果文本小于16位,用空格补到16位,#如果大于16,当时不是16的倍数,那就补上16的倍数。defencrypt(self,text):try:text=text.encode('utf-8')cryptor=DES.new(self.key,self.mode,self.key)#这里的密钥长度必须是16(DES-128),#24(DES-192),or32(DES-256)Byteslength#目前DES-128足够当前使用length=16#lenth可以设置为8的倍数count=长度(文本)ifcountlength:add=(length-(count%length))#text=text+('\0'*add)text=text+('\0'*add).encode('utf-8')self.ciphertext=cryptor.encrypt(text)#因为DES加密时得到的字符串不一定是ascii字符集,输出到终端或者保存的时候可能会有问题#所以这里我们将加密后的字符串转换为16-in使字符串返回b2a_hex(self.ciphertext)except:return""#解密后,去除补充空格并使用strip()去除defdecrypt(self,text):try:cryptor=DES.new(self.key,self.mode,self.key)plain_text=cryptor.decrypt(a2b_hex(text))#returnplain_text.rstrip('\0')returnbytes.decode(plain_text).rstrip('\0')除了:返回“”2:加密组文件使用自。importdesmsg="passwordis961223"key="12345678"#key值可不可以传decTxt=des1.decrypt(cipherTxt);#返回值为str类型print(decTxt)