]> nmode's Git Repositories - signal-cli/blob - src/main/java/cli/JsonIdentityKeyStore.java
Update README
[signal-cli] / src / main / java / cli / JsonIdentityKeyStore.java
1 package cli;
2
3 import org.json.JSONArray;
4 import org.json.JSONObject;
5 import org.whispersystems.libaxolotl.IdentityKey;
6 import org.whispersystems.libaxolotl.IdentityKeyPair;
7 import org.whispersystems.libaxolotl.InvalidKeyException;
8 import org.whispersystems.libaxolotl.state.IdentityKeyStore;
9
10 import java.io.IOException;
11 import java.util.HashMap;
12 import java.util.Map;
13
14 public class JsonIdentityKeyStore implements IdentityKeyStore {
15
16 private final Map<String, IdentityKey> trustedKeys = new HashMap<>();
17
18 private final IdentityKeyPair identityKeyPair;
19 private final int localRegistrationId;
20
21 public JsonIdentityKeyStore(JSONObject jsonAxolotl) throws IOException, InvalidKeyException {
22 localRegistrationId = jsonAxolotl.getInt("registrationId");
23 identityKeyPair = new IdentityKeyPair(Base64.decode(jsonAxolotl.getString("identityKey")));
24
25 JSONArray list = jsonAxolotl.getJSONArray("trustedKeys");
26 for (int i = 0; i < list.length(); i++) {
27 JSONObject k = list.getJSONObject(i);
28 try {
29 trustedKeys.put(k.getString("name"), new IdentityKey(Base64.decode(k.getString("identityKey")), 0));
30 } catch (InvalidKeyException | IOException e) {
31 System.out.println("Error while decoding key for: " + k.getString("name"));
32 }
33 }
34 }
35
36 public JsonIdentityKeyStore(IdentityKeyPair identityKeyPair, int localRegistrationId) {
37 this.identityKeyPair = identityKeyPair;
38 this.localRegistrationId = localRegistrationId;
39 }
40
41 public JSONObject getJson() {
42 JSONArray list = new JSONArray();
43 for (String name : trustedKeys.keySet()) {
44 list.put(new JSONObject().put("name", name).put("identityKey", Base64.encodeBytes(trustedKeys.get(name).serialize())));
45 }
46
47 JSONObject result = new JSONObject();
48 result.put("registrationId", localRegistrationId);
49 result.put("identityKey", Base64.encodeBytes(identityKeyPair.serialize()));
50 result.put("trustedKeys", list);
51 return result;
52 }
53
54 @Override
55 public IdentityKeyPair getIdentityKeyPair() {
56 return identityKeyPair;
57 }
58
59 @Override
60 public int getLocalRegistrationId() {
61 return localRegistrationId;
62 }
63
64 @Override
65 public void saveIdentity(String name, IdentityKey identityKey) {
66 trustedKeys.put(name, identityKey);
67 }
68
69 @Override
70 public boolean isTrustedIdentity(String name, IdentityKey identityKey) {
71 IdentityKey trusted = trustedKeys.get(name);
72 return (trusted == null || trusted.equals(identityKey));
73 }
74 }