python3 RSA分段加解密,以及SHA1withRSA签名

# -*- coding: utf-8 -*-
import os,base64
from Cryptodome.PublicKey import RSA
from Cryptodome.Hash import SHA1
from Cryptodome.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5  # 加密解密模块
from Cryptodome.Signature import pkcs1_15  # 加签验签模块

basedir = os.path.dirname(os.getcwd())
private_key_file = os.path.join(basedir, "demo", "rsa_private.pem")  # 读取私钥
public_key_file = os.path.join(basedir, "demo", "rsa_public.pem")  # 读取公钥
my_rsa_private = open(private_key_file).read().encode("utf-8")
my_rsa_public = open(public_key_file).read().encode("utf-8")

# 公钥加密,单次加密串的长度最大为(key_size/8 - 11),本次以2048为例#公钥加密
def rsa_long_encrypt(message):  
    msg = message.encode('utf-8')  #待加密信息转成utf-8形式
    length = len(msg)
    default_length = 245
    pubobj = Cipher_pkcs1_v1_5.new(RSA.importKey(my_rsa_public))
    # 长度不用分段
    if length < default_length:
        return base64.b64encode(pubobj.encrypt(msg))
    # 需要分段
    offset = 0
    res = []
    while length - offset > 0:
        if length - offset > default_length:
            res.append(pubobj.encrypt(msg[offset:offset + default_length]))
        else:
            res.append(pubobj.encrypt(msg[offset:]))
        offset += default_length
    byte_data = b''.join(res)
    return base64.b64encode(byte_data) #对返回内容以base64编码

#私钥解密
def rsa_long_decrypt(message):  
    msg = base64.b64decode(message)
    length = len(msg)
    default_length = 256
    #私钥解密
    priobj = Cipher_pkcs1_v1_5.new(RSA.importKey(my_rsa_private))
    #长度不用分段
    if length < default_length:
        return b''.join(priobj.decrypt(msg, b'xyz'))
    #需要分段
    offset = 0
    res = []
    while length - offset > 0:
        if length - offset > default_length:
            res.append(priobj.decrypt(msg[offset:offset+default_length], b'xyz'))
        else:
            res.append(priobj.decrypt(msg[offset:], b'xyz'))
        offset += default_length
        m=b''.join(res)
        n=m.decode("utf-8")
        print(n)
    return n

#私钥加签
def rsa_sign(message):
    msg = message.encode('utf-8')
    private_key = RSA.importKey(my_rsa_private)   
    ## message做“哈希”处理,RSA签名这么要求的
    hash_obj = SHA1.new(msg)
    signature = pkcs1_15.new(private_key).sign(hash_obj)
    return base64.b64encode(signature)


# 公钥验签
def rsa_design(signature, message):
    msg = message.encode("utf-8")
    public_key = RSA.importKey(my_rsa_public)
    # message做“哈希”处理,RSA签名这么要求的
    hash_obj = SHA1.new(msg)
    try:
        pkcs1_15.new(public_key).verify(hash_obj, base64.b64decode(signature))
        print('The signature is valid.')
        return True
    except (ValueError,TypeError):
        print('The signature is invalid.')

参考资料:https://www.cnblogs.com/kuzaman/p/8584200.html

你可能感兴趣的:(python3,RSA)