0

I am trying to sign a string with an RSA key in Python. I have working JavaScript code that does it, but now I need to replicate it in Python using Python-RSA.

In particular, these are the two JavaScript calls that I need to deal with:

const key = await crypto.subtle.importKey(
'raw',
bytesOfSecretKey,
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign']);

and

const mac = await crypto.subtle.sign('HMAC', key, bytesOfStringToSign));

where bytesOfSecretKey is just a key string represented as bytes, and bytesOfStringToSign is the string I am signing. Any pointers would be appreciated!

2
  • 3
    The JavaScript code does not use RSA for signing, but an HMAC. The latter is supported e.g. by the Python standard library (s. hmac). Python-RSA is not required for this (and afaik does not even provide this functionality). Commented Jan 8, 2023 at 20:44
  • @Topaco Thanks man, that's exactly it. Got it to work with signature = hmac.new(key.encode("utf-8"), str.encode("utf-8"), hashlib.sha256).hexdigest() Commented Jan 8, 2023 at 23:08

1 Answer 1

1

As pointed out by the commenter, the JavaScript code uses HMAC to generate the signature. In python the equivalent code to generate the hexadecimal signature would be:

import hmac
import hashlib

key = 'SECRET_KEY_STRING'
strToSign = 'STRING_TO_SIGN'

signature = hmac.new(key.encode("utf-8"),
                     strToSign.encode("utf-8"), hashlib.sha256).hexdigest()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.