| 218 | // ==================================================== |
| 219 | |
| 220 | public static String Jwt(Object data, Object secret, Object hash, boolean isRsa, Object options2) { |
| 221 | Map<String, Object> options = (options2 instanceof Map) ? (Map<String, Object>) options2 : new LinkedHashMap<>(); |
| 222 | String algorithm = (hash == null) ? null : toString(hash); // e.g., "sha256", "sha384", "sha512" |
| 223 | if (algorithm == null) throw new IllegalArgumentException("JWT requires hash algorithm name"); |
| 224 | |
| 225 | String alg = (isRsa ? "RS" : "HS") + algorithm.substring(3).toUpperCase(Locale.ROOT); |
| 226 | if (options.containsKey("alg")) { |
| 227 | alg = toString(options.get("alg")); |
| 228 | } |
| 229 | |
| 230 | Map<String, Object> header = new LinkedHashMap<>(); |
| 231 | header.put("alg", alg); |
| 232 | header.put("typ", "JWT"); |
| 233 | header.putAll(options); |
| 234 | |
| 235 | // Move iat from header to payload if present (to mimic C# logic) |
| 236 | if (header.containsKey("iat") && data instanceof Map<?, ?>) { |
| 237 | ((Map<String, Object>) data).put("iat", header.get("iat")); |
| 238 | header.remove("iat"); |
| 239 | } |
| 240 | |
| 241 | String encodedHeader = Base64urlEncode(json(header)); |
| 242 | String encodedPayload = Base64urlEncode(json(data)); |
| 243 | String token = encodedHeader + "." + encodedPayload; |
| 244 | |
| 245 | String algoType = alg.substring(0, 2); // HS / RS / ES / Ed |
| 246 | String signatureB64Url; |
| 247 | |
| 248 | if (isRsa) { |
| 249 | // RSxxx with private key PEM |
| 250 | byte[] sig = rsaSign(token, toString(secret), algorithm); |
| 251 | signatureB64Url = Base64ToBase64Url(BinaryToBase64(sig), true); |
| 252 | } else if ("ES".equals(algoType)) { |
| 253 | // ES256: sign over P-256 -> r||s then base64url |
| 254 | byte[] rs = es256Sign(token, toString(secret)); |
| 255 | signatureB64Url = Base64ToBase64Url(BinaryToBase64(rs), true); |
| 256 | } else if ("Ed".equals(algoType)) { |
| 257 | // Ed25519 |
| 258 | String base64Sig = toString(Eddsa(token, secret, ed25519())); |
| 259 | signatureB64Url = Base64ToBase64Url(base64Sig, true); |
| 260 | } else { |
| 261 | // HMAC HS256/384/512 |
| 262 | String bin = toString(Hmac(token, secret, algorithm, "binary")); |
| 263 | // Hmac(...,"binary") above returns byte[] in C#, here we returned hex/base64. |
| 264 | // So call Hmac again but fetch raw bytes: |
| 265 | byte[] sig = hmacRaw(alg, token, secret); |
| 266 | signatureB64Url = Base64ToBase64Url(BinaryToBase64(sig), true); |
| 267 | } |
| 268 | |
| 269 | return token + "." + signatureB64Url; |
| 270 | } |
| 271 | |
| 272 | private static byte[] hmacRaw(String hsName, String data, Object secret) { |
| 273 | // hsName = HS256/HS384/HS512 |