• 解密解密RSA、AES


    RSA(加密的内容有长度限制)

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    import rsa
    import base64
    
    # ######### 1. 生成公钥私钥 #########
    pub_key_obj, priv_key_obj = rsa.newkeys(256)
    pub_key_str = pub_key_obj.save_pkcs1()
    pub_key_code = base64.standard_b64encode(pub_key_str)
    priv_key_str = priv_key_obj.save_pkcs1()
    priv_key_code = base64.standard_b64encode(priv_key_str)
    print(pub_key_code)
    print(priv_key_code)
    
    # ######### 2. 加密 #########
    def encrypt(value):
        key_str = base64.standard_b64decode(pub_key_code)
        pk = rsa.PublicKey.load_pkcs1(key_str)
        val = rsa.encrypt(value.encode('utf-8'), pk)
        return val
    
    # ######### 3. 解密 #########
    def decrypt(value):
        key_str = base64.standard_b64decode(priv_key_code)
        pk = rsa.PrivateKey.load_pkcs1(key_str)
        val = rsa.decrypt(value, pk)
        return val
    
    # ######### 基本使用 #########
    if __name__ == '__main__':
        v = 'wupeiqi'
        v1 = encrypt(v)
        print(v1)
        v2 = decrypt(v1)
    
        print(v2)

    AES

    from Crypto.Cipher import AES
    # 安装pip3 install pycryptodome
    
    def encrypt(message):
        key = b'dfdsdfsasdfdsdfs'
        cipher = AES.new(key, AES.MODE_CBC, key)
        by_data = bytearray(message, encoding='utf-8')
        # bytearray是bytes列表类型,可以修改,bytes类型不可修改
        v1 = len(bytes(message, encoding='utf-8'))
        v2 = v1 % 16
        if v2 == 0:
            v3 = 16
        else:
            v3 = 16 - v2
        for i in range(v3):
            by_data.append(v3)
            # bytearray只能追加数字进去,这儿追加进数字占一个字节
        final_data = by_data.decode('utf-8')
        final_data = bytes(final_data, encoding='utf-8')
        msg = cipher.encrypt(final_data)
        # 加密 要加密的字符串,必须是16个字节或16个字节的倍数
        return msg
    
    
    def decrypt(msg):
        key = b'dfdsdfsasdfdsdfs'
        cipher = AES.new(key, AES.MODE_CBC, key)
        result = cipher.decrypt(msg)
        # 解密
        data = result[0:-result[-1]]
        return str(data, encoding='utf-8')
    
    v = '我是你爸'   # 这里传进去的值只能是字符串形式的值
    msg = encrypt(v)
    result = decrypt(msg)
    print(result)
  • 相关阅读:
    职业的选择
    事务的隔离性理解
    浅谈CSS和JQuery实现鼠标悬浮图片放大效果
    jvm 类加载器
    jvm 类加载
    Spring 启动 Bean加载流程
    优雅的博客园客户端发布Forms版啦。
    Xamarin Forms中WebView的自适应高度
    2017回顾与2018目标
    优雅的博客园Android客户端
  • 原文地址:https://www.cnblogs.com/domestique/p/7268841.html
Copyright © 2020-2023  润新知