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(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(utf8Data);

    String authToken = encodedHeader + "." + encodedData;

    byte[] signatureBytes = CryptoJS.HmacSHA512(authToken, apiSecret);
    String signature = base64url(new String(signatureBytes));

    String signedToken = authToken + "." + signature;

    System.out.println(signedToken);
}
将以下代码转换为java代码function base64urlsource Encode in classical base64 encodedSource = CryptoJSencBase64stringifysource; Remove padding equal characters encodedSource = encodedSourcereplace=+$ ; R

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

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