zoukankan      html  css  js  c++  java
  • PYTHON加密解密字符串

    依赖包安装部分

    • 安装依赖包: 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''), (key, salt))
        cryptor = AES.new(fmtkey, AES.MODE_CBC, fmtiv)
        fmttext = rpad(text.encode(), 16, b'')
        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''), (key, salt))
        cryptor = AES.new(fmtkey, AES.MODE_CBC, fmtiv)
        fmttext = rpad(text, 4, '=')
        return cryptor.decrypt(a2b_base64(fmttext)).rstrip(b'').decode()
    
    if __name__ == "__main__":
        # key,salt应为16字节(汉字3字节,字母1字节),不足的自动补空格,超过的取前16字节
        ciphertext = encrypt("我们的祖国是花园~", "hello", "world")
        plaintext = decrypt(ciphertext, "hello", "world")
  • 相关阅读:
    LG gram 双系统全指南
    离散数学读书记录
    研究小报告:掺杂硅脂对处理器散热能力的影响
    SICP 课程总结 & 复习
    maxHeap 的 python 实现
    KDD Cup 2018 冠军团队 思路分享
    mergeSort, quickSort, shellSort 的 python 实现
    数据集-搜集
    【NOIP2018模拟赛】
    【NOIP2018 模拟】
  • 原文地址:https://www.cnblogs.com/shld/p/10027710.html
Copyright © 2011-2022 走看看