RSA签名 python PHP demo 例子
python RSA+MD5签名demo:
1 #!/usr/bin/env python2.7 2 #coding:utf-8 3 4 import base64 5 from Crypto.PublicKey import RSA 6 from Crypto.Signature import PKCS1_v1_5 7 from Crypto.Hash import SHA,MD5 8 9 TEST_PRIKEY='''-----BEGIN RSA PRIVATE KEY----- 10 MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAmXug8cAahQfFpHYGe3K9gHsBvhnD 11 VlfR+SkfVQ8pLFEeQGWu7C0xKLNgzkBKP8A9y9j+Zoyv1irPRJvasgR3uwIDAQABAkAN6AezH8bH 12 Wubrec4ojULiS0LjKI5sWlSqELHIETGX1DXPrkx61AojZGFdO+4rINkXgix5sQAkeExlWml8EMph 13 AiEAx4gOPVfATGBm7AWS74geXFaA0ONegSJy1i5oUJnHm/MCIQDE62Gyi1lzmCnC63S7EgmvbtK0 14 BzZhgs95k3NPLtEPGQIhAJQJ7ga1RIdmPvZ+bDYr19rKk2hoSYWl+W3PoLWsYtzhAiAWwGtlSZxo 15 MqiAkNvH0Wm1D0Tg8ARkd8yo61RjTbFx4QIgAzEzc/MYJubgOqjGB91Bo/GIWyx1NEmBstdA3G5W 16 f08= 17 -----END RSA PRIVATE KEY-----''' 18 19 TEST_PUBKEY='''-----BEGIN PUBLIC KEY----- 20 MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJl7oPHAGoUHxaR2BntyvYB7Ab4Zw1ZX0fkpH1UPKSxR 21 HkBlruwtMSizYM5ASj/APcvY/maMr9Yqz0Sb2rIEd7sCAwEAAQ== 22 -----END PUBLIC KEY-----''' 23 24 def sign(data,priKey=None): 25 if priKey==None: 26 priKey=TEST_PRIKEY 27 key = RSA.importKey(priKey) 28 h = MD5.new(data) 29 # print h 30 signer = PKCS1_v1_5.new(key) 31 signature = signer.sign(h) 32 # print signature 33 return_ret= base64.b64encode(signature) 34 # print return_ret 35 return return_ret 36 37 38 def verify(data, signature, DEBUG=False): 39 if DEBUG: 40 pubKey=TEST_PUBKEY 41 else: 42 pubKey='' 43 if not data: 44 return False 45 if not signature: 46 return False 47 key = RSA.importKey(pubKey) 48 h = MD5.new(data) 49 verifier = PKCS1_v1_5.new(key) 50 if verifier.verify(h, base64.b64decode(signature)): 51 return True 52 return False 53 54 55 if __name__ == '__main__': 56 test_byte = 'test_abc' 57 print test_byte 58 sign_data = sign(test_byte) 59 print sign_data 60 print verify(test_byte, sign_data, DEBUG=True)
PHP RSA+MD5签名demo:
1 <?php 2 ini_set('error_reporting', -1); 3 ini_set('display_errors', -1); 4 5 header('Content-Type: text/html; charset=utf-8'); 6 7 8 # openssl genrsa -out rsa_private_key.pem 1024 9 # openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem 10 11 12 $private_key = file_get_contents("rsa_private_key.pem"); 13 $public_key = file_get_contents("rsa_public_key.pem"); 14 15 $data = 'test_abc'; 16 17 $res = openssl_get_privatekey($private_key); 18 openssl_sign($data, $sign, $res, OPENSSL_ALGO_MD5); 19 openssl_free_key($res); 20 $encrypt = base64_encode($sign); 21 echo $encrypt,"\n";
PS:PHP 加密方法openssl_sign API:http://php.net/manual/zh/function.openssl-sign.php
Signature Algorithms 参数可以直接指定 OPENSSL_ALGO_MD5