用Python实现MD5&RSA签名和验签

用pem文件

pub_key.pem

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQChNn3wKRtPmxaKq2dKsfMn6sO6AKxvtxZgNdh7
HBWq2z0AJusZHFx2tO2X3jpaYWSIwDrH6AdU2LMMc7IRaUgvLRgT6kPK5OLEzvS+Bmh+1kh7Fz4z
k96UX7UDt55vyK18dJxad+tYwzcN4/Vjudy9RQy6nVX+tRtqRMVNKE254wIDAQAB
-----END PUBLIC KEY-----

priv_key.pem

-----BEGIN PRIVATE KEY-----

-----END PRIVATE KEY-----

签名&验签

from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import MD5
import base64


def rsa_sign(data):
    private_key_file = open('priv_key.pem', 'r')
    pri_key = RSA.importKey(private_key_file.read())
    signer = PKCS1_v1_5.new(pri_key)
    hash_obj = my_hash(data)
    signature = base64.b64encode(signer.sign(hash_obj))
    private_key_file.close()
    return signature


def rsa_verify(signature, data):
    public_key_file = open('pub_key.pem', 'r')
    pub_key = RSA.importKey(public_key_file.read())
    hash_obj = my_hash(data)
    verifier = PKCS1_v1_5.new(pub_key)
    public_key_file.close()
    return verifier.verify(hash_obj, base64.b64decode(signature))


def my_hash(data):
    return MD5.new(data.encode('utf-8'))

用json文件

注意:经过测试,无论换行符是\n, \r\n还是\r,加密的结果都一致
key.json

{
  "RSAPublicKey": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQChNn3wKRtPmxaKq2dKsfMn6sO6AKxvtxZgNdh7\r\nHBWq2z0AJusZHFx2tO2X3jpaYWSIwDrH6AdU2LMMc7IRaUgvLRgT6kPK5OLEzvS+Bmh+1kh7Fz4z\r\nk96UX7UDt55vyK18dJxad+tYwzcN4/Vjudy9RQy6nVX+tRtqRMVNKE254wIDAQAB\r\n",
  "RSAPrivateKey": 
}

签名

def test_json_file(data):
    key_file = open('key.json', 'r')
    key_dict = json.load(key_file)

    pri_key = RSA.importKey(base64.b64decode(key_dict["RSAPrivateKey"]))
    signer = PKCS1_v1_5.new(pri_key)
    hash_obj = my_hash(data)
    signature = base64.b64encode(signer.sign(hash_obj))
    key_file.close()
    return signature

更多

密钥生成

你可能感兴趣的:(python,密码学,2018)