JWT实现ES256加密生成token

jwt实现非对称加密生成token

1、生成私钥

openssl ecparam -genkey -name prime256v1 -noout -out private-key.pem

2、生成公钥

openssl ec -in private-key.pem -pubout -out public-key.pem

此时可以看到 private-key.pem 和 public-key.pem 两个文件。这时候的私钥是不能直接使用的,需要进行 pkcs8 编码

openssl的pkcs8编码命令:

openssl pkcs8 -topk8 -in private_key.pem -out pkcs8_rsa_private_key.pem -nocrypt

此时可以看到 pkcs8_rsa_private_key.pem 文件。

3、Java代码生成jwt token

public static void main(String[] args) throws Exception {
    long iat = new Date().getTime() / 1000;
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    calendar.add(Calendar.DATE, 180);
    long exp = calendar.getTimeInMillis() / 1000;
    System.out.println(iat + "==" + exp);
    HashMap header = new HashMap<>();
    header.put("alg", "ES256");
    header.put("kid", "xxx");
    HashMap payload = new HashMap<>();
    payload.put("iss", "xxx");
    payload.put("iat", iat);
    payload.put("exp", exp);
    payload.put("aud", "xxx");
    payload.put("sub", "xxx");
    SignatureAlgorithm es256 = SignatureAlgorithm.ES256;
    PrivateKey privateKey = getPrivateKeyFromPem();
    String token = Jwts.builder()
            .setHeader(header)
            .setClaims(payload)
            .signWith(es256, privateKey)
            .compact();
    System.out.println(token);
}

// 获取私匙
public static PrivateKey getPrivateKeyFromPem() throws Exception {
    BufferedReader br = new BufferedReader(new FileReader("/Users/data/keytest/pkcs8_rsa_private_key.pem"));
    String s = br.readLine();
    String str = "";
    s = br.readLine();
    while (s.charAt(0) != '-') {
        str += s + "\r";
        s = br.readLine();
    }
    BASE64Decoder base64decoder = new BASE64Decoder();
    byte[] b = base64decoder.decodeBuffer(str);

    // 生成私匙
    KeyFactory kf = KeyFactory.getInstance("ECDH", "BC");
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(b);
    PrivateKey privateKey = kf.generatePrivate(keySpec);
    return privateKey;
}

至此,采用ES256算法加密token完成。

你可能感兴趣的:(工作记录,java,数据结构)