@Test public void testGenerateHmacSignature() { Jwt jwt = new Jwt(); jwt.getHeader().setType("JWT"); jwt.getHeader().setAlgorithm("HS256"); jwt.getClaims().setExpiration(new Date(1300819380L * 1000L)); jwt.getClaims().setIssuer("joe"); jwt.getClaims().setClaim("http://example.com/is_root", Boolean.TRUE); byte[] key = null; JwtSigner signer; // sign it try { key = "secret".getBytes("UTF-8"); signer = new HmacSigner(); ((HmacSigner) signer).setPassphrase(key); ((HmacSigner) signer).afterPropertiesSet(); signer.sign(jwt); /* * Expected string based on the following structures, serialized exactly * as follows and base64 encoded: * * header: {"typ":"JWT","alg":"HS256"} claims: * {"exp":1300819380,"iss":"joe","http://example.com/is_root":true} * * Expected signature: iGBPJj47S5q_HAhSoQqAdcS6A_1CFj3zrLaImqNbt9E */ String signature = "p-63Jzz7mgi3H4hvW6MFB7lmPRZjhsL666MYkmpX33Y"; String expected = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjEzMDA4MTkzODAsImlzcyI6ImpvZSIsImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ." + signature; String actual = jwt.toString(); assertThat(actual, equalTo(expected)); assertThat(jwt.getSignature(), equalTo(signature)); assertThat(signer.verify(actual), equalTo(true)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@Test public void testValidateHmacSignature() { byte[] key = null; JwtSigner signer; // sign it try { key = "secret".getBytes("UTF-8"); signer = new HmacSigner(); ((HmacSigner) signer).setPassphrase(key); ((HmacSigner) signer).afterPropertiesSet(); /* * Token string based on the following structures, serialized exactly as * follows and base64 encoded: * * header: {"typ":"JWT","alg":"HS256"} claims: * {"exp":1300819380,"iss":"joe","http://example.com/is_root":true} * * Python script to generate signature: * * import hashlib * import hmac * import base64 * * m = hmac.new('secret', 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjEzMDA4MTkzODAsImlzcyI6ImpvZSIsImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ', hashlib.sha256) * base64.urlsafe_b64encode(m.digest()) * * Expected signature: p-63Jzz7mgi3H4hvW6MFB7lmPRZjhsL666MYkmpX33Y */ String jwtString = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjEzMDA4MTkzODAsImlzcyI6ImpvZSIsImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.p-63Jzz7mgi3H4hvW6MFB7lmPRZjhsL666MYkmpX33Y"; boolean valid = signer.verify(jwtString); assertThat(valid, equalTo(Boolean.TRUE)); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }