· 6 years ago · Feb 15, 2019, 09:26 PM
1import java.io.File;
2import java.io.FileInputStream;
3import java.io.FileOutputStream;
4import java.io.InputStream;
5import java.io.OutputStream;
6import java.util.Properties;
7
8import javax.crypto.Cipher;
9import javax.crypto.CipherInputStream;
10import javax.crypto.CipherOutputStream;
11import javax.crypto.KeyGenerator;
12import javax.crypto.SecretKey;
13import javax.crypto.spec.SecretKeySpec;
14
15public class Jirau {
16
17 private static final byte[] SALT = "OH MYGOD".getBytes();
18 private static final String ALG = "DES";
19 private static final File PROPS = new File("my.properties");
20
21 public static void main(String[] args) throws Exception {
22 Properties p = new Properties();
23 p.setProperty("foo", "bar");
24
25 save(p);
26
27 Properties p2 = load();
28
29 System.out.println(p2.get("foo"));
30
31
32 }
33
34 public static Properties load() throws Exception {
35 Properties configs = new Properties();
36
37 if (PROPS.exists()) {
38 FileInputStream fin = null;
39
40 try (InputStream in = new FileInputStream(PROPS)) {
41 final SecretKey key = new SecretKeySpec(SALT, ALG);
42
43 final Cipher cipher = Cipher.getInstance(ALG);
44 cipher.init(Cipher.DECRYPT_MODE, key);
45
46 configs.load(new CipherInputStream(in, cipher));
47 }
48 }
49
50 return configs;
51 }
52
53 public static void save(Properties p) throws Exception {
54
55 try (OutputStream os = new FileOutputStream(PROPS)) {
56 final KeyGenerator kg = KeyGenerator.getInstance(ALG);
57
58 final Cipher c = Cipher.getInstance(ALG);
59 final SecretKey key = new SecretKeySpec(SALT, ALG);
60 c.init(Cipher.ENCRYPT_MODE, key);
61
62 p.store(new CipherOutputStream(os, c), null);
63 }
64 }
65
66
67}