且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

与RESTful API相比,使用RSA签名JWT与SHA相比有什么优势?

更新时间:2023-02-27 13:11:40

我假设您在这里谈论的是RSxxx(例如RSA256)和HSxxx(例如HS256(HMAC-SHA256))算法.主要区别在于HS256是对称算法,而RS256是非对称算法.对称算法仅使用一个密钥(或秘密)进行签名和验证,而非对称算法则使用私钥进行签名和公钥来验证令牌.

I assume you're talking about RSxxx (e.g. RSA256) and HSxxx (e.g. HS256 (HMAC-SHA256)) algorithms here. The main difference is that HS256 is an symmetric algorithm while RS256 is an asymmetric algorithm. Symmetric algorithms just use one key (or secret) for signing and verifying, whereas asymmetric algorithms use the private key to sign and the public key to verify the token.

如果您共享用于HS256的机密,那么知道该机密的每个人都可以发布或修改并重新签名令牌.如果您与客户共享机密,那将破坏签名的目的.如果使用RS256或任何其他非对称算法,则只有身份验证服务器才能知道私钥,并且需要验证令牌的任何人都可以使用公钥来做到这一点.匹配密钥通常由令牌标题中的 KID (密钥ID)声明标识.

If you share the secret used for HS256, everyone knowing the secret could issue or modify and re-sign a token. That would defeat the purpose of the signature if you share the secret with the client. In case of RS256 or any other asymmetric algorithm, only the authentication server knows the private key and anyone who need to verify the token can use the public key to do so. The matching key is usually identified by the KID (Key Id) claim in the header of the token.

但是通常,签名和验证仅在服务器端完成,客户端不需要验证令牌,因此根本不需要知道密钥或机密.因此,在简单服务的情况下,当身份验证和资源服务器相同时,仍可以依靠对称算法.但是,一旦为多个资源服务器使用一台单独的身份验证服务器,就应该使用非对称算法.

But usually, signing and verifying is only done on server side, the client does not need to verify the token and thus does not need to know the key or secret at all. Therefore you can in case of a simple service, when authentication and resource server are the same, still rely on a symmetric algorithms. But once you have one separate authentication server for several resource servers, asymmetric algotrithms should be used.