我正在使用 RSA 签署 SHA512 哈希并将其保存到文件中。python和javascript上的哈希值相同,但无法验证签名。Python代码:
from Cryptodome.Hash import SHA512
from Cryptodome.PublicKey import RSA
from Cryptodome.Signature import pkcs1_15
hash = SHA512.new(someByteArray)
#This is equal to digest generated in JavaScript
hashDigest = hashPDF.hexdigest()
pk = RSA.importKey(privateKey)
signature=pkcs1_15.new(pk).sign(hashPDF)
#Write signature to file
with open("storage/{0}.sig".format(hashDigest), 'wb+') as f:
f.write(signature)
#Then JavaScript request occurs return content of saved signature in base64
from base64 import b64encode
from flask import jsonify
with open("storage/{0}.sig".format(pdfHashDigest), "rb") as f:
sign = b64encode(f.read())
return jsonify({"sign":sign.decode("utf-8")})
JavaScript:
var hash=await crypto.subtle.digest('SHA-512', Uint8Array.from(atob(someBase64content), c => c.charCodeAt(0)))
//This is equal to python hashDigest
var hashDigest = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
var cryptoKey=await crypto.subtle.importKey('spki', this.pemToArrayBuffer(publicKey), {name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-512'}, false, ["verify"])
//Always false
var result=await crypto.subtle.verify("RSASSA-PKCS1-v1_5", cryptoKey, Uint8Array.from(atob(signature), c => c.charCodeAt(0)), hash)
我尝试了不同的方法将 base64 签名转换为 ArrayBuffer 以在 Web Crypto API 中使用:rfc4648.js、new TextEncoder()、自定义转换为 Uint8Array,但结果总是错误的。我也尝试使用伪造(https://github.com/digitalbazaar/forge)验证签名,但结果也是错误的。
我哪里错了?我试图比较哈希的字节值,它用于签名函数的输入,但实际上它是 python 上的 Crypto.Hash 对象。