解密签名并实现JWT的精化

解密签名并实现JWT的精化

本文介绍了解密签名并实现JWT的精化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道还有其他一些库可以使我的生活更轻松地与JWT一起使用(在node.js中).

I understand that there exist other libraries which make my life easier to work with JWT (in node.js).

在这种情况下,我使用"crypto-js"以手动方式学习JWT.以下是令牌:

In this case, I am using "crypto-js" to learn JWT in a manual way. The following gives me the token:

var header = {
    "alg": "HS256",
    "typ": "JWT"
};
var wordArrayHeader = CryptoJS.enc.Utf8.parse(JSON.stringify(header));
var base64Header = CryptoJS.enc.Base64.stringify(wordArrayHeader);

var payload = {
    "sub": "1234567890",
    "name": "John Doe",
    "admin": true
};
var wordArrayPayload = CryptoJS.enc.Utf8.parse(JSON.stringify(payload));
var base64Payload = CryptoJS.enc.Base64.stringify(wordArrayPayload);

var signature = CryptoJS.HmacSHA256(base64Header + "." + base64Payload , "secret");
var base64Sign = CryptoJS.enc.Base64.stringify(signature);
var token = base64Header + "." + base64Payload + "." + base64Sign;

我无法完全相反地验证令牌.例如,解密签名时,以下内容会引发错误:

I am unable to do the exact opposite, to verify the token. For example, the following throws me an error when decrypting the signature:

var token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ";
var base64Header = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
var base64Payload = "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9";
var base64Sign = "TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ";

var parsedSignArray = CryptoJS.enc.Base64.parse(base64Sign);
var parsedSign = parsedSignArray.toString(CryptoJS.enc.Utf8);
var decrypted = CryptoJS.HmacSHA256.decrypt(parsedSign , "secret");
console.log(decrypted);

我在这里想念什么?顺便说一句,仅在此示例中,我正在使用 http://jwt.io

What am I missing here? BTW, just for this example, I am using token from http://jwt.io

推荐答案

没有CryptoJS.HmacSHA256.decrypt这样的东西.由于HMAC和一般的散列函数都是单向函数,因此验证签名"的唯一方法是对同一字符串运行相同的单向函数,然后将其与您获得的函数进行比较. :

There is no such thing as CryptoJS.HmacSHA256.decrypt. Since HMAC, as well as hash functions in general, are one-way functions the only way to verify the "signature" would be to run the same one way function over the same string and then compare it with the one that you've got:

var signature = CryptoJS.HmacSHA256(base64Header + "." + base64Payload , "secret").toString(CryptoJS.enc.Base64);
var valid = signature == base64Sign;

这篇关于解密签名并实现JWT的精化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 09:21