首页 > 技术文章 > PYTHON加密解密字符串

shld 2018-11-27 17:24 原文

依赖包安装部分

  • 安装依赖包: pip install pycryptodome
  • 在你的python环境中的下图红框路径中找到 crypto 将其改成 Crypto

 

代码部分

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2018-11-27 17:21:23
# @Author  : Sheldon (thisisscret@qq.com)
# @blogs   : 谢耳朵的派森笔记
# @Link    : https://www.cnblogs.com/shld/
from Crypto.Cipher import AES
from binascii import b2a_base64, a2b_base64

def rpad(text, divisor: int, suffix):
    remain = len(text) % divisor
    if remain > 0:
        text += suffix * (divisor - remain)
    return text

def encrypt(text, salt, key):
    fmtkey, fmtiv = map(lambda s: s.encode()[:16].ljust(16, b'\0'), (key, salt))
    cryptor = AES.new(fmtkey, AES.MODE_CBC, fmtiv)
    fmttext = rpad(text.encode(), 16, b'\0')
    ciphertext = cryptor.encrypt(fmttext)
    return str(b2a_base64(ciphertext))[2:-3].rstrip('=')

def decrypt(text, salt, key):
    fmtkey, fmtiv = map(lambda s: s.encode()[:16].ljust(16, b'\0'), (key, salt))
    cryptor = AES.new(fmtkey, AES.MODE_CBC, fmtiv)
    fmttext = rpad(text, 4, '=')
    return cryptor.decrypt(a2b_base64(fmttext)).rstrip(b'\0').decode()

if __name__ == "__main__":
    # key,salt应为16字节(汉字3字节,字母1字节),不足的自动补空格,超过的取前16字节
    ciphertext = encrypt("我们的祖国是花园~", "hello", "world")
    plaintext = decrypt(ciphertext, "hello", "world")

 

推荐阅读