Reputation: 1143
I have to get a JWT using the SHA-256 algorithm and a secret key (for example "blablablamysecretkey").
Despite checking SO, several libraries and their documentations I don't know yet how to perform this.
If I use this library https://github.com/jwtk/jjwt (one of the most used) this is the code sample:
Key key = MacProvider.generateKey();
String s = Jwts.builder().setSubject("stringtoencode").signWith(SignatureAlgorithm.HS512, key).compact();
Since I have to use SHA-256 algorithm I guess that I should use:
Key key = MacProvider.generateKey();
String s = Jwts.builder().setSubject("stringtoencode").signWith(SignatureAlgorithm.HS256, key).compact();
My problem is that this sample (and all of the samples I've seen by the way) use Key key = MacProvider.generateKey();, and if I'm not wrong this generates a generic key. In fact this is what the documentation says:
// We need a signing key, so we'll create one just for this example. Usually
// the key would be read from your application configuration instead.
So my problem is how could I convert my secret key (string) into something of Key class?
Upvotes: 4
Views: 4025
Reputation: 39251
MacProvider.generateKey()
generates a random secret key, which is safer than using a passphrase. Keys need to be chosen at random. Read this post if you want to know how hmac keys have to be generated https://security.stackexchange.com/questions/95972/what-are-requirements-for-hmac-secret-key
// We need a signing key, so we'll create one just for this example. Usually // the key would be read from your application configuration instead.
The text you have highlighted means that you have to persist the key in your server in order to verify JWT signature when a client sends a token. HMAC keys are symmetric, the key is used both for sign and verify
If you want to generate a Key
from a passphrase String
use
byte hmacKey[] = passphrase.getBytes(StandardCharsets.UTF8);
Key key = new SecretKeySpec(hmacKey,signatureAlgorithm.getJcaName());
Upvotes: 2