import org.apache.commons.codec.binary.Base64; import org.json.JSONObject;

public class JwtAuth { public static String base64url(String source) { // Encode in classical base64 String encodedSource = Base64.encodeBase64String(source.getBytes());

    // Remove padding equal characters
    encodedSource = encodedSource.replaceAll("=+", "");

    // Replace characters according to base64url specifications
    encodedSource = encodedSource.replaceAll("\\+", "-");
    encodedSource = encodedSource.replaceAll("/", "_");

    return encodedSource;
}

public static void main(String[] args) {
    String apiKey = System.getenv("api_key");
    String apiSecret = System.getenv("api_secret");

    JSONObject tokenHeader = new JSONObject();
    tokenHeader.put("alg", "HS512");

    String stringifiedHeader = tokenHeader.toString();
    byte[] utf8Header = stringifiedHeader.getBytes();
    String encodedHeader = base64url(new String(utf8Header));

    JSONObject tokenData = new JSONObject();
    tokenData.put("sub", apiKey);
    tokenData.put("iat", Math.round(System.currentTimeMillis() / 1000.0));
    tokenData.put("exp", Math.round(System.currentTimeMillis() / 1000.0 + 5 * 60));

    String stringifiedData = tokenData.toString();
    byte[] utf8Data = stringifiedData.getBytes();
    String encodedData = base64url(new String(utf8Data));

    String authToken = encodedHeader + "." + encodedData;

    // 使用 HmacSHA512 算法生成签名
    // 需要引入相应的加密库,比如 CryptoJS
    // byte[] signatureBytes = CryptoJS.HmacSHA512(authToken, apiSecret);
    // String signature = base64url(new String(signatureBytes));

    // 签名部分需要根据实际情况进行修改
    String signature = "your_signature";

    String signedToken = authToken + "." + signature;

    System.out.println(signedToken);
}

}

Java JWT 生成代码实现 - 使用 Apache Commons Codec 库

原文地址: https://www.cveoy.top/t/topic/opPf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录