简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM