python AES对称加密示例

发布时间:2019-09-01 10:38:23编辑:auto阅读(1636)



    基本概念:

    高级加密标准(英语:Advanced Encryption Standard,缩写:AES)


    注意点:

    1.字符集处理

    2.秘钥的生成,建议按照某种规则产生,比如对用户id进行一定规则加工后,进行md5计算,再从中取出16个字节,这样每条数据的加密秘钥不一样,防止被碰撞

    3.秘钥的长度,key可以是16/24/32 位长度, 其对应为 AES-128,AES-196 和 AES-256

    4.测试源码的加密方式仅限于在服务器加解密,比如存到数据库前进行加密,防脱裤


    测试源码:

    #!/usr/bin/env python
    #coding=utf8
    
    from Crypto.Cipher import AES
    from Crypto import Random
    
    # AES根据16位对齐
    BS = 16
    
    # 转成utf8编码
    def unicode_to_utf8(s):
        if isinstance(s, unicode):
            s = s.encode("utf-8")
        return s
    
    
    # 补充字符,最少1个
    def pad(s):
        length = len(s)
        add = BS - length % BS
        byte = chr(BS - length % BS)
        return s + (add * byte)
    
    
    # 去除补充字符
    def unpad(s):
        length = len(s)
        byte = s[length-1:]
        add = ord(byte)
        return s[:-add]
    
    
    # class
    class AESCipher:
        #初始化
        def __init__(self, key):
            self.key = key
    
        #加密
        def encrypt(self, raw):
            raw = unicode_to_utf8(raw)
            raw = pad(raw)
            cipher = AES.new(self.key, AES.MODE_CBC, self.key)
            return cipher.encrypt(raw)
    
        #解密
        def decrypt(self, enc):
            cipher = AES.new(self.key, AES.MODE_CBC, self.key)
            return unpad(cipher.decrypt(enc))
    
    
    if __name__ == '__main__':
        
        #注意key是16字节长
        key = "f2c85e0140a47415"
        
        #初始化
        aes = AESCipher(key)
    
        s1 = "hello world"
        s2 = "带鱼拯救世界"
        s3 = "~!@#$%^&"
        s4 = u"~!@#¥%……&带鱼拯救world"
    
        en1 = aes.encrypt(s1)
        de1 = aes.decrypt(en1)
    
        en2 = aes.encrypt(s2)
        de2 = aes.decrypt(en2)
    
        en3 = aes.encrypt(s3)
        de3 = aes.decrypt(en3)
    
        en4 = aes.encrypt(s4)
        de4 = aes.decrypt(en4)
    
        print 's1:', de1
        print 's2:', de2
        print 's3:', de3
        print 's4:', de4
    
    


    原文出自:http://blog.csdn.net/daiyudong2020/article/details/62088583


    End;

关键字