Static secret like byte [], Key or String?

I started working with JJWT to handle JWT on my server application.

My JWT secret will be saved in a folder resourcesand I will upload the secret with the class Properties.

JJWT contains three JWT signing methods, one uses byte[], the other uses String, and the other uses Key:

JwtBuilder signWith(SignatureAlgorithm var1, byte[] var2);

JwtBuilder signWith(SignatureAlgorithm var1, String var2);

JwtBuilder signWith(SignatureAlgorithm var1, Key var2);

Question: Regarding security, encoding and other things, are there recommendations from which I should use?

While I stood with String, since it Propertiesreturns a String.

+3
source share
1 answer

JavaDoc signWith(SignatureAlgorithm var1, String var2) :

/**
 * Signs the constructed JWT using the specified algorithm with 
 * the specified key, producing a JWS.
 *
 * <p>
 * This is a convenience method: the string argument is first
 * BASE64-decoded to a byte array and this resulting byte array is
 * used to invoke {@link #signWith(SignatureAlgorithm, byte[])}.
 * </p>
 *
 * @param alg                    the JWS algorithm to use to digitally
 *                               sign the JWT, thereby producing a JWS.
 *
 * @param base64EncodedSecretKey the BASE64-encoded algorithm-specific
 *                               signing key to use to digitally sign
 *                               the JWT.
 *
 * @return the builder for method chaining.
 */
JwtBuilder signWith(SignatureAlgorithm alg, String base64EncodedSecretKey);

, , Base64. , , . JJWT Base64, , Base64, , .

JWT JWA , HMAC , .

, :

| If you're signing with: | your key (byte array) length MUST be: |
| ----------------------- | ------------------------------------- |
| HMAC SHA 256            | >= 256 bits (32 bytes)                |
| HMAC SHA 384            | >= 384 bits (48 bytes)                |
| HMAC SHA 512            | >= 512 bits (64 bytes)                |

- JWT - , , . , secret ( , !).

, , JJWT , , io.jsonwebtoken.impl.crypto.MacProvider.

generateKey, , , HMAC. :

//creates a 256-bit secure-random key:
MacProvider.generateKey(SignatureAlgorithm.HS256);

//creates a 384-bit secure-random key:
MacProvider.generateKey(SignatureAlgorithm.HS384);

//creates a 512-bit secure-random key (the default):
MacProvider.generateKey();

String, , , Base64:

SecretKey key = MacProvider.generateKey();
byte[] keyBytes = key.getEncoded();

String base64Encoded = TextCodec.BASE64.encode(keyBytes);

: base64Encoded -. Base64 - . , ( ..).

, JWS, base64Encoded, JJWT , base64 , , :

Jwts.builder()
    //...
    .signWith(SignatureAlgorithm.HS512, base64Encoded)
    .compact();
+5

Source: https://habr.com/ru/post/1666836/


All Articles