1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.quic;
17
18 import io.netty.util.concurrent.FastThreadLocal;
19
20 import javax.crypto.Mac;
21 import javax.crypto.spec.SecretKeySpec;
22 import java.nio.ByteBuffer;
23 import java.security.InvalidKeyException;
24 import java.security.NoSuchAlgorithmException;
25 import java.security.SecureRandom;
26 import java.util.Arrays;
27
28 final class Hmac {
29
30 private static final String ALGORITHM = "HmacSHA256";
31
32
33
34
35 private static final byte[] CID_KEY = new byte[32];
36 private static final byte[] TOKEN_KEY = new byte[32];
37
38 static {
39 SecureRandom rng = new SecureRandom();
40 rng.nextBytes(CID_KEY);
41 rng.nextBytes(TOKEN_KEY);
42 }
43
44 private static final FastThreadLocal<Mac> CID_MACS = new FastThreadLocal<Mac>() {
45 @Override
46 protected Mac initialValue() {
47 return newMac(CID_KEY);
48 }
49 };
50
51 private static final FastThreadLocal<Mac> TOKEN_MACS = new FastThreadLocal<Mac>() {
52 @Override
53 protected Mac initialValue() {
54 return newMac(TOKEN_KEY);
55 }
56 };
57
58 private static Mac newMac(byte[] key) {
59 try {
60 SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM);
61 Mac mac = Mac.getInstance(ALGORITHM);
62 mac.init(keySpec);
63 return mac;
64 } catch (NoSuchAlgorithmException | InvalidKeyException exception) {
65 throw new IllegalStateException(exception);
66 }
67 }
68
69 private static ByteBuffer sign(Mac mac, ByteBuffer input, int outLength) {
70 mac.reset();
71 mac.update(input);
72 byte[] signBytes = mac.doFinal();
73 if (signBytes.length != outLength) {
74 signBytes = Arrays.copyOf(signBytes, outLength);
75 }
76 return ByteBuffer.wrap(signBytes);
77 }
78
79 static ByteBuffer signCid(ByteBuffer input, int outLength) {
80 return sign(CID_MACS.get(), input, outLength);
81 }
82
83 static ByteBuffer signToken(ByteBuffer input, int outLength) {
84 return sign(TOKEN_MACS.get(), input, outLength);
85 }
86
87 private Hmac() { }
88 }