为什么我可以使用 EC 密钥对使用 RSA 算法对 JWT 进行签名和验证?



我使用node.js中的加密核心模块来生成ec密钥对。

然后我使用这个密钥对对JWT的签名和验证。

我希望签名/验证只有在使用ec算法时才能工作。

然而,它似乎可以与除HMAC以外的任何算法一起工作。

根据我的理解,这应该是不可能的。

谁能给我解释一下这个?感谢您阅读我的问题。

const crypto = require('crypto')
const jwt = require('jsonwebtoken')
const keyPair = crypto.generateKeyPairSync('ec', {
namedCurve: 'secp256k1',
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
})
const token = jwt.sign({}, keyPair.privateKey, {
algorithm: 'ES256' // I expect this to work, but it seems to be also working with e.g. "RS256" or "PS512", which I don't understand.
})
const verify = jwt.verify(token, keyPair.publicKey)

这也让我很好奇,所以我试着去挖掘资料。如果您按照jwt签名过程中发生的操作进行操作,您将最终得到以下内容:

function createKeySigner(bits) {
return function sign(thing, privateKey) {
checkIsPrivateKey(privateKey);
thing = normalizeInput(thing);
// Even though we are specifying "RSA" here, this works with ECDSA
// keys as well.
var signer = crypto.createSign('RSA-SHA' + bits);
var sig = (signer.update(thing), signer.sign(privateKey, 'base64'));
return fromBase64(sig);
}
}

这并没有回答为什么。再深入一点,crypto是用C实现的,我认为这是相关的部分。如果我理解正确的话,它工作的原因主要归结为它只是作为字符串/缓冲区读取的事实。

最新更新