英文:
Signing a string with an RSA key in Python - how can I translate this JavaScript code that uses SubtleCrypto to Python?
问题
我正在尝试使用Python中的RSA密钥对字符串进行签名。我有一个可以正常工作的JavaScript代码,它可以完成这个任务,但现在我需要在Python中使用Python-RSA来复制它。
特别是,这是我需要处理的两个JavaScript调用:
const key = await crypto.subtle.importKey(
'raw',
bytesOfSecretKey,
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign']);
和
const mac = await crypto.subtle.sign('HMAC', key, bytesOfStringToSign);
其中bytesOfSecretKey
只是表示为字节的密钥字符串,而bytesOfStringToSign
是我要签名的字符串。任何指导都将不胜感激!
英文:
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!
答案1
得分: 1
根据评论者指出,JavaScript 代码使用 HMAC 生成签名。在 Python 中生成十六进制签名的等效代码如下:
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()
英文:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论