python实现DES算法

pycrypto库下载:http://pan.baidu.com/s/1nvNtCvB (python2.7的版本),直接安装就可以了

from Crypto.Cipher import DES #第三方库导入,没有的话去百度云下载

class MyDESCrypt: #自己实现的DES加密类

    key = chr(11)+chr(11)+chr(11)+chr(11)+chr(11)+chr(11)+chr(11)+chr(11)
    iv = chr(22)+chr(22)+chr(22)+chr(22)+chr(22)+chr(22)+chr(22)+chr(22)

    def __init__(self,key='',iv=''):
        if len(key)> 0:
            self.key = key
        if len(iv)>0 :
            self.iv = iv

    def ecrypt(self,ecryptText):
       try:
           cipherX = DES.new(self.key, DES.MODE_CBC, self.iv)
           pad = 8 - len(ecryptText) % 8
           padStr = ""
           for i in range(pad):
              padStr = padStr + chr(pad)
           ecryptText = ecryptText + padStr
           x = cipherX.encrypt(ecryptText)
           return x.encode('hex_codec').upper()
       except:
           return ""


    def decrypt(self,decryptText):
        try:

            cipherX = DES.new(self.key, DES.MODE_CBC, self.iv)
            str = decryptText.decode('hex_codec')
            y = cipherX.decrypt(str)
            return y[0:ord(y[len(y)-1])*-1]
        except:
            return ""
def     main():

        msg = "password is 961223"
        key = "stupid00" #密钥长度必须为64位,也就是8个字节
        des = DES.MyDESCrypt(key)
        cipherTxt = des.ecrypt(msg)
        print cipherTxt

        print des.decrypt(cipherTxt)
if      __name__== "__main__":
        main()

python实现DES算法_第1张图片

你可能感兴趣的:(python,密码学)