zoukankan      html  css  js  c++  java
  • python 实现 AES ECB模式加解密

    AES ECB模式加解密
    使用cryptopp完成AES的ECB模式进行加解密。

    AES加密数据块分组长度必须为128比特,密钥长度可以是128比特、192比特、256比特中的任意一个。(8比特 == 1字节)

    在CBC、CFB、OFB、CTR模式下除了密钥外,还需要一个初始化向IV。(ECB模式不用IV)

    代码:

      

    # -*- coding=utf-8-*-
    from Crypto.Cipher import AES
    import os
    from Crypto import Random
    import base64
    
    """
    aes加密算法
    padding : PKCS7
    """
    
    class AESUtil:
    
        __BLOCK_SIZE_16 = BLOCK_SIZE_16 = AES.block_size
    
        @staticmethod
        def encryt(str, key, iv):
            cipher = AES.new(key, AES.MODE_ECB,iv)
            x = AESUtil.__BLOCK_SIZE_16 - (len(str) % AESUtil.__BLOCK_SIZE_16)
            if x != 0:
                str = str + chr(x)*x
            msg = cipher.encrypt(str)
            # msg = base64.urlsafe_b64encode(msg).replace('=', '')
            msg = base64.b64encode(msg)
            return msg
    
        @staticmethod
        def decrypt(enStr, key, iv):
            cipher = AES.new(key, AES.MODE_ECB, iv)
            # enStr += (len(enStr) % 4)*"="
            # decryptByts = base64.urlsafe_b64decode(enStr)
            decryptByts = base64.b64decode(enStr)
            msg = cipher.decrypt(decryptByts)
            paddingLen = ord(msg[len(msg)-1])
            return msg[0:-paddingLen]
    
    if __name__ == "__main__":
        key = "1234567812345678"
        iv = "1234567812345678"
        res = AESUtil.encryt("123456", key, iv)
        print res # mdSm0RmB+xAKrTah3DG31A==
        print AESUtil.decrypt(res, key, iv) # 123456
  • 相关阅读:
    bzoj4423 [AMPPZ2013]Bytehattan
    bzoj3643 Phi的反函数
    hdu1024 Max Sum Plus Plus的另一种解法
    hdu1024 Max Sum Plus Plus
    bzoj3638 Cf172 k-Maximum Subsequence Sum
    bzoj3620 似乎在梦中见过的样子
    bzoj3667 Rabin-Miller算法
    bzoj3680 吊打XXX
    阿里Linux Shell脚本面试25个经典问答
    编程面试的10大算法概念汇总
  • 原文地址:https://www.cnblogs.com/xuchunlin/p/11421788.html
Copyright © 2011-2022 走看看