Rijul Choudhry
Rijul Choudhry

Reputation: 1

I am using java code for jwt but get slight variations in comparsion to online tools.Why?

I have my java piece of code :

 public static String generate(String key, String data) throws NoSuchAlgorithmException, InvalidKeyException {
            if (key == null || data == null) {
                throw new NullPointerException();
            }
            final Mac hMacSHA256 = Mac.getInstance(HMAC_SHA256);
            byte[] hmacKeyBytes = key.getBytes(StandardCharsets.UTF_8);
            final SecretKeySpec secretKey = new SecretKeySpec(hmacKeyBytes, HMAC_SHA256);
            hMacSHA256.init(secretKey);
            byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
            byte[] res = hMacSHA256.doFinal(dataBytes);

            return Base64.getEncoder().encodeToString(res);

        }

And using Base64 encoding I get the following signature: OpDZIL3l/RRZoeDgMBmlaRGPAthcbyiZJt5wqWFPSK4=

If I check the online tool,the signature there shows: OpDZIL3l_RRZoeDgMBmlaRGPAthcbyiZJt5wqWFPSK4=

Only the "_" is replaced with "/". Can anyone help me out with this as I am new to JWT?

Thanks in advance

Upvotes: 0

Views: 45

Answers (1)

sleske
sleske

Reputation: 83635

Only the "_" is replaced with "/". Can anyone help me out with this as I am new to JWT?

This has nothing to do with JWT - the two systems simply use different variants of the Base64 encoding.

The thing is - there are multiple variants of Base64. The Wikipedia article has a nice overview.

In particular, there is the so-called "URL-safe" encoding, or base64url, standardized in RFC 4648. The only difference to regular Base64 is that it uses the characters - and _ instead of + and /. That's what you are seeing.


The advantage of the URL-safe encoding, as the name implies, is that encoded strings can be included in URLs as query parameters without further encoding (i.e. URL percent-encoding). The characters + and / used by standard Base64 have special meaning in URLs, so would need to be encoded, so they are replace by - and _.

The URL-safe encoding is often used for JWTs, because they are often passed as URL parameters.

Upvotes: 1

Related Questions