本文實例講述了python實現無證書加密解密的方法,分享給大家供大家參考。具體實現方法如下:
無證書加密就是雙方不需要維護證書,加密與解密只需要雙方約定一個key就可以,無證書加解密的方式應用更廣泛一些,python官方也有這方面的相關例子說明,地址是:https://pypi.python.org/pypi/pycrypto,主要用的是from Crypto.Cipher import AES這個模塊,代碼如下:
代碼如下:'''
/**
* AES加密字符串
*
* @param string data 加密的串
* @param string key 密鑰(只能是16、24、32位)
* @param string iv 16位長度向量
* @param bool 編碼格式(true:base64 / false:十六進制)
* @return string 加密后的結果
*/
'''
def encrypt_mode_cbc(data, key, iv = 'www.jb51.net!!', base64 = True):
lenth = len(data)
num = lenth % 16
data = data.ljust(lenth + 16 - num)
obj = AES.new(key, AES.MODE_CBC, iv)
result = obj.encrypt(data)
return result.encode('base64') if base64 is True else result.encode('hex')
encrypt = encrypt_mode_cbc('hello geekso', 'www.jb51.net!!')
print encrypt
'''
/**
* AES解密字符串
*
* @param string encrypted 待解密的串
* @param string key 密鑰
* @param string iv 16位長度向量
* @param bool 編碼(true:base64 / false:十六進制)
* @return string 解密后的結果 or bool
*/
'''
def decrypt_mode_cbc(encrypted, key, iv = 'www.jb51.net!!', base64 = True):
encrypted = encrypted.decode('base64') if base64 is True else encrypted.decode('hex')
if encrypted is not '':
obj = AES.new(key, AES.MODE_CBC, iv)
return obj.decrypt(encrypted)
else:
return False
print decrypt_mode_cbc(encrypt,'www.jb51.net!!')
exit()
希望本文所述對大家的Python程序設計有所幫助。
新聞熱點
疑難解答