· 4 years ago · Feb 19, 2021, 05:36 PM
1import java.security.GeneralSecurityException;
2import java.security.Key;
3import java.security.KeyFactory;
4import java.security.KeyPair;
5import java.security.KeyPairGenerator;
6import java.security.NoSuchAlgorithmException;
7import java.security.PublicKey;
8import java.security.spec.X509EncodedKeySpec;
9import java.util.Arrays;
10import java.util.Random;
11import javax.crypto.Cipher;
12import javax.crypto.SecretKey;
13import javax.crypto.spec.SecretKeySpec;
14import net.md_5.bungee.jni.NativeCode;
15import net.md_5.bungee.jni.cipher.BungeeCipher;
16import net.md_5.bungee.jni.cipher.JavaCipher;
17import net.md_5.bungee.jni.cipher.NativeCipher;
18import net.md_5.bungee.protocol.packet.EncryptionRequest;
19import net.md_5.bungee.protocol.packet.EncryptionResponse;
20
21public class EncryptionUtil {
22 private static final Random random = new Random();
23
24 public static final KeyPair keys;
25
26 public static SecretKey getSecret() {
27 return secret;
28 }
29
30 private static final SecretKey secret = new SecretKeySpec(new byte[16], "AES");
31
32 public static final NativeCode<BungeeCipher> nativeFactory = new NativeCode("native-cipher", JavaCipher.class, NativeCipher.class);
33
34 static {
35 try {
36 KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
37 generator.initialize(1024);
38 keys = generator.generateKeyPair();
39 } catch (NoSuchAlgorithmException ex) {
40 throw new ExceptionInInitializerError(ex);
41 }
42 }
43
44 public static EncryptionRequest encryptRequest() {
45 String hash = Long.toString(random.nextLong(), 16);
46 byte[] pubKey = keys.getPublic().getEncoded();
47 byte[] verify = new byte[4];
48 random.nextBytes(verify);
49 return new EncryptionRequest(hash, pubKey, verify);
50 }
51
52 public static SecretKey getSecret(EncryptionResponse resp, EncryptionRequest request) throws GeneralSecurityException {
53 Cipher cipher = Cipher.getInstance("RSA");
54 cipher.init(2, keys.getPrivate());
55 byte[] decrypted = cipher.doFinal(resp.getVerifyToken());
56 if (!Arrays.equals(request.getVerifyToken(), decrypted))
57 throw new IllegalStateException("Key pairs do not match!");
58 cipher.init(2, keys.getPrivate());
59 return new SecretKeySpec(cipher.doFinal(resp.getSharedSecret()), "AES");
60 }
61
62 public static BungeeCipher getCipher(boolean forEncryption, SecretKey shared) throws GeneralSecurityException {
63 BungeeCipher cipher = (BungeeCipher)nativeFactory.newInstance();
64 cipher.init(forEncryption, shared);
65 return cipher;
66 }
67
68 public static PublicKey getPubkey(EncryptionRequest request) throws GeneralSecurityException {
69 return KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(request.getPublicKey()));
70 }
71
72 public static byte[] encrypt(Key key, byte[] b) throws GeneralSecurityException {
73 Cipher hasher = Cipher.getInstance("RSA");
74 hasher.init(1, key);
75 return hasher.doFinal(b);
76 }
77}