python RSA簽名和解籤

youbo_sun發表於2015-07-18
# -*- coding:utf-8 -*-

import base64

from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5 as pk


class Crypt(object):

    public_key = RSA.importKey(open('rsa_public_key.pem', 'r').read())
    pkcs8_private_key = RSA.importKey(open('pkcs8_rsa_private_key.pem', 'r').read())
   
    @classmethod
    def rsa_sign(cls, des_reqdata):
        """
            @:param reqdata: request reqData
        """
        h = SHA.new(des_reqdata)
        signer = pk.new(cls.pkcs8_private_key)
        signature = signer.sign(h)

        return base64.b64encode(signature)

    @classmethod
    def check_rsa_sign(cls, des_retdata, sign):
        """ check sign use this method
            @:param retdata:  response retData
            @:param sign:  response sign
        """
        # retdata = base64.b64decode(des_retdata)
        sign = base64.b64decode(sign)
        h = SHA.new(des_retdata) 
        verifier = pk.new(cls.public_key)

        return verifier.verify(h, sign)

相關文章