python AES加密解密(基于base64)

本文详细介绍了使用Python实现AES加密和解密的具体方法,包括如何将数据填充到16位长度,利用AES.MODE_ECB模式进行加密,并通过Base64编码进行数据传输,最后解析并还原加密数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

加密

def add_to_16(value):
  while len(value) % 16 != 0:
    value += '\0'
  return str.encode(value)
 
def aesEncrypt(content,Key):
  BS = 16
  pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
  content1 = pad(content)
  text = add_to_16(content1)
  cryptos = AES.new(Key, AES.MODE_ECB)
  cipher_text = cryptos.encrypt(text)
  aes_base64 = base64.encodebytes(cipher_text)
  m = str(aes_base64, encoding="utf-8")
  return m.replace('\n','')

解密:

def aesDecrypt(text):
    unpad = lambda s: s[0:-ord(s[-1])]
    cryptos = AES.new(Key,AES.MODE_ECB)
    base64_decrypted = base64.decodebytes(text.encode(encoding='utf-8'))
    content=cryptos.decrypt(base64_decrypted).decode('utf-8')
    decrypted_text = unpad(content)
    decrypted_code = decrypted_text.rstrip('\0')
    return decrypted_code

文章参考:http://www.manongjc.com/article/87217.html

AES(Advanced Encryption Standard)是高级加密标准的缩写,它是对称加密算法中的一种。Python中有多个库能够实现AES加密和解密操作,其中`pycryptodome`是一个常用的选择。 ### 安装 pycryptodome 如果你还没有安装这个库的话,请先用pip安装: ```bash pip install pycryptodome ``` ### Python AES 加密解密示例代码 以下是一段简单的例子展示如何在Python中使用AES来进行字符串的加密与解密: #### 导入必要的模块 首先导入所需的类和方法: ```python from Crypto.Cipher import AES import base64 # 用于处理填充 from Crypto.Util.Padding import pad, unpad ``` #### 设置加解密使用的函数 接下来定义两个辅助函数用来执行实际的加密和解密逻辑: ```python def encrypt(plain_text, key): # 创建一个基于给定key的新AES Cipher实例 cipher = AES.new(key.encode('utf8'), AES.MODE_CBC) # 对明文进行PKCS7填充并编码为bytes类型后再加密 padded_plaintext = plain_text.encode('utf-8') ct_bytes = cipher.encrypt(pad(padded_plaintext, AES.block_size)) # 将IV(初始化向量)附加上去以便后续正确解码;这里我们简单地把它base64转成string连在一起返回。 iv_base64 = base64.b64encode(cipher.iv).decode('utf-8') ct_base64 = base64.b64encode(ct_bytes).decode('utf-8') return f"{iv_base64}:{ct_base64}" def decrypt(encryption_str, key): try: # 解析出IV部分以及真实的cipher text部分. iv_base64, ct_base64 = encryption_str.split(':') # 分别将两部分内容从base64恢复回来得到原本的数据形式。 iv = base64.b64decode(iv_base64) ct = base64.b64decode(ct_base64) # 使用相同的key创建一个新的AES Cipher对象,并传入之前保存下来的IV作为参数之一重新构造Cipher instance。 cipher = AES.new(key.encode('utf8'), AES.MODE_CBC, iv=iv) decrypted_data = unpad(cipher.decrypt(ct), AES.block_size) return decrypted_data.decode('utf-8') except Exception as e: print(f"Error occurred during decryption - {str(e)}") raise ValueError("Failed to Decrypt Data") ``` 请注意,在上面的例子中,我们需要确保提供的`key`长度符合AES的要求——即必须为16字节、24字节或32字节长(对应于AES-128, AES-192 和 AES-256)。如果您的键不符合这些尺寸,则需要对其进行适当的截断或者扩展以满足需求。 #### 测试功能 现在我们可以尝试一下这两个新构建的方法了! ```python if __name__ == "__main__": secret_key = "thisisaverysecret" message_to_encrypt = "Hello World!" encrypted_message = encrypt(message_to_encrypt, secret_key) print("Encrypted:", encrypted_message) decrypted_message = decrypt(encrypted_message, secret_key) print("Decrypted:", decrypted_message) ``` 以上就是关于Python中的AES加密/解密的基本介绍啦~希望这对您有所帮助!如果您还有其他疑问或其他方面的需求,请随时告诉我哦。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值