aes256加密如何在python項(xiàng)目中實(shí)現(xiàn)?相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。

基礎(chǔ)知識(shí)
# 在Linux操作系統(tǒng)下,Python3的默認(rèn)環(huán)境編碼變?yōu)榱藆tf-8編碼,所以在編寫(xiě)代碼的時(shí)候,字符串大部分都是以u(píng)tf-8處理
UTF-8:
1byte = 8bit
1個(gè)英文字符 = 1byte
1個(gè)中文字符 = 3byte
128bit = 16byte = 16個(gè)英文字符
192bit = 24byte = 24個(gè)英文字符
256bit = 32byte = 32個(gè)英文字符
AES256概念
AES是一種對(duì)稱(chēng)加密算法,對(duì)稱(chēng)指加密和解密使用同一個(gè)密鑰; 256指密鑰的長(zhǎng)度是256bit,即32個(gè)英文字符的長(zhǎng)度;密鑰的長(zhǎng)度決定了AES加密的輪數(shù)
AES256加密參數(shù)
密鑰: 一個(gè)32byte的字符串, 常被叫為key
明文: 待加密的字符串;字節(jié)長(zhǎng)度(按byte計(jì)算)必須是16的整數(shù)倍,因此,明文加密之前需要被填充
模式: 加密模式,常用的有ECB、CBC;具體含義見(jiàn)參考鏈接
iv 偏移量: CBC模式下需要是16byte字符串; ECB下不需要
參考代碼
# -------------------------------
# -*- coding: utf-8 -*-
# @Author:jianghan
# @Time:2020/11/25 14:46
# @File: crypt.py
# Python版本:3.6.8
# -------------------------------
"""
1、 填充字符串和明文字符串最后一位不能相同
2、 字符串編碼默認(rèn)是utf-8, key和iv默認(rèn)為英文字符;字符串不支持其他編碼或key/iv不支持為中文字符
"""
from enum import Enum, unique
from Crypto.Cipher import AES
@unique
class Mode(Enum):
CBC = AES.MODE_CBC
ECB = AES.MODE_ECB
@unique
class Padding(Enum):
""" 定義填充的字符串 """
SPACE = ' ' # 空格
class AES256Crypto:
def __init__(self, key, mode=Mode.ECB, padding=Padding.SPACE, iv=None):
"""
:param key: 密鑰, 32byte 長(zhǎng)度字符串
:param mode: 加密模式, 來(lái)源 class Mode
:param iv: 16byte 長(zhǎng)度字符串
:param padding: 填充的字符串, 來(lái)源class Padding
"""
self.padding = self.check_padding(padding)
self.key = self.padding_key(key)
self.iv = self.padding_iv(iv) if iv else None
self.mode = self.check_mode(mode)
def check_mode(self, mode):
""" 核對(duì) mode """
if mode not in Mode.__members__.values():
raise Exception(f'mode {mode} not allowed!')
if mode == Mode.CBC and not self.iv:
raise Exception(f'iv is required')
return mode
def check_padding(self, padding):
""" 核對(duì) padding """
if padding not in Padding.__members__.values():
raise Exception(f'mode {padding} not allowed!')
return padding
def padding_ret_byte(self, text, _len=16):
""" 填充并轉(zhuǎn)成 bytes """
text = text.encode()
remainder = len(text) % _len
remainder = _len if remainder == 0 else remainder
text += (_len - remainder) * self.padding.value.encode()
return text
def padding_iv(self, iv: str):
""" 補(bǔ)全iv 并轉(zhuǎn)成 bytes"""
if len(iv.encode()) > 16:
raise Exception(f'iv {iv} must <= 16bytes')
return self.padding_ret_byte(iv)
def padding_key(self, key: str):
""" 補(bǔ)全key 并轉(zhuǎn)成 bytes """
if len(key.encode()) > 32:
raise Exception(f'key {key} must <= 32bytes')
return self.padding_ret_byte(key, _len=32)
def encrypt(self, text, encode=None):
"""
加密
:param text: 待加密字符串
:param encode: 傳入base64里面的方法
:return: 若encode=None則不進(jìn)行base加密處理,返回bytes類(lèi)型數(shù)據(jù)
"""
text = self.padding_ret_byte(text)
# 注意:加密中的和解密中的AES.new()不能使用同一個(gè)對(duì)象,所以在兩處都使用了AES.new()
text = AES.new(key=self.key, mode=self.mode.value, iv=self.iv).encrypt(text)
if encode:
return encode(text).decode()
return text
def decrypt(self, text, decode=None):
""" 解密 """
if decode:
if type(text) == str:
text = text.encode()
text = decode(bytes(text))
else:
if type(text) != bytes:
raise Exception(text)
text = AES.new(key=self.key, mode=self.mode.value, iv=self.iv).decrypt(text)
text = text.strip(self.padding.value.encode())
return text.decode()使用范例
import json
# 這是一段待加密的字符串
text = '{"upi": "1341343", "overdue": "2020-11-26 00:00:00"}'
key = 't6LtKa3tD5X6qaJ6qOrAW3XmobFrY6ob'
iv = 'NjtP47eSECuOm3s6'
aes = AES256Crypto(key, Mode.CBC, Padding.SPACE, iv)
text_1 = aes.encrypt(text)
# b'\xe7\x1d\xeae\xff\xc7\xc2\xd7\x8c\xf6\xe7\x82u\x7f\x168\xbc\x90\xad\x1e\x85M\xcb\xb0\xb4Ho\x1b\xe4\xec\x9d\x1d\xf93\xeb\x9b\xe7\xa3\xdd$\x8cEa\xab\xf7K~\x91H\xc3]5\xc4\x1a\xd4w[\x83\xb2"FC\x9f\x9d'
text_2 = aes.decrypt(text_1)
# '{"upi": "1341343", "overdue": "2020-11-26 00:00:00"}'
import base64
text_3 = aes.encrypt(text, encode=base64.b16encode)
# 'E71DEA65FFC7C2D78CF6E782757F1638BC90AD1E854DCBB0B4486F1BE4EC9D1DF933EB9BE7A3DD248C4561ABF74B7E9148C35D35C41AD4775B83B22246439F9D'
text_4 = aes.decrypt(text_3, decode=base64.b16decode)
# '{"upi": "1341343", "overdue": "2020-11-26 00:00:00"}'看完上述內(nèi)容,你們掌握aes256加密如何在python項(xiàng)目中實(shí)現(xiàn)的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
分享題目:aes256加密如何在python項(xiàng)目中實(shí)現(xiàn)-創(chuàng)新互聯(lián)
文章出自:http://chinadenli.net/article0/gcdoo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供Google、網(wǎng)站內(nèi)鏈、品牌網(wǎng)站制作、商城網(wǎng)站、網(wǎng)站收錄、手機(jī)網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容