1 package org
.asamk
.signal
;
3 import com
.fasterxml
.jackson
.core
.JsonGenerator
;
4 import com
.fasterxml
.jackson
.core
.JsonParser
;
5 import com
.fasterxml
.jackson
.core
.JsonProcessingException
;
6 import com
.fasterxml
.jackson
.databind
.*;
7 import org
.whispersystems
.libsignal
.InvalidKeyIdException
;
8 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
9 import org
.whispersystems
.libsignal
.state
.PreKeyStore
;
11 import java
.io
.IOException
;
12 import java
.util
.HashMap
;
15 class JsonPreKeyStore
implements PreKeyStore
{
17 private final Map
<Integer
, byte[]> store
= new HashMap
<>();
20 public JsonPreKeyStore() {
24 public void addPreKeys(Map
<Integer
, byte[]> preKeys
) {
25 store
.putAll(preKeys
);
29 public PreKeyRecord
loadPreKey(int preKeyId
) throws InvalidKeyIdException
{
31 if (!store
.containsKey(preKeyId
)) {
32 throw new InvalidKeyIdException("No such prekeyrecord!");
35 return new PreKeyRecord(store
.get(preKeyId
));
36 } catch (IOException e
) {
37 throw new AssertionError(e
);
42 public void storePreKey(int preKeyId
, PreKeyRecord
record) {
43 store
.put(preKeyId
, record.serialize());
47 public boolean containsPreKey(int preKeyId
) {
48 return store
.containsKey(preKeyId
);
52 public void removePreKey(int preKeyId
) {
53 store
.remove(preKeyId
);
56 public static class JsonPreKeyStoreDeserializer
extends JsonDeserializer
<JsonPreKeyStore
> {
59 public JsonPreKeyStore
deserialize(JsonParser jsonParser
, DeserializationContext deserializationContext
) throws IOException
, JsonProcessingException
{
60 JsonNode node
= jsonParser
.getCodec().readTree(jsonParser
);
63 Map
<Integer
, byte[]> preKeyMap
= new HashMap
<>();
65 for (JsonNode preKey
: node
) {
66 Integer preKeyId
= preKey
.get("id").asInt();
68 preKeyMap
.put(preKeyId
, Base64
.decode(preKey
.get("record").asText()));
69 } catch (IOException e
) {
70 System
.out
.println(String
.format("Error while decoding prekey for: %s", preKeyId
));
75 JsonPreKeyStore keyStore
= new JsonPreKeyStore();
76 keyStore
.addPreKeys(preKeyMap
);
83 public static class JsonPreKeyStoreSerializer
extends JsonSerializer
<JsonPreKeyStore
> {
86 public void serialize(JsonPreKeyStore jsonPreKeyStore
, JsonGenerator json
, SerializerProvider serializerProvider
) throws IOException
, JsonProcessingException
{
87 json
.writeStartArray();
88 for (Map
.Entry
<Integer
, byte[]> preKey
: jsonPreKeyStore
.store
.entrySet()) {
89 json
.writeStartObject();
90 json
.writeNumberField("id", preKey
.getKey());
91 json
.writeStringField("record", Base64
.encodeBytes(preKey
.getValue()));
92 json
.writeEndObject();