#coding: utf8
import
sysfrom crypto.cipher import
aesfrom binascii import
b2a_hex, a2b_hex
class
prpcrypt():
def__init__
(self, key):
self.key =key
self.mode =aes.mode_cbc
#加密函式,如果text不是16的倍數【加密文字text必須為16的倍數!】,那就補足為16的倍數
defencrypt(self, text):
cryptor =aes.new(self.key, self.mode, self.key)
#這裡金鑰key 長度必須為16(aes-128)、24(aes-192)、或32(aes-256)bytes 長度.目前aes-128足夠用
length = 16count =len(text)
add = length - (count %length)
text = text + ('
\0' *add)
self.ciphertext =cryptor.encrypt(text)
#因為aes加密時候得到的字串不一定是ascii字符集的,輸出到終端或者儲存時候可能存在問題
#所以這裡統一把加密後的字串轉化為16進製制字串
return
b2a_hex(self.ciphertext)
#解密後,去掉補足的空格用strip() 去掉
defdecrypt(self, text):
cryptor =aes.new(self.key, self.mode, self.key)
plain_text =cryptor.decrypt(a2b_hex(text))
return plain_text.rstrip('\0'
) if__name__ == '
__main__':
pc = prpcrypt('
douniwandouniwan
') #
初始化金鑰
e = pc.encrypt("
00000")
d = pc.decrypt(e)
e, d
e = pc.encrypt("
heheheeheheh")
d = pc.decrypt(e)
print e, d
Python 實現 AES 加密 解密
一 前言 金鑰 k 用來加密明文的密碼,在對稱加密演算法中,加密與解密的金鑰是相同的。金鑰為接收方與傳送方協商產生,但不可以直接在網路上傳輸,否則會導致金鑰洩漏,通常是通過非對稱加密演算法加密金鑰,然後再通過網路傳輸給對方,或者直接面對面商量金鑰。金鑰是絕對不可以洩漏的,否則會被攻擊者還原密文,竊取...
Python實現AES加密解密
報錯 typeerror decrypt cannot be called after encrypt 原因 cryptor不能寫在主函式中同時給加密函式與解密函式使用,儘管加密解密都是用 cryptor aes.new key,mode,iv 但若將其定義在main並分別傳給加密解密同時使用時,會...
python實現AES的加密解密
了解aes aes advanced encryption standard 是一種對稱加密演算法,相較於des和3des演算法而言,aes演算法有著更高的速度和資源使用效率,安全級別也較之更高 公式 c e k,p 明文p,金鑰k,aes加密函式組成e,密文c。主要要了解以下幾點 aes金鑰的長度...