Crypto.java 2.15 KB
Newer Older
Melledy's avatar
Melledy committed
1
2
package emu.grasscutter.utils;

3
4
5
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
Melledy's avatar
Melledy committed
6
import java.security.SecureRandom;
7
8
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
Melledy's avatar
Melledy committed
9
10

import emu.grasscutter.Grasscutter;
11

KingRainbow44's avatar
KingRainbow44 committed
12
13
public final class Crypto {
	private static final SecureRandom secureRandom = new SecureRandom();
Melledy's avatar
Melledy committed
14
15

	public static byte[] DISPATCH_KEY;
16
17
	public static byte[] DISPATCH_SEED;

Melledy's avatar
Melledy committed
18
	public static byte[] ENCRYPT_KEY;
19
20
	public static long ENCRYPT_SEED = Long.parseUnsignedLong("11468049314633205968");
	public static byte[] ENCRYPT_SEED_BUFFER = new byte[0];
21
22
23
24
25

    public static PublicKey CUR_OS_ENCRYPT_KEY;
    public static PublicKey CUR_CN_ENCRYPT_KEY;
    public static PrivateKey CUR_SIGNING_KEY;

Melledy's avatar
Melledy committed
26
	public static void loadKeys() {
27
28
		DISPATCH_KEY = FileUtils.readResource("/keys/dispatchKey.bin");
		DISPATCH_SEED = FileUtils.readResource("/keys/dispatchSeed.bin");
29

30
31
		ENCRYPT_KEY = FileUtils.readResource("/keys/secretKey.bin");
		ENCRYPT_SEED_BUFFER = FileUtils.readResource("/keys/secretKeyBuffer.bin");
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

        try {
            //These should be loaded from ChannelConfig_whatever.json
            CUR_SIGNING_KEY = KeyFactory.getInstance("RSA")
                .generatePrivate(new PKCS8EncodedKeySpec(FileUtils.readResource("/keys/SigningKey.der")));

            CUR_OS_ENCRYPT_KEY = KeyFactory.getInstance("RSA")
                .generatePublic(new X509EncodedKeySpec(FileUtils.readResource("/keys/OSCB_Pub.der")));

            CUR_CN_ENCRYPT_KEY = KeyFactory.getInstance("RSA")
                .generatePublic(new X509EncodedKeySpec(FileUtils.readResource("/keys/OSCN_Pub.der")));
        }
        catch (Exception e) {
            Grasscutter.getLogger().error("An error occurred while loading keys.", e);
        }
Melledy's avatar
Melledy committed
47
	}
48

Melledy's avatar
Melledy committed
49
50
51
52
53
54
55
56
57
	public static void xor(byte[] packet, byte[] key) {
		try {
			for (int i = 0; i < packet.length; i++) {
				packet[i] ^= key[i % key.length];
			}
		} catch (Exception e) {
			Grasscutter.getLogger().error("Crypto error.", e);
		}
	}
58

Melledy's avatar
Melledy committed
59
60
61
	public static byte[] createSessionKey(int length) {
		byte[] bytes = new byte[length];
		secureRandom.nextBytes(bytes);
62
		return bytes;
Melledy's avatar
Melledy committed
63
64
	}
}