summaryrefslogtreecommitdiffstats
path: root/dozentenmodul/src/main/java/org/openslx/dozmod/authentication/FingerprintManager.java
blob: e41e4f28f4caac9ef1bf665ca511edb408fb9d03 (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
package org.openslx.dozmod.authentication;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Properties;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openslx.dozmod.Config;

public class FingerprintManager {

	private static final Logger LOGGER = LogManager.getLogger(FingerprintManager.class);

	private static final File file = new File(Config.getPath(), "fingerprints.properties");
	private static final Properties prop = new Properties();

	static {
		if (file.exists()) {
			try {
				prop.load(new FileInputStream(file));
			} catch (IOException e) {
				LOGGER.warn("Could not load cached fingerprints from " + file.toString());
			}
		}
	}

	public static void saveKnownFingerprint(String address, byte[] fingerprint) {
		if (saveFingerprint(address, fingerprint, true)) {
			store();
		}
	}

	public static void saveSuggestedFingerprint(String address, byte[] fingerprint) {
		saveFingerprint(address, fingerprint, false);
		prop.setProperty(address + "_master", Base64.getEncoder().encodeToString(fingerprint));
		store();
	}

	private static boolean saveFingerprint(String address, byte[] fingerprint, boolean replace) {
		if (replace || !prop.containsKey(address)) {
			prop.setProperty(address, Base64.getEncoder().encodeToString(fingerprint));
			return true;
		}
		return false;
	}

	private static void store() {
		try {
			prop.store(new FileOutputStream(file), "Written by bwLehrstuhl");
		} catch (IOException e) {
			LOGGER.warn("Could not store fingerprint");
		}
	}

	/**
	 * Get the fingerprint we accepted previously for this address.
	 * 
	 * @param address
	 * @return fingerprint, null if unknown
	 */
	public static byte[] getKnownFingerprint(String address) {
		return Base64.getDecoder().decode(prop.getProperty(address));
	}

	/**
	 * Get the fingerprint the master server suggests should be
	 * the one for the given address.
	 * 
	 * @param address
	 * @return fingerprint, null if unknown
	 */
	public static byte[] getSuggestedFingerprint(String address) {
		return Base64.getDecoder().decode(prop.getProperty(address + "_master"));
	}

}