当前位置: 移动技术网 > IT编程>脚本编程>Python > python实现AES加密与解密

python实现AES加密与解密

2019年06月03日  | 移动技术网IT编程  | 我要评论

郑州皇家一号被查,连体钞票,地下影带

aes加密方式有五种:ecb, cbc, ctr, cfb, ofb

从安全性角度推荐cbc加密方法,本文介绍了cbc,ecb两种加密方法的python实现

python 在 windows下使用aes时要安装的是pycryptodome 模块  

pip install pycryptodome

python 在 linux下使用aes时要安装的是pycrypto模块  

pip install pycrypto

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

ecb加密不需要iv

aes cbc 加密的python实现

from crypto.cipher import aes
from binascii import b2a_hex, a2b_hex


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


# 加密函数
def encrypt(text):
 key = '9999999999999999'.encode('utf-8')
 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)


# 解密后,去掉补足的空格用strip() 去掉
def decrypt(text):
 key = '9999999999999999'.encode('utf-8')
 iv = b'qqqqqqqqqqqqqqqq'
 mode = aes.mode_cbc
 cryptos = aes.new(key, mode, iv)
 plain_text = cryptos.decrypt(a2b_hex(text))
 return bytes.decode(plain_text).rstrip('\0')


if __name__ == '__main__':
 e = encrypt("hello world") # 加密
 d = decrypt(e) # 解密
 print("加密:", e)
 print("解密:", d)

aes ecb加密的python实现

"""
ecb没有偏移量
"""
from crypto.cipher import aes
from binascii import b2a_hex, a2b_hex


def add_to_16(text):
 if len(text.encode('utf-8')) % 16:
 add = 16 - (len(text.encode('utf-8')) % 16)
 else:
 add = 0
 text = text + ('\0' * add)
 return text.encode('utf-8')


# 加密函数
def encrypt(text):
 key = '9999999999999999'.encode('utf-8')
 mode = aes.mode_ecb
 text = add_to_16(text)
 cryptos = aes.new(key, mode)

 cipher_text = cryptos.encrypt(text)
 return b2a_hex(cipher_text)


# 解密后,去掉补足的空格用strip() 去掉
def decrypt(text):
 key = '9999999999999999'.encode('utf-8')
 mode = aes.mode_ecb
 cryptor = aes.new(key, mode)
 plain_text = cryptor.decrypt(a2b_hex(text))
 return bytes.decode(plain_text).rstrip('\0')


if __name__ == '__main__':
 e = encrypt("hello world") # 加密
 d = decrypt(e) # 解密
 print("加密:", e)
 print("解密:", d)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网