Created
June 12, 2019 09:44
-
-
Save willmenn/ccbeec223d7e41d48dc6bf0fbd948650 to your computer and use it in GitHub Desktop.
JWT implementation in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
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