美文网首页
python3中Crypto的AES和RSA

python3中Crypto的AES和RSA

作者: 静默加载 | 来源:发表于2018-08-28 10:08 被阅读606次

    RSA加密一般使用RSA/ECB/PKCS1Padding(算法/工作模式/填充方式),AES加密一般使用AES/ECB/PKCS5Padding。但python中的补码需要自己进行填充。

    生产RSA的公钥和私钥

    # -*- coding: utf-8 -*-
    import rsa
    
    # 先生成一对密钥,然后保存.pem格式文件,当然也可以直接使用
    (pubkey, privkey) = rsa.newkeys(1024)
    
    pub = pubkey.save_pkcs1()
    pubfile = open('public.pem','w+')
    pubfile.write(pub)
    pubfile.close()
    
    pri = privkey.save_pkcs1()
    prifile = open('privateKey.pem','w+')
    prifile.write(pri)
    prifile.close()
    

    RSA加解密

    # rsa加密
    def rsa_encrypt(message):
        with open('pubkey.pem') as f:
            key = f.read()
            rsakey = RSA.importKey(key)
            cipher = Cipher_pkcs1_v1_5.new(rsakey)
            cipher_text = base64.b64encode(cipher.encrypt(message))
            return cipher_text
    
    # rsa解密
    def rsa_decrypt(message):
        with open('privateKey.pem') as f:
            key = f.read()
            rsakey = RSA.importKey(key)
            cipher = Cipher_pkcs1_v1_5.new(rsakey)
            message = message.encode("ascii")
            byte_msg = base64.b64decode(message)
            random_generator = Random.new().read
            return cipher.decrypt(byte_msg, random_generator)
    

    AES加密

    BLOCK_SIZE = 16  # Bytes
    # 填充补码,不足16*N个字节,填充字符为chr(填充个数)
    pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * \
                    chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
    # 去掉填充的补码
    unpad = lambda s: s[:-ord(s[len(s) - 1:])]
    
    
    def aes_encrpty(key, message):
        message = pad(message)
        cipher = AES.new(key, AES.MODE_ECB)
        aessource = cipher.encrypt(message)
        return base64.b64encode(aessource)
    
    
    def aes_decrpty(key, message):
        cipher = AES.new(key, AES.MODE_ECB)
        aessource = cipher.decrypt(base64.b64decode(message))
        return unpad(aessource).decode('utf8')
    

    文章到这里就全部讲述完啦,若有其他需要交流的可以留言哦

    想阅读作者的更多文章,可以查看我 个人博客 和公共号:

    振兴书城

    相关文章

      网友评论

          本文标题:python3中Crypto的AES和RSA

          本文链接:https://www.haomeiwen.com/subject/djatwftx.html