· 7 years ago · Nov 29, 2018, 11:20 AM
1import java.io.*;
2import java.security.NoSuchAlgorithmException;
3import java.util.ArrayList;
4
5import javax.crypto.KeyGenerator;
6import javax.crypto.SecretKey;
7
8
9public class ClientUserCache {
10
11 public static void main(String[] args){
12 new ClientUserCache("testuser");
13 }
14
15 public SecretKey key;
16 public String dir = System.getenv("APPDATA")+"/o/";
17 public File file;
18 public BufferedReader in;
19 public BufferedWriter out;
20 public ArrayList<String> cache = new ArrayList<String>();
21
22
23 private ClientUserCache(String filename){
24 try {
25 File k = new File(dir, "key.oc");
26 if(!k.exists()){
27 ObjectOutputStream keyOut = new ObjectOutputStream(new FileOutputStream(k));
28 key = KeyGenerator.getInstance("DES").generateKey();
29 keyOut.writeObject(key);
30 }else{
31 ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(k));
32 key = (SecretKey) keyIn.readObject();
33 }
34 } catch (Exception e1) {
35 e1.printStackTrace();
36 }
37 File dirCheck = new File(dir);
38 if(!dirCheck.exists()){
39 dirCheck.mkdir();
40 }
41 if(dirCheck.isDirectory()){
42 file = new File(dir, filename+".oc");
43 if(!file.exists()){
44 if(file.length() <= 0)
45 try {
46 file.createNewFile();
47 } catch (IOException e) {
48 e.printStackTrace();
49 }
50 }
51 }
52 for(String s : readCredentials()){
53 System.out.println(s);
54 }
55 }
56
57 public ClientUserCache(String username, String password){
58 this(username);
59 this.writeCredentials(new String[]{username, password});
60 }
61
62 public String[] readCredentials(){
63 String[] result = new String[2];
64 try {
65 in = new BufferedReader(new InputStreamReader(new DataInputStream(new FileInputStream(file))));
66 String temp;
67 int type = 0;
68 while((temp = in.readLine()) != null){
69 if(type < 3){
70 result[type] = temp;
71 type++;
72 }
73 }
74 in.close();
75 } catch (Exception e) {
76 e.printStackTrace();
77 }
78 System.out.println("Done!");
79 Protector p = null;
80 try {
81 p = new Protector(key);
82 }catch(Exception e){}
83
84 return new String[]{p.decrypt(result[0]),p.decrypt(result[1])};
85 }
86 public void writeCredentials(String[] s){
87 try {
88 if(s.length != 2){
89 return;
90 }
91 out = new BufferedWriter(new OutputStreamWriter(new DataOutputStream(new FileOutputStream(file))));
92 Protector p = null;
93 try {
94 p = new Protector(key);
95 }catch(Exception e){}
96
97 for(String outs : s){
98 out.write(p.encrypt(outs));
99 out.write("\n");
100 }
101 out.close();
102 } catch (Exception e) {
103 e.printStackTrace();
104 }
105 System.out.println("Done!"); }
106}