PlinyTheElder
PlinyTheElder

Reputation: 1494

Signing a string with an RSA key in Python - how can I translate this JavaScript code that uses SubtleCrypto to Python?

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!

Upvotes: 0

Views: 781

Answers (1)

PlinyTheElder
PlinyTheElder

Reputation: 1494

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()

Upvotes: 1

Related Questions