1. 程式人生 > >AES(高級加密)

AES(高級加密)

array ear asd pip 格式 創建 nco == ssa

AES(高級加密)

3.6安裝  pip3 install pycryptodome

a. 事例:

############################### 加密 ##############################

	from Crypto.Cipher import AES
	def encrypt(message):
	    key = b‘dfdsdfsasdfdsdfs‘						#key必須是16的整數倍
	    cipher = AES.new(key, AES.MODE_CBC, key)		#創建對象
	    ----------------------------------------------
	    #先轉成字節,把數據拼夠16字節的整數倍
	    ba_data = bytearray(message,encoding=‘utf-8‘)	#把數據轉成bytearray(byte的數組),bytearray只能追加數字,默認把數字轉成字節
	    v1 = len(ba_data)
	    v2 = v1 % 16
	    if v2 == 0:
	        v3 = 16
	    else:
	        v3 = 16 - v2								#v3是追加的長度
	    for i in range(v3):
	        ba_data.append(v3)							#bytearray只能追加數字,默認把數字轉成字節
	    final_data = ba_data.decode(‘utf-8‘)
		----------------------------------------------
	    msg = cipher.encrypt(final_data) 				#要加密的字符串,必須是16個字節或16個字節的倍數,加密後是byte格式
	    return msg

############################### 解密 ##############################
	def decrypt(msg):
	    key = b‘dfdsdfsasdfdsdfs‘
	    cipher = AES.new(key, AES.MODE_CBC, key)
	    result = cipher.decrypt(msg)					#把加密後的字節解密成不加密的字節
	    data = result[0:-result[-1]]
	    return str(data,encoding=‘utf-8‘)

  

wuSir  

AES(高級加密)