JavaScript(crypto.subtle)vs python(pycryptodomex)钥匙包装
我的公钥加密在 Javascript 中运行良好。我使用的是 RSA-OAEP 封装的 AES-GCM。加密/解密在 Javascript 版本中运行良好。现在我正在尝试加密服务器端的某些内容(python)并使用我现有的解密客户端(window.crypto.subtle)。当我尝试打开密钥并出现以下错误时,它失败了:
OperationError: The operation failed for an operation-specific reason
超级有用的错误消息! python 中的相关代码是:
from Cryptodome.Cipher import AES
from Cryptodome.Random import get_random_bytes
from Cryptodome.Cipher import PKCS1_OAEP
from Cryptodome.PublicKey import RSA
keyPub = RSA.import_key(base64.b64decode(public_key))
rsa_cipher = PKCS1_OAEP.new(keyPub)
aes = get_random_bytes(16)
aes_cipher = AES.new(aes, AES.MODE_GCM)
wrapped = str(base64.b64encode(rsa_cipher.encrypt(aes)), 'ascii')
要解开的代码是:
window.crypto.subtle.unwrapKey(
'raw',
self.from64(wrapped),
self.keyPair.privateKey,
{
name: "RSA-OAEP"
},
{
name: "AES-GCM"
},
false,
["decrypt"]
).then((aesKey) => {
我对 base64 转换很有信心,因为 Python 代码很乐意接受我的公钥,但如果 ASN.1 被搞乱了,则不会。
当我尝试用 Javascript 解开密钥包装时,你能看出为什么 Python 中的密钥包装失败吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是,错误消息非常不具体(WebCrypto API 经常出现这种情况)。但是,发布的 WebCrypto 代码可以正常工作,如以下代码片段所示。
包装的密钥是使用发布的 Python 代码创建的。
检查您的代码是否存在差异。一个可能的错误可能是关键导入。检查您的代码是否在
importKey()
调用。 Python 代码默认对 OAEP 和 MGF1 摘要使用 SHA-1(请参阅PKCS1_OAEP.new()
)。Unfortunately, the error message is very unspecific (as is often the case with the WebCrypto API). However, the posted WebCrypto code works, as the following code snippet shows.
The wrapped key was created using the posted Python code.
Inspect your code for differences. A possible bug could be the key import. Check in your code if SHA-1 is explicitly specified as digest in the 3rd parameter of the
importKey()
call. The Python code uses SHA-1 by default for the OAEP and MGF1 digest (seePKCS1_OAEP.new()
).