Python3 AES加解密 手把手教学

第一步 安装python第三方包 pycryptodome

pip install pycryptodome

第二步 使用密钥新建aes加解密对象

from Crypto.Cipher import AES

KEY = '你的密钥'  # 必须是16位, 32位等2的4+次幂 

# 使用你的KEY创建加密对象, 加密模式为ECB
# 这里使用ECB比较方便, 但是据说安全性比其他模式稍差(安全方面没有了解过)
aes = AES.new(str.encode(KEY), AES.MODE_ECB)

第三步 加密

这里一般需要使用到base64包

import base64
pwd = '你的密码string'  # 密码不足16位向左补@符号, 并转换为bytes 
encode_pwd = str.encode(pwd.rjust(16, '@')) # 使用aes加密bytes并使用base64编码bytes 
encrypt_str = str(base64.encodebytes(aes.encrypt(encode_pwd)), encoding='utf-8')

encrypt_str就是你获得的加密后的字符串

第四步 解密

decrypt_str = (aes.decrypt(base64.decodebytes(encrypt_str.encode(encoding='utf-8'))).decode().replace('@', ''))

说明:

  1. 先使用base64解码encrypt_str的bytes
  2. 再使用aes.decrypt解密bytes
  3. 使用decode() 将解密后的bytes转化为str
  4. 使用replace替换掉之前补位用的@符号

完整代码如下(辣鸡代码随意转载使用):

import base64
from Crypto.Cipher import AES

KEY = '你的密钥'  # 必须是16位, 32位等2的4+次幂
aes = AES.new(str.encode(KEY), AES.MODE_ECB)

pwd = '你的密码string'

# 密码不足16位向左补@符号, 并转换为bytes
encode_pwd = str.encode(pwd.rjust(16, '@'))
# 使用aes加密bytes并使用base64编码bytes
encrypt_str = str(base64.encodebytes(aes.encrypt(encode_pwd)), encoding='utf-8')

decrypt_str = (
        aes.decrypt(base64.decodebytes(encrypt_str.encode(encoding='utf-8')))
        .decode()
        .replace('@', '')
    )

你可能感兴趣的:(Python3 AES加解密 手把手教学)