summary refs log tree commit diff stats
path: root/src/main/java/ganarchy/friendcode/sam/I2PSamAuthUtil.java
blob: ff8455184d64c0e52405186d5feb5017b665167b (plain) (blame)
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
package ganarchy.friendcode.sam;

import ganarchy.friendcode.util.ConfigUtil;
import org.apache.commons.codec.binary.Base32;

import java.security.SecureRandom;
import java.util.Properties;

/**
 * Helper for I2P SAM authentication.
 */
public class I2PSamAuthUtil {
    /**
     * The default username. It is used by default.
     */
    private static final String DEFAULT_USERNAME = "minecraft_friendcode";

    /**
     * Fallback authentication password, used on first install.
     */
    private static final AuthenticationPair INSECURE_FALLBACK =
        new AuthenticationPair(DEFAULT_USERNAME, "friendcode");

    /**
     * Returns the currently active SAM auth pair.
     */
    public static AuthenticationPair getAuthPair() {
        AuthenticationPair strongAuthPair = getStrongAuthPair();
        if (strongAuthPair != null) {
            return strongAuthPair;
        }
        return INSECURE_FALLBACK;
    }

    /**
     * Generates and stores a modern auth pair.
     *
     * @return The generated auth pair.
     */
    public static AuthenticationPair upgradeAuthPair() {
        var rand = new SecureRandom();
        var bytes = new byte[16];
        rand.nextBytes(bytes);
        var b32 = new Base32().encodeToString(bytes);
        Properties auth = new Properties();
        auth.setProperty("i2p.sam.username", DEFAULT_USERNAME);
        auth.setProperty("i2p.sam.password", b32);
        if (ConfigUtil.updateSettings(auth)) {
            return new AuthenticationPair(DEFAULT_USERNAME, b32);
        } else {
            return INSECURE_FALLBACK;
        }
    }

    /**
     * Returns whether strong auth is enabled.
     */
    public static boolean isStrongAuth() {
        return getStrongAuthPair() != null;
    }


    /**
     * Returns the currently active strong SAM auth pair, or null if using the
     * weak fallback.
     */
    private static AuthenticationPair getStrongAuthPair() {
        Properties auth = new Properties();
        if (ConfigUtil.getSettings(auth)) {
            String username = auth.getProperty("i2p.sam.username");
            String password = auth.getProperty("i2p.sam.password");
            if (username != null && password != null) {
                return new AuthenticationPair(username, password);
            }
        }
        return null;
    }

    /**
     * An authentication pair.
     *
     * @param user     The username.
     * @param password The password.
     */
    public record AuthenticationPair(String user, String password) {
    }
}