#encoding=utf-8
# pip install pycrypto
import binascii
from Crypto.Cipher import AES
from Crypto.Cipher import DES
import hashlib
def PCS7(src, blockSize = 16):
padLen = blockSize - len(src) % blockSize
text = src + chr(padLen) * padLen
return text
def unPCS7(src, blocksize = 16):
if (len(src) % blocksize != 0):
return src
padNum = ord(src[-1])
return src[0:len(src) - padNum]
def AesCbcEncode(src, key, iv):
cryp = AES.new(key, AES.MODE_CBC, iv)
padSrc = PCS7(src)
return cryp.encrypt(padSrc)
def AesCbcDecode(src, key, iv):
cryp = AES.new(key, AES.MODE_CBC, iv)
src = cryp.decrypt(src)
return unPCS7(src)
def DesEncode(src, key, iv):
cryp = DES.new(key, DES.MODE_CBC, iv)
src = PCS7(src, 8)
return cryp.encrypt(src)
def DesDecode(src, key, iv):
cryp = DES.new(key, DES.MODE_CBC, iv)
src = cryp.decrypt(src)
return unPCS7(src, 8)
def aesEx():
src = "testAes"
key = "6b2f62a6482bef462219387c20b0ed89"
iv = "1234567890ABCDEF"
cipher = AesCbcEncode(src, key, iv)
print binascii.b2a_hex(cipher)
resrc = AesCbcDecode(cipher, key, iv)
print resrc
if resrc == src:
print 'test aes suc'
else:
print 'test aes fail'
def desEx():
src = 'testDes1'
key = "6b2f14zd"
iv = "12345678"
cipher = DesEncode(src, key, iv)
print binascii.b2a_hex(cipher)
resrc = DesDecode(cipher, key, iv)
print resrc
if resrc == src:
print 'test des suc'
else:
print 'test des fail'
def hash(src):
md5 = hashlib.md5()
md5.update(src)
print md5.hexdigest()
print binascii.b2a_hex(md5.digest())
sha = hashlib.sha256()
sha.update(src)
print sha.hexdigest()
if __name__ == '__main__':
# aesEx()
# desEx()
hash('daf')
Python AES/DES/MD5 加密
最新推荐文章于 2023-10-22 16:08:23 发布