DDR爱好者之家 Design By 杰米

AES加密方式有五种 : ECB, CBC, CTR, CFB, OFB

从安全性角度推荐cbc算法

windows 下安装 : pip install pycryptodome

linux 下安装 : pip install pycrypto

cbc加密需要一个十六位的key 和一个十六位的iv(偏移量)

ecb加密不需要iv

aes cbc 加密的python实现

from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex

# 如果text不足十六位的倍数用空格补充
def add_to_16(text):
  if len(text.encode('utf8')) % 16:
    add = 16 - (len(text.encode('utf8')) % 16)
  else:
    add = 0
  text = text + '\0' * add
  return text

# 加密
def encrypt(text):
  key = '9999999999999999'.encode('utf8')
  mode = AES.MODE_CBC
  iv = b'qqqqqqqqqqqqqqqq'
  text = add_to_16(text)
  cryptos = AES.new(key, mode, iv)
  cipher_text = cryptos.encrypt(text)
  # 因为AES加密后的字符串不一定是ascii字符集的,输出保存可能存在问题,所以这里转为16进制字符串
  return b2a_hex(cipher_text)

# 解密后去掉空格
def decrypt(text):
  key = '9999999999999999'.encode('utf8')
  mode = AES.MODE_CBC
  iv = b'qqqqqqqqqqqqqqqq'
  cryptos = AES.new(key, mode, iv)
  plain_text = cryptos.decrypt(a2b_hex(text))
  return bytes.decode(plain_text).rstrip('\0')

if __name__ == '__main__':
  a = encrypt('hello')
  b = decrypt(a)
  print('加密', a)
  print('解密', b)

aes ecb加密, 没有偏移量iv

from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex

# 如果text不足十六位的倍数用空格补充
def add_to_16(text):
  if len(text.encode('utf8')) % 16:
    add = 16 - (len(text.encode('utf8')) % 16)
  else:
    add = 0
  text = text + '\0' * add
  return text

# 加密
def encrypt(text):
  key = '9999999999999999'.encode('utf8')
  mode = AES.MODE_ECB
  text = add_to_16(text)
  cryptos = AES.new(key, mode)
  cipher_text = cryptos.encrypt(text)
  # 因为AES加密后的字符串不一定是ascii字符集的,输出保存可能存在问题,所以这里转为16进制字符串
  return b2a_hex(cipher_text)

# 解密后去掉空格
def decrypt(text):
  key = '9999999999999999'.encode('utf8')
  mode = AES.MODE_ECB
  cryptos = AES.new(key, mode)
  plain_text = cryptos.decrypt(a2b_hex(text))
  return bytes.decode(plain_text).rstrip('\0')

if __name__ == '__main__':
  a = encrypt('hello')
  b = decrypt(a)
  print('加密', a)
  print('解密', b)
DDR爱好者之家 Design By 杰米
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
DDR爱好者之家 Design By 杰米