生活随笔
收集整理的這篇文章主要介紹了
【Python】pyCryptodome模块实现AES加密、解密
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
高級加密標準(英語:Advanced Encryption Standard,縮寫:AES),在密碼學中又稱Rijndael加密法,是美國聯邦政府采用的一種區塊加密標準。這個標準用來替代原先的DES,已經被多方分析且廣為全世界所使用。經過五年的甄選流程,高級加密標準由美國國家標準與技術研究院(NIST)于2001年11月26日發布于FIPS PUB 197,并在2002年5月26日成為有效的標準。2006年,高級加密標準已然成為對稱密鑰加密中最流行的算法之一。
本文主要通過pycryptodome庫進行AES的簡單加解密。
# -*- coding: utf-8 -*-
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#作者:cacho_37967865
#博客:https://blog.csdn.net/sinat_37967865
#文件:encryption.py
#日期:2019-07-31
#備注:多種加解密方法 # pip install pycryptodome
用pyCryptodome模塊帶的aes先將秘鑰以及要加密的文本填充為16位 AES key must be either 16, 24, or 32 bytes long
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
import base64
from Crypto.Cipher import AES# bytes不是32的倍數那就補足為32的倍數
def add_to_32(value):while len(value) % 32 != 0:value += b'\x00'return value # 返回bytes# str轉換為bytes超過32位時處理
def cut_value(org_str):org_bytes = str.encode(org_str)n = int(len(org_bytes) / 32)print('bytes長度:',len(org_bytes))i = 0new_bytes = b''while n >= 1:i = i + 1new_byte = org_bytes[(i-1)*32:32*i-1]new_bytes += new_byten = n - 1if len(org_bytes) % 32 == 0: # 如果是32的倍數,直接取值all_bytes = org_byteselif len(org_bytes) % 32 != 0 and n>1: # 如果不是32的倍數,每次截取32位相加,最后再加剩下的并補齊32位all_bytes = new_bytes + add_to_32 (org_bytes[i*32:])else:all_bytes = add_to_32 (org_bytes) # 如果不是32的倍數,并且小于32位直接補齊print(all_bytes)return all_bytesdef AES_encrypt(org_str,key):# 初始化加密器aes = AES.new(cut_value(key), AES.MODE_ECB)#先進行aes加密encrypt_aes = aes.encrypt(cut_value(org_str))# 用base64轉成字符串形式encrypted_text = str(base64.encodebytes(encrypt_aes), encoding='utf-8') # 執行加密并轉碼返回bytesprint(encrypted_text)return(encrypted_text)def AES_decrypt(secret_str,key):# 初始化加密器aes = AES.new(cut_value(key), AES.MODE_ECB)# 優先逆向解密base64成bytesbase64_decrypted = base64.decodebytes(secret_str.encode(encoding='utf-8'))# 執行解密密并轉碼返回strdecrypted_text = str(aes.decrypt(base64_decrypted), encoding='utf-8').replace('\0', '')print(decrypted_text)if __name__ == '__main__':org_str = 'http://mp.weixin.qq.com/s?__biz=MjM5NjAxOTU4MA==&mid=3009217590&idx=1&sn=14532c49bc8cb0817544181a10e9309f&chksm=90460825a7318133e7905c02e708d5222abfea930e61b4216f15b7504e39734bcd41cfb0a26d&scene=27#wechat_redirect'# 秘鑰key = '123abc'secret_str = AES_encrypt(org_str,key)AES_decrypt(secret_str,key)
總結
以上是生活随笔為你收集整理的【Python】pyCryptodome模块实现AES加密、解密的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。