Creating JWT and signing it

Posted on
  • Found this link and started with this:

    var header = {
      "alg": "HS256",
      "typ": "JWT"
    };
    
    var data = {
      "id": 1337,
      "username": "john.doe"
    };
    
    var encodedHeader = btoa(JSON.stringify(header));
    var encodedData = btoa(JSON.stringify(data));
    var token = encodedHeader + "." + encodedData;
    var secret = "My very confidential secret!";
    
    print(token);
    
    /* struggled at this point, no clue if there i an existing solution for this 
    var signature = CryptoJS.HmacSHA256(token, secret);
    */
    
    signature = btoa(signature);
    var signedToken = token + "." + signature;
    
    

    Any hints howto?

  • Would https://www.espruino.com/Reference#l_cry­pto_SHA256 work?

    That doesn't have the HMAC but you might be able to use https://www.espruino.com/hmac

    Seems like there's a convenience function for SHA1 but hmac=require("hmac"); ... = new hmac.HMAC(key, require('crypto').SHA256, 64, 20); might do it (if you know what block size HmacSHA256 uses?)

  • Nice, thank for sharing, will try to write a HmacSHA256 module.

  • sha-256 64 32

  • Maybe you could do a PR to add that to the hmac module?

  • Yes, definitely - on my way but struggling a fresh LINUX build and a working connecting via tcp.

  • There should be a new module named hmac2, because not all boards include SHA256.

  • Missing a last piece, how to encode the Uint8Array([...]).bufferto a base64. The method toString only allow option 2 and 16, base64 is not implemented, any hint?

  • got it

    signature = HmacSHA256(token, secret);
    print(btoa(String.fromCharCode.apply(nul­l, signature)));
    
  • Using module hmac256 to create JSON Web Token. A PR is wating for verification and comments.

    const HMAC = require('hmac2256');
    HmacSHA256 = function(token, secret) {
          var hmac = HMAC.SHA256(E.toArrayBuffer(secret));
         return btoa(String.fromCharCode.apply(null,  hmac.digest(E.toArrayBuffer(token)))).re­place(/=+$/, ''); 
    };
    
    var header = { "alg": "HS256", "typ": "JWT"};
    var data = { "id": 1337,"username": "john.doe"};
    var secret = "My very confidential secret!";
    var encodedHeader = btoa(JSON.stringify(header));
    var encodedData = btoa(JSON.stringify(data));
    var token = encodedHeader + "." + encodedData;
    var signature = HmacSHA256(token, secret);
    var jwt = (token+'.'+signature);
    
  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Creating JWT and signing it

Posted by Avatar for MaBe @MaBe

Actions