Skip to content
This repository was archived by the owner on Jul 7, 2024. It is now read-only.

Commit d32e52a

Browse files
committed
Add authentication to shared
1 parent b5008a8 commit d32e52a

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,5 @@
1414

1515
target/
1616
*.yml
17+
18+
shared.iml
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.cascadebot.shared;
2+
3+
import javax.crypto.Mac;
4+
import javax.crypto.spec.SecretKeySpec;
5+
import java.nio.charset.StandardCharsets;
6+
import java.security.InvalidKeyException;
7+
import java.security.NoSuchAlgorithmException;
8+
9+
public class Auth {
10+
11+
private Mac hmac;
12+
13+
public Auth(String key) throws NoSuchAlgorithmException, InvalidKeyException {
14+
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA512");
15+
hmac = Mac.getInstance("HmacSHA512");
16+
hmac.init(keySpec);
17+
}
18+
19+
public String hmacEncrypt(String text) {
20+
return toHex(hmac.doFinal(text.getBytes(StandardCharsets.UTF_8)));
21+
}
22+
23+
public boolean verifyEncrypt(String text, String hmacText) {
24+
return toHex(hmac.doFinal(text.getBytes(StandardCharsets.UTF_8))).equals(hmacText);
25+
}
26+
27+
private static String digits = "0123456789abcdef";
28+
29+
public static String toHex(byte[] data) {
30+
return toHex(data, data.length);
31+
}
32+
33+
public static String toHex(byte[] data, int length) {
34+
StringBuilder buf = new StringBuilder();
35+
36+
for(int i = 0; i != length; i++) {
37+
int v = data[i] & 0xff;
38+
buf.append(digits.charAt(v >> 4));
39+
buf.append(digits.charAt(v & 0xf));
40+
}
41+
42+
return buf.toString();
43+
44+
}
45+
}

0 commit comments

Comments
 (0)