Skip to content

Instantly share code, notes, and snippets.

@willmenn
Created June 12, 2019 09:44
Show Gist options
  • Save willmenn/ccbeec223d7e41d48dc6bf0fbd948650 to your computer and use it in GitHub Desktop.
Save willmenn/ccbeec223d7e41d48dc6bf0fbd948650 to your computer and use it in GitHub Desktop.
JWT implementation in java
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {
String header = "{\"alg\":\"HS256\",\"typ\":\"JWT\"}";
String payload = "{\"sub\":\"1234567890\",\"name\":\"John Doe\",\"iat\":1516239022}";
String headerBase64 = Base64.encodeBase64URLSafeString(header.getBytes());
String payloadBase64 = Base64.encodeBase64URLSafeString(payload.getBytes());
//Create a secret to create the signature
String secret = "your-256-bit-secret"; //this could be anything
final SecretKeySpec secret_key = new javax.crypto.spec.SecretKeySpec(StandardCharsets.UTF_8.encode(secret).array(), "HmacSHA256");
//Create the signature
final Mac mac = Mac.getInstance("HmacSHA256");
mac.init(secret_key);
mac.update(headerBase64.getBytes());
mac.update((byte)'.');
byte[] bytes = mac.doFinal(payloadBase64.getBytes());
//print
System.out.println(headerBase64);
System.out.println(payloadBase64);
System.out.println(Base64.encodeBase64URLSafeString(bytes));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment