1. 程式人生 > >用Python實現MD5&RSA簽名和驗籤

用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

更多

金鑰生成