-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenClaim.java
More file actions
403 lines (291 loc) · 9.35 KB
/
OpenClaim.java
File metadata and controls
403 lines (291 loc) · 9.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
// Optional strict canonicalizer:
// Maven:
// <dependency>
// <groupId>org.webpki</groupId>
// <artifactId>json-canonicalization</artifactId>
// </dependency>
// https://github.com/cyberphone/json-canonicalization
//
// HTTP fetch:
// Uses java.net.URL (built-in)
//
// Base64:
// Uses java.util.Base64
//
// JSON:
// Uses Jackson (com.fasterxml.jackson.databind)
//
// P-256 / ECDSA:
// Uses java.security (EC)
//
// SHA-256:
// Uses java.security.MessageDigest
//
// Note:
// Fallback canonicalization:
// - lexicographically sorted keys
// - arrays preserved
// - numbers converted to strings
// - no whitespace
//
// Signing model:
// signature = sign( SHA256(canonicalized_claim) )
package openclaiming;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.webpki.json.JSONCanonicalizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class OpenClaim {
private static final ObjectMapper mapper = new ObjectMapper();
static {
mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
}
// ---------- CACHE ----------
private static final long TTL = 60_000;
private static class CacheEntry<T> {
long time;
T value;
CacheEntry(long t, T v) { time = t; value = v; }
}
private static final Map<String, CacheEntry<String>> urlCache = new ConcurrentHashMap<>();
private static final Map<String, CacheEntry<Object>> keyCache = new ConcurrentHashMap<>();
private static final Map<String, CacheEntry<PublicKey>> pubKeyCache = new ConcurrentHashMap<>();
private static long now() {
return System.currentTimeMillis();
}
private static <T> T getCache(Map<String, CacheEntry<T>> map, String key) {
CacheEntry<T> e = map.get(key);
if (e != null && now() - e.time < TTL) return e.value;
map.remove(key);
return null;
}
private static <T> void setCache(Map<String, CacheEntry<T>> map, String key, T value) {
map.put(key, new CacheEntry<>(now(), value));
}
// ---------- NORMALIZATION ----------
private static Object normalize(Object v) {
if (v instanceof Map<?,?> map) {
Map<String,Object> sorted = new TreeMap<>();
for (var e : map.entrySet()) {
sorted.put(e.getKey().toString(), normalize(e.getValue()));
}
return sorted;
}
if (v instanceof List<?> list) {
List<Object> out = new ArrayList<>();
for (Object x : list) {
out.add(normalize(x));
}
return out;
}
if (v instanceof Number) {
return v.toString();
}
return v;
}
// ---------- CANONICALIZATION ----------
private static byte[] fallbackCanonicalize(Map<String,Object> claim) throws Exception {
Map<String,Object> obj = new HashMap<>(claim);
obj.remove("sig");
Object normalized = normalize(obj);
return mapper.writeValueAsBytes(normalized);
}
public static byte[] canonicalize(Map<String,Object> claim) throws Exception {
Map<String,Object> obj = new HashMap<>(claim);
obj.remove("sig");
try {
String json = mapper.writeValueAsString(obj);
return new JSONCanonicalizer(json).getEncodedUTF8();
} catch (Exception e) {
return fallbackCanonicalize(claim);
}
}
// ---------- HASH ----------
private static byte[] sha256(byte[] data) throws Exception {
MessageDigest md = MessageDigest.getInstance("SHA-256");
return md.digest(data);
}
// ---------- PEM / DER ----------
private static String derToPem(String base64) {
return "-----BEGIN PUBLIC KEY-----\n" + base64 + "\n-----END PUBLIC KEY-----";
}
private static PublicKey getCachedPublicKey(String base64) throws Exception {
PublicKey cached = getCache(pubKeyCache, base64);
if (cached != null) return cached;
byte[] decoded = Base64.getDecoder().decode(base64);
KeyFactory kf = KeyFactory.getInstance("EC");
PublicKey key = kf.generatePublic(new X509EncodedKeySpec(decoded));
setCache(pubKeyCache, base64, key);
return key;
}
// ---------- DATA KEY ----------
private static Map<String,Object> parseDataKey(String key) {
if (!key.startsWith("data:key/")) return null;
int idx = key.indexOf(",");
if (idx < 0) return null;
String meta = key.substring(5, idx);
String data = key.substring(idx + 1);
String[] parts = meta.split(";");
String fmt = parts[0].replace("key/", "").toUpperCase();
String encoding = "raw";
for (int i = 1; i < parts.length; i++) {
if (parts[i].equals("base64")) encoding = "base64";
if (parts[i].equals("base64url")) encoding = "base64url";
}
Object value = data;
if (encoding.equals("base64")) {
value = Base64.getDecoder().decode(data);
}
return Map.of("fmt", fmt, "value", value);
}
// ---------- FETCH ----------
private static String fetchJson(String url) {
String cached = getCache(urlCache, url);
if (cached != null) return cached;
String data = null;
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(new URL(url).openStream())
);
StringBuilder sb = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
data = sb.toString();
} catch (Exception ignored) {}
setCache(urlCache, url, data);
return data;
}
// ---------- KEY RESOLUTION ----------
private static Object resolveKey(String key, Set<String> seen) throws Exception {
if (seen.contains(key)) {
throw new RuntimeException("OpenClaim: cyclic key reference detected");
}
Object cached = getCache(keyCache, key);
if (cached != null) return cached;
Set<String> next = new HashSet<>(seen);
next.add(key);
if (key.startsWith("data:key/")) {
Object parsed = parseDataKey(key);
setCache(keyCache, key, parsed);
return parsed;
}
if (key.startsWith("http")) {
String[] parts = key.split("#");
String raw = fetchJson(parts[0]);
if (raw == null) return null;
Object json = mapper.readValue(raw, Map.class);
Object current = json;
for (int i = 1; i < parts.length; i++) {
if (current instanceof Map<?,?> m) {
current = m.get(parts[i]);
}
}
if (current instanceof List<?>) {
setCache(keyCache, key, current);
return current;
}
if (current instanceof String s) {
Object resolved = resolveKey(s, next);
setCache(keyCache, key, resolved);
return resolved;
}
return null;
}
int idx = key.indexOf(":");
if (idx > 0) {
Map<String,Object> result = Map.of(
"fmt", key.substring(0, idx).toUpperCase(),
"value", key.substring(idx + 1)
);
setCache(keyCache, key, result);
return result;
}
return null;
}
// ---------- SIGN ----------
public static Map<String,Object> sign(
Map<String,Object> claim,
PrivateKey privateKey
) throws Exception {
PublicKey pub = KeyFactory.getInstance("EC")
.generatePublic(new X509EncodedKeySpec(
KeyFactory.getInstance("EC")
.getKeySpec(privateKey, X509EncodedKeySpec.class)
.getEncoded()
));
String keyStr = "data:key/es256;base64," +
Base64.getEncoder().encodeToString(pub.getEncoded());
List<String> keys = new ArrayList<>();
if (claim.get("key") instanceof List<?> list) {
for (Object o : list) keys.add(o.toString());
}
if (!keys.contains(keyStr)) keys.add(keyStr);
Collections.sort(keys);
List<String> sigs = new ArrayList<>();
if (claim.get("sig") instanceof List<?> list) {
for (Object o : list) sigs.add(o == null ? null : o.toString());
}
while (sigs.size() < keys.size()) sigs.add(null);
int index = keys.indexOf(keyStr);
Map<String,Object> tmp = new HashMap<>(claim);
tmp.put("key", keys);
tmp.put("sig", sigs);
byte[] canon = canonicalize(tmp);
byte[] hash = sha256(canon);
Signature signer = Signature.getInstance("NONEwithECDSA");
signer.initSign(privateKey);
signer.update(hash);
String sig = Base64.getEncoder().encodeToString(signer.sign());
sigs.set(index, sig);
Map<String,Object> out = new HashMap<>(claim);
out.put("key", keys);
out.put("sig", sigs);
return out;
}
// ---------- VERIFY ----------
public static boolean verify(Map<String,Object> claim) throws Exception {
List<String> keys = (List<String>) claim.get("key");
List<String> sigs = (List<String>) claim.get("sig");
if (keys == null || keys.isEmpty()) {
throw new RuntimeException("OpenClaim: missing public keys");
}
Map<String,Object> tmp = new HashMap<>(claim);
tmp.put("key", keys);
tmp.put("sig", sigs);
byte[] canon = canonicalize(tmp);
byte[] hash = sha256(canon);
int valid = 0;
for (int i = 0; i < keys.size(); i++) {
String sigB64 = sigs.get(i);
if (sigB64 == null) continue;
Object resolved = resolveKey(keys.get(i), new HashSet<>());
List<Object> objs = resolved instanceof List<?> l ? (List<Object>) l : List.of(resolved);
for (Object obj : objs) {
if (!(obj instanceof Map<?,?> m)) continue;
if (!"ES256".equals(m.get("fmt"))) continue;
String der = m.get("value") instanceof byte[]
? Base64.getEncoder().encodeToString((byte[]) m.get("value"))
: m.get("value").toString();
PublicKey pub = getCachedPublicKey(der);
Signature verifier = Signature.getInstance("NONEwithECDSA");
verifier.initVerify(pub);
verifier.update(hash);
if (verifier.verify(Base64.getDecoder().decode(sigB64))) {
valid++;
break;
}
}
}
return valid >= 1;
}
}