Python Python AES 對稱加密示例

2022-04-01 02:59:46 字數 1458 閱讀 5393

**:

import sys

from

crypto.cipher import aes

from

binascii import b2a_hex, a2b_hex

aes_secret_key = '

此處16|24|32個字元

'class aes_encrypt(object

): def __init__(self):

self.key =aes_secret_key

self.mode =aes.mode_cbc

#加密函式,如果text不是16的倍數【加密文字text必須為16的倍數!】,那就補足為16的倍數

def encrypt(self, text):

#cryptor = aes.new

(self.key, self.mode, self.key)

cryptor = aes.new

(self.key, self.mode)

#這裡金鑰key 長度必須為16(aes-128)、24(aes-192)、或32(aes-256)bytes 長度.目前aes-128足夠用

length = 16

count =len(text)

add = length - (count %length)

text = text + ('

\0' *add)

self.ciphertext =cryptor.encrypt(text)

#因為aes加密時候得到的字串不一定是ascii字符集的,輸出到終端或者儲存時候可能存在問題

#所以這裡統一把加密後的字串轉化為16進製制字串

return

b2a_hex(self.ciphertext)

#解密後,去掉補足的空格用strip() 去掉

def decrypt(self, text):

#cryptor = aes.new

(self.key, self.mode, self.key)

cryptor = aes.new

(self.key, self.mode)

plain_text =cryptor.decrypt(a2b_hex(text))

return plain_text.rstrip('\0'

) if __name__ == '

__main__':

aes_encrypt =aes_encrypt() #初始化金鑰

customer_id = "

3f500ac5-020d-3ce3-a2a2-51a59ddd606e

"e =aes_encrypt.encrypt(customer_id)

d =aes_encrypt.decrypt(e)

print customer_id

print e

print d

對稱加密 非對稱加密

區別在於加密金鑰和解密金鑰是否一樣,一樣則是對稱加密,不一樣則是非對稱加密。對稱加密計算量小,但若不同的客戶端使用不能的金鑰時,伺服器的複雜大。常用的對稱加密包括 des 3des aes des 3des使用的架構為feistel。des金鑰長度為56位,3des相容des,可設定3個56位密碼,...

對稱加密 非對稱加密

1 對稱加密 對稱加密採用了對稱密碼編碼技術,它的特點是檔案加密和解密使用相同的金鑰,即加密金鑰也可以用作解密金鑰,這種方法在密碼學中叫做對稱加密演算法,對稱加密演算法使用起來簡單快捷,金鑰較短,且破譯困難,除了資料加密標準 des 另乙個對稱金鑰加密系統是國際資料加密演算法 idea 它比des的...

對稱加密 非對稱加密

演算法選擇 對稱加密aes,非對稱加密 ecc,訊息摘要 md5,數字簽名 dsa 對稱加密演算法 加解密金鑰相同 名稱金鑰長度 運算速度 安全性資源消耗 des56位較快低 中3des 112位或168位慢中 高aes 128 192 256位快高 低非對稱演算法 加密金鑰和解密金鑰不同 名稱成熟...