Json web token 详解(二)

来源:互联网 发布:ubuntu怎么上传lrzsz包 编辑:程序博客网 时间:2024/04/30 17:10

下面不使用jwt的类库,而用一个程序来实现jwt,来加深对jwt的格式和生成的理解。


package jwt;import org.apache.commons.codec.binary.Base64;import javax.crypto.Mac;import javax.crypto.spec.SecretKeySpec;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;/** * 不使用jwt库的java实现jwt数据生成 */public class JwtJava {    private static final String MAC_INSTANCE_NAME = "HMacSHA256";    /**     * 生成jwt的签名部分     * @param secret     * @param message     * @return     * @throws NoSuchAlgorithmException     * @throws InvalidKeyException     */    public static String Hmacsha256(String secret, String message) throws NoSuchAlgorithmException, InvalidKeyException {        Mac hmac_sha256 = Mac.getInstance(MAC_INSTANCE_NAME);        SecretKeySpec key = new SecretKeySpec(secret.getBytes(), MAC_INSTANCE_NAME);        hmac_sha256.init(key);        byte[] buff = hmac_sha256.doFinal(message.getBytes());        return Base64.encodeBase64URLSafeString(buff);    }    /**     * 模拟一个jwt的完成数据     * @throws InvalidKeyException     * @throws NoSuchAlgorithmException     */    public static void testJWT() throws InvalidKeyException, NoSuchAlgorithmException {        //签名的key        String secret = "secret";        //header数据        String headerJson = "{\"type\":\"JWT\",\"alg\":\"HS256\"}";        //Payload(载荷)        String payloadJson = "{\"sub\":\"1234567890\", \"name\":\"John Doe\",\"admin\":true}";        String base64Header = Base64.encodeBase64URLSafeString(headerJson.getBytes());        String base64Claim = Base64.encodeBase64URLSafeString(payloadJson.getBytes());        String signature = Hmacsha256(secret, base64Header + "." + base64Claim);        String jwt = base64Header + "." + base64Claim  + "." + signature;        System.out.println(jwt);    }    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {        JwtJava.testJWT();    }}


原创粉丝点击