• Python RSA操作


    公钥加密、私钥解密

    # -*- coding: utf-8 -*-
    import rsa
    
    # rsa加密
    def rsaEncrypt(str):
        # 生成公钥、私钥
        (pubkey, privkey) = rsa.newkeys(512)
        print("pub: ", pubkey)
        print("priv: ", privkey)
        # 明文编码格式
        content = str.encode('utf-8')
        # 公钥加密
        crypto = rsa.encrypt(content, pubkey)
        return (crypto, privkey)
    
    
    # rsa解密
    def rsaDecrypt(str, pk):
        # 私钥解密
        content = rsa.decrypt(str, pk)
        con = content.decode('utf-8')
        return con
    
    
    (a, b) = rsaEncrypt("hello")
    print('加密后密文:')
    print(a)
    content = rsaDecrypt(a, b)
    print('解密后明文:')
    print(content)  
    

    密钥导出、签名验证

    # -*- coding: utf-8 -*-
    import rsa
    
    # 先生成一对密钥,然后保存.pem格式文件,当然也可以直接使用
    (pubkey, privkey) = rsa.newkeys(1024)
    
    pub = pubkey.save_pkcs1()
    pubfile = open('public.pem', 'wb')
    pubfile.write(pub)
    pubfile.close()
    
    pri = privkey.save_pkcs1()
    prifile = open('private.pem', 'wb')
    prifile.write(pri)
    prifile.close()
    
    # load公钥和密钥
    message = 'lovesoo.org'
    with open('public.pem', "rb") as publickfile:
        p = publickfile.read()
        pubkey = rsa.PublicKey.load_pkcs1(p)
        print(pubkey)
    with open('private.pem', "rb") as privatefile:
        p = privatefile.read()
        privkey = rsa.PrivateKey.load_pkcs1(p)
        print(privkey)
    # 用公钥加密、再用私钥解密
    crypto = rsa.encrypt(message.encode('utf-8'), pubkey)
    message = rsa.decrypt(crypto, privkey)
    message = message.decode('utf-8')
    print (message)
    
    # sign 用私钥签名认证、再用公钥验证签名
    signature = rsa.sign(message.encode('utf-8'), privkey, 'SHA-1')
    method_name = rsa.verify('lovesoo.org'.encode('utf-8'), signature, pubkey)
    print(method_name)
    

    对文件进行RSA加密解密

    from rsa.bigfile import *
    import rsa
    
    with open('public.pem') as publickfile:
        p = publickfile.read()
        pubkey = rsa.PublicKey.load_pkcs1(p)
    
    with open('private.pem') as privatefile:
        p = privatefile.read()
        privkey = rsa.PrivateKey.load_pkcs1(p)
    with open('mysec.txt', 'rb') as infile, open('outputfile', 'wb') as outfile: #加密输出
        encrypt_bigfile(infile, outfile, pubkey)
    
    with open('outputfile', 'rb') as infile2, open('result', 'wb') as outfile2:  #解密输出
        decrypt_bigfile(infile2, outfile2, privkey)
    

    4.0的主要变化
    版本3.4是3.x范围内的最后一个版本。版本4.0删除了以下模块,因为它们不安全:

    rsa._version133
    rsa._version200
    rsa.bigfile
    rsa.varblock
    这些模块在3.4版中被标记为已弃用。

    此外,在4.0中,I / O函数经过简化,可以在所有支持的Python版本上使用字节。

    4.0版本不再支持Python 2.6和3.3。

  • 相关阅读:
    JZOJ5906 传送门
    JZOJ5907 轻功
    JZOJ5904 刺客信条
    JZOJ5347 遥远的金字塔
    JZOJ5344 摘果子
    JZOJ4742 单峰
    JZOJ4725 质数序列
    JZOJ2499 东风谷早苗
    JZOJ4737 金色丝线将瞬间一分为二
    最后的财产——模板大全
  • 原文地址:https://www.cnblogs.com/gmhappy/p/11863976.html
Copyright © 2020-2023  润新知