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

huangapple go评论81阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年1月9日 04:03:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75050886.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定