• Python3 RSA加密解密加签验签示例代码


    本代码引入Pycryptodome基于Python3.50版本编译库

     1 #!/usr/bin/env python3
     2 # coding=utf-8
     3 # Author: Luosu201803
     4 """
     5 create_rsa_key() - 创建RSA密钥
     6 my_encrypt_and_decrypt() - 测试加密解密功能
     7 rsa_sign() & rsa_signverify() - 测试签名与验签功能
     8 """
     9 
    10 from binascii import unhexlify
    11 from Crypto.PublicKey import RSA
    12 from Crypto.Cipher import PKCS1_OAEP, PKCS1_v1_5
    13 import base64
    14 from Crypto.Hash import SHA1
    15 from Crypto.Signature import pkcs1_15
    16 
    17 def create_rsa_key(password="123456"):
    18     """
    19     创建RSA密钥,步骤说明:
    20     1、从 Crypto.PublicKey 包中导入 RSA,创建一个密码(此密码不是RSA秘钥对)
    21     2、生成 1024/2048 位的 RSA 密钥对(存储在私钥文件和公钥文件)
    22     3、调用 RSA 密钥实例的 exportKey 方法(传入"密码"、"使用的 PKCS 标准"、"加密方案"这三个参数)得到私钥。
    23     4、将私钥写入磁盘的文件。
    24     5、使用方法链调用 publickey 和 exportKey 方法生成公钥,写入磁盘上的文件。
    25     """
    26     key = RSA.generate(1024)
    27     encrypted_key = key.exportKey(passphrase=password, pkcs=8,protection="scryptAndAES128-CBC")
    28     # encrypted_key = key.exportKey(pkcs=1)
    29     print('encrypted_key:',encrypted_key)
    30     with open("my_private_rsa_key.pem", "wb") as f:
    31         f.write(encrypted_key)
    32     with open("my_rsa_public.pem", "wb") as f:
    33         f.write(key.publickey().exportKey())
    34 
    35 
    36 def encrypt_and_decrypt_test(password="123456"):
    37     # 加载私钥用于加密
    38     recipient_key = RSA.import_key(
    39         open("my_rsa_public.pem").read()
    40     )
    41     cipher_rsa = PKCS1_v1_5.new(recipient_key)
    42     #使用base64编码保存数据方便查看,同样解密需要base64解码
    43     en_data = base64.b64encode(cipher_rsa.encrypt(b"123456,abcdesd"))
    44     print("加密数据信息:",type(en_data),'
    ',len(en_data),'
    ',en_data)
    45 
    46     # 加载公钥用于解密
    47     encoded_key = open("my_private_rsa_key.pem").read()
    48     private_key = RSA.import_key(encoded_key,passphrase=password)
    49     cipher_rsa = PKCS1_v1_5.new(private_key)
    50     data = cipher_rsa.decrypt(base64.b64decode(en_data), None)
    51     print(data)
    52 
    53 def rsa_sign(message,password="123456"):
    54     #读取私钥信息用于加签
    55     private_key = RSA.importKey(open("my_private_rsa_key.pem").read(),passphrase=password)
    56     hash_obj = SHA1.new(message)
    57     # print(pkcs1_15.new(private_key).can_sign())  #check wheather object of pkcs1_15 can be signed
    58     #base64编码打印可视化
    59     signature = base64.b64encode(pkcs1_15.new(private_key).sign(hash_obj))
    60     return signature
    61 
    62 def rsa_signverify(message,signature):
    63     #读取公钥信息用于验签
    64     public_key = RSA.importKey(open("my_rsa_public.pem").read())
    65     #message做“哈希”处理,RSA签名这么要求的
    66     hash_obj = SHA1.new(message)
    67     try:
    68         #因为签名被base64编码,所以这里先解码,再验签
    69         pkcs1_15.new(public_key).verify(hash_obj,base64.b64decode(signature))
    70         print('The signature is valid.')
    71         return True
    72     except (ValueError,TypeError):
    73         print('The signature is invalid.')
    74 
    75 if __name__ == '__main__':
    76     # create_rsa_key()
    77     encrypt_and_decrypt_test()
    78     # message = b'Luosu is a Middle-aged uncle.'
    79     # signature = rsa_sign(message)
    80     # print('signature:',signature)
    81     # print(rsa_signverify(message,signature))
  • 相关阅读:
    <置顶>Eclipse和myeclipse常用快捷键-操作-设置
    Eclipse : Loading descriptor for ...错误解决
    ORA-00937: 不是单组分组函数
    An error has occurred,See error log for more details 错误解决办法
    [Error Code: 942, SQL State: 42000] ORA-00942: 表或视图不存在
    ORA-00001: 违反唯一约束条件
    eclipse 出现user operation is waiting
    [空格][空白][特殊]字符/文字
    powerdesigner16.5安装教程及破解步骤
    mybatis遇到日期类型数据时String到date的转化
  • 原文地址:https://www.cnblogs.com/kuzaman/p/8584200.html
Copyright © 2020-2023  润新知