一:crypto库装置

pycrypto,pycryptodome是crypto第三方库,pycrypto曾经进行更新三年了,所以不倡议装置这个库;pycryptodome是pycrypto的延长版本,用法和pycrypto 是截然不同的;所以只须要装置pycryptodome就能够了

pip install pycryptodome

二:python应用crypto

1:crypto的加密解密组件des.py

#!/usr/bin/env python# -*- coding: utf-8 -*-from Crypto.Cipher import DESfrom binascii import b2a_hex, a2b_hexclass MyDESCrypt: #本人实现的DES加密类    def __init__(self, key = ''):        #密钥长度必须为64位,也就是8个字节        if key is not '':            self.key = key.encode('utf-8')        else:            self.key = '12345678'.encode('utf-8')        self.mode = DES.MODE_CBC    # 加密函数,如果text有余16位就用空格补足为16位,    # 如果大于16过后不是16的倍数,那就补足为16的倍数。    def encrypt(self,text):        try:            text = text.encode('utf-8')            cryptor = DES.new(self.key, self.mode, self.key)            # 这里密钥key 长度必须为16(DES-128),            # 24(DES-192),或者32 (DES-256)Bytes 长度            # 目前DES-128 足够目前应用            length = 16   #lenth能够设置为8的倍数            count = len(text)            if count < length:                add = (length - count)                # \0 backspace                # text = text + ('\0' * add)                text = text + ('\0' * add).encode('utf-8')            elif count > length:                add = (length - (count % length))                # text = text + ('\0' * add)                text = text + ('\0' * add).encode('utf-8')            self.ciphertext = cryptor.encrypt(text)            # 因为DES加密时候失去的字符串不肯定是ascii字符集的,输入到终端或者保留时候可能存在问题            # 所以这里对立把加密后的字符串转化为16进制字符串            return b2a_hex(self.ciphertext)        except:            return ""    # 解密后,去掉补足的空格用strip() 去掉    def decrypt(self, text):        try:            cryptor = DES.new(self.key, self.mode, self.key)            plain_text = cryptor.decrypt(a2b_hex(text))            # return plain_text.rstrip('\0')            return bytes.decode(plain_text).rstrip('\0')        except:            return ""

2:crypto组件应用

from . import desmsg = "password is 961223"key = "12345678"  #key值可传可不传des1 = des.MyDESCrypt()#加密cipherTxt = des1.encrypt(msg)  #返回值为bytes型print(cipherTxt)#解密decTxt = des1.decrypt(cipherTxt);  #返回值为str型print(decTxt)