for a bank transaction implementation, I have a private key and some data and I need to sign that data with the private key.
The example code the bank has given is in C# .NET and I can't find any equivalent to it in python.
The key is in the following format :
<RSAKeyValue>
<Modulus>...</Modulus>
<Exponent>...</Exponent>
<P>...</P>
<Q>...</Q>
<DP>...</DP>
<DQ>...</DQ>
<InverseQ>...</InverseQ>
<D>...</D>
</RSAKeyValue>
And the example code is this :
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(“ <RSAKeyValue><Modulus>oQRshGhLf2Fh... ”);
string data = "#" + merchantCode + "#" + terminalCode + "#"
+invoiceNumber + "#" + invoiceDate + "#" + amount + "#" +redirectAddress
+ "#" + action + "#" + timeStamp + "#";
byte[] signMain = rsa.SignData(Encoding.UTF8.GetBytes(data), new
SHA1CryptoServiceProvider());
sign = Convert.ToBase64String(signMain);
Now I have not found any good equivalent for this in python and I need to do the exact thing in order to not raise any exceptions. I once asked this question in another literature and it got put on hold. I don't know why they did that but I have been struggling this for weeks and I have not yet found any solutions. so please help me in any way you can. thanks in advance.
Notice that example code use SHA1 ,not SHA256.
Also you can use an online RSA Key Converter tool to convert RSA xml format to .pem format if you want to do it once.
You can use this method:
import json
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA1
import base64 import
def get_sign(data, private_key):
rsa_key = RSA.importKey(base64.b64decode(private_key.encode("utf-8")))
signer = PKCS1_v1_5.new(rsa_key)
digest = SHA1.new()
digest.update(data)
sign = signer.sign(digest)
return base64.b64encode(sign).decode('utf-8')
# usage example
pem_private_key= """
izfrNTmQLnfsLzi2Wb9xPz2Qj9fQYGgeug3N2MkDuVHwpPcgkhHkJgCQuuvT+qZI
...
eM1tfdFZ6wMTLkxRhBkBK4JiMiUMvpERyPib6a2L6iXTfH+3RUDS6A==
"""
payload_json = json.dumps({"is_example":True})
sign = get_sign(pem_private_key, payload_json.encode('utf-8'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With