Sign string with private key using RSA in Python

Issue

I am unable to sign a string using my private key with the following conditions:

  1. Use SHA 256 algorithm to calculate the hash of the string
  2. Use the private key and RSA (PKCS1_PADDING) algorithm to sign the Hash Value
  3. Base64 encode the encrypted Hash Value

The code I am using is below, yet the signature does not match on the server side.

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


pkey = RSA.importKey(keystring)

message = "Hello world"

h = SHA256.new(message.encode())
signature = PKCS1_v1_5.new(pkey).sign(h)
result = base64.b64encode(signature).decode()

Can anyone help me troubleshoot why my signature is not matching?

Answer

The issue could be caused by the encoding of the string before hashing. Try encoding the string using UTF-8 before hashing it. Here’s the updated code:

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

pkey = RSA.importKey(keystring)

message = "Hello world"

h = SHA256.new(message.encode('utf-8')) # encode the message using 'utf-8'
signature = PKCS1_v1_5.new(pkey).sign(h)
result = base64.b64encode(signature).decode()

Additionally, ensure that the keystring variable is properly defined and contains the private key.