Python之RSA加密、解密、签名、验签代码分享

Python之RSA加密、解密、签名、验签代码分享

import os
import sys
import datetime
from collections import OrderedDict

import configparser
import argparse

import hashlib

from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto.PublicKey.RSA import RsaKey
from Crypto.Signature import pkcs1_15
from Crypto.Cipher import PKCS1_v1_5

import base64
import binascii

from X_conversion import *
from X_hash import *



def main(argv):

    xh = X_hash()
    xh.test()

    xr = X_rsa()
    xr.test()

    input()

def rsa_key_gen():
    # 生成RSA密钥对
    rsa_key = RSA.generate(2048)
    return rsa_key
        
def rsa_private_key_gen(rsa_key:RsaKey):
    # 生成RSA密钥对
    rsa_private_key = rsa_key
    return rsa_private_key

def rsa_public_key_gen(rsa_key:RsaKey):
    # 生成RSA密钥对
    rsa_public_key = rsa_key.publickey()
    return rsa_public_key

def rsa_encrypt(data_str:str, public_key_str:str):
    # 用公钥进行加密
    data_bytes = str2bytes(data_str)
    public_key_bytes = str2bytes(public_key_str)

    public_key = RSA.import_key(public_key_bytes)

    cipher_rsa = PKCS1_v1_5.new(public_key)
    cipher_data_bytes = cipher_rsa.encrypt(data_bytes)

    return cipher_data_bytes

def rsa_decrypt(cipher_data_hex_str:str, private_key_str:str):
    # 用私钥进行解密
    private_key_bytes = str2bytes(private_key_str)
    cipher_data_hex_bytes = hexstr2bytes(cipher_data_hex_str)

    private_key = RSA.import_key(private_key_bytes)
    cipher_rsa = PKCS1_v1_5.new(private_key)
    plain_data = cipher_rsa.decrypt(cipher_data_hex_bytes, None)
    plain_data_str = plain_data.decode()

    return plain_data_str


def rsa_sign(data_str:str, private_key_str:str):
    # 要签名的明文数据
    private_key_bytes = str2bytes(private_key_str)
    data_bytes = str2bytes(data_str)

    # 用私钥进行签名
    hash_obj = SHA256.new(data_bytes)
    private_key = RSA.import_key(private_key_bytes)
    signer_rsa = pkcs1_15.new(private_key)
    signature_bytes = signer_rsa.sign(hash_obj)

    return signature_bytes


def rsa_verif(data_str:str, public_key_str:str, signature_hex_str:str):
    # 要签名的明文数据
    public_key_bytes = str2bytes(public_key_str)
    signature = hexstr2bytes(signature_hex_str)
    data_bytes = str2bytes(data_str)

    # 用公钥进行验证
    hash_obj = SHA256.new(data_bytes)
    public_key = RSA.import_key(public_key_bytes)
    verifier_rsa = pkcs1_15.new(public_key)

    try:
        verifier_rsa.verify(hash_obj, signature)
        return True
    except:
        return False

class X_rsa(object):
    def __init__(self):
        self.version = 'V1.0.0'
        self.current_path = os.path.dirname(sys.argv[0])
        self._out_dir = os.path.join(self.current_path, '_out')
        # 使用makedirs创建新文件夹,如果文件夹已存在,则不会抛出异常 
        os.makedirs(self._out_dir, exist_ok=True)

    def rsa_key_gen(self):
        # 生成RSA密钥对
        rsa_key = RSA.generate(2048)
        return rsa_key
            
    def rsa_private_key_gen(self, rsa_key:RsaKey):
        # 生成RSA密钥对
        rsa_private_key = rsa_key
        return rsa_private_key

    def rsa_public_key_gen(self, rsa_key:RsaKey):
        # 生成RSA密钥对
        rsa_public_key = rsa_key.publickey()
        return rsa_public_key

    def rsa_encrypt(self, data_str:str, public_key_str:str):
        # 用公钥进行加密
        data_bytes = str2bytes(data_str)
        public_key_bytes = str2bytes(public_key_str)

        public_key = RSA.import_key(public_key_bytes)

        cipher_rsa = PKCS1_v1_5.new(public_key)
        cipher_data_bytes = cipher_rsa.encrypt(data_bytes)

        return cipher_data_bytes

    def rsa_decrypt(self, cipher_data_hex_str:str, private_key_str:str):
        # 用私钥进行解密
        private_key_bytes = str2bytes(private_key_str)
        cipher_data_hex_bytes = hexstr2bytes(cipher_data_hex_str)

        private_key = RSA.import_key(private_key_bytes)
        cipher_rsa = PKCS1_v1_5.new(private_key)
        plain_data = cipher_rsa.decrypt(cipher_data_hex_bytes, None)
        plain_data_str = plain_data.decode()

        return plain_data_str


    def rsa_sign(self, data_str:str, private_key_str:str):
        # 要签名的明文数据
        private_key_bytes = str2bytes(private_key_str)
        data_bytes = str2bytes(data_str)

        # 用私钥进行签名
        hash_obj = SHA256.new(data_bytes)
        private_key = RSA.import_key(private_key_bytes)
        signer_rsa = pkcs1_15.new(private_key)
        signature_bytes = signer_rsa.sign(hash_obj)

        return signature_bytes


    def rsa_verif(self, data_str:str, public_key_str:str, signature_hex_str:str):
        # 要签名的明文数据
        public_key_bytes = str2bytes(public_key_str)
        signature = hexstr2bytes(signature_hex_str)
        data_bytes = str2bytes(data_str)

        # 用公钥进行验证
        hash_obj = SHA256.new(data_bytes)
        public_key = RSA.import_key(public_key_bytes)
        verifier_rsa = pkcs1_15.new(public_key)

        try:
            verifier_rsa.verify(hash_obj, signature)
            return True
        except:
            return False

    def test(self):
        print('X_rsa test start ********************************************************')
        message = "Hello World!"
        # 生成RSA密钥对
        rsa_key = self.rsa_key_gen()
        
        # 从RSA密钥对中获取公钥和私钥
        private_key = self.rsa_private_key_gen(rsa_key)
        public_key = self.rsa_public_key_gen(private_key)

        public_key_bytes = private_key.publickey().export_key()
        private_key_bytes = private_key.export_key()
        public_key_str = bytes2str(public_key_bytes)
        private_key_str = bytes2str(private_key_bytes)


        print('private_key: ', type(private_key),'@', private_key)
        print('public_key: ', type(public_key),'@', public_key)
        print('\n')
        print("public_key_str:", type(public_key_str),'@\n', public_key_str)
        print('\n')
        print("private_key_str:", type(private_key_str),'@\n', private_key_str)
        print('\n')

        # 用公钥进行加密
        cipher_data_bytes = self.rsa_encrypt(message, public_key_str)
        
        cipher_data_hex_str = bytes2hexstr(cipher_data_bytes)
        print("加密前的数据(str):", type(message),'@', message)
        # print("加密后的数据:", type(cipher_data_bytes),'@', cipher_data_bytes)
        print("加密后的数据(hex_str):", type(cipher_data_hex_str),'@', cipher_data_hex_str)
        print('\n')


        # 用私钥进行解密
        plain_data_str = self.rsa_decrypt(cipher_data_hex_str, private_key_str)
        print("解密前的数据(hex_str):", type(cipher_data_hex_str),'@', cipher_data_hex_str)
        print("解密后的数据(str):", type(plain_data_str),'@', plain_data_str)
        print('\n')



        # 从文件中读出私钥字符串
        with open(os.path.join(self.current_path, 'private.pem'), 'r') as f:
            private_key_str = f.read()

        # 从文件中读出私钥字符串
        with open(os.path.join(self.current_path, 'public.pem'), 'r') as f:
            public_key_str = f.read()

        # 用私钥进行签名
        signature_bytes = self.rsa_sign(message, private_key_str)

        # 将签名字节串写入文件
        with open(os.path.join(self._out_dir, 'signature.bin'), 'wb') as f:
            f.write(signature_bytes)

        # 从文件中读出签名字节串
        with open(os.path.join(self._out_dir, 'signature.bin'), 'rb') as f:
            signature_bytes = f.read()

        signature_hex_str = bytes2hexstr(signature_bytes)
        signature_hex_str_len = len(signature_hex_str)
        print('signature_bytes: ', type(signature_bytes),'@', signature_bytes)
        print('signature_hex_str: ', type(signature_hex_str),'@', signature_hex_str)
        print('signature_hex_str_len: ', type(signature_hex_str_len),'@', signature_hex_str_len)
        print('\n')

        # 用公钥进行验证
        if self.rsa_verif(message, public_key_str, signature_hex_str):
            print("public_key is correct!")
        else:
            print("public_key error!")

        print('X_rsa test end ********************************************************\n\n')



if __name__ == "__main__":
    main(sys.argv[1:])

《AUTOSAR谱系分解(ETAS工具链)》之总目录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值