python加密解密

1. md5加密

方法一:使用Crypto

from  Crypto.Hash import MD5

md5 = MD5.new()
md5.update('1111')
print md5.hexdigest()

方法二:使用hashlib

import hashlib

md5 = hashlib.md5()
md5.update('1111')
print md5.hexdigest()
2. AES加密解密

导入库

from Crypto.Cipher import AES
from Crypto import Random

加密

def myEncrypt(textEncrypt, password):

    bs = AES.block_size
    pad = lambda s: s + (bs - len(s) % bs) * chr(bs - len(s) % bs)
    iv = Random.new().read(bs)
    cipher = AES.new(password, AES.MODE_CBC, iv)
    data = cipher.encrypt(pad(textEncrypt))
    data =iv + data

    return data

解密

def myDecrypt(data, password):

    bs = AES.block_size
    if len(data) <= bs:
        return data
    unpad = lambda s: s[0:-ord(s[-1])]
    iv = data[:bs]
    cipher = AES.new(password, AES.MODE_CBC, iv)
    data = unpad(cipher.decrypt(data[bs:]))
    print data.encode('hex')
    return data

你可能感兴趣的:(python加密解密)