1package eu.siacs.conversations.crypto.axolotl;
2
3import android.util.Base64;
4import android.util.Log;
5
6import java.security.InvalidAlgorithmParameterException;
7import java.security.InvalidKeyException;
8import java.security.NoSuchAlgorithmException;
9import java.security.NoSuchProviderException;
10import java.security.SecureRandom;
11import java.util.HashMap;
12import java.util.List;
13import java.util.Map;
14
15import javax.crypto.BadPaddingException;
16import javax.crypto.Cipher;
17import javax.crypto.IllegalBlockSizeException;
18import javax.crypto.KeyGenerator;
19import javax.crypto.NoSuchPaddingException;
20import javax.crypto.SecretKey;
21import javax.crypto.spec.IvParameterSpec;
22import javax.crypto.spec.SecretKeySpec;
23
24import eu.siacs.conversations.Config;
25import eu.siacs.conversations.xml.Element;
26import eu.siacs.conversations.xmpp.jid.Jid;
27
28public class XmppAxolotlMessage {
29 public static final String CONTAINERTAG = "encrypted";
30 public static final String HEADER = "header";
31 public static final String SOURCEID = "sid";
32 public static final String KEYTAG = "key";
33 public static final String REMOTEID = "rid";
34 public static final String IVTAG = "iv";
35 public static final String PAYLOAD = "payload";
36
37 private static final String KEYTYPE = "AES";
38 private static final String CIPHERMODE = "AES/GCM/NoPadding";
39 private static final String PROVIDER = "BC";
40
41 private byte[] innerKey;
42 private byte[] ciphertext = null;
43 private byte[] iv = null;
44 private final Map<Integer, byte[]> keys;
45 private final Jid from;
46 private final int sourceDeviceId;
47
48 public static class XmppAxolotlPlaintextMessage {
49 private final String plaintext;
50 private final String fingerprint;
51
52 public XmppAxolotlPlaintextMessage(String plaintext, String fingerprint) {
53 this.plaintext = plaintext;
54 this.fingerprint = fingerprint;
55 }
56
57 public String getPlaintext() {
58 return plaintext;
59 }
60
61
62 public String getFingerprint() {
63 return fingerprint;
64 }
65 }
66
67 public static class XmppAxolotlKeyTransportMessage {
68 private final String fingerprint;
69 private final byte[] key;
70 private final byte[] iv;
71
72 public XmppAxolotlKeyTransportMessage(String fingerprint, byte[] key, byte[] iv) {
73 this.fingerprint = fingerprint;
74 this.key = key;
75 this.iv = iv;
76 }
77
78 public String getFingerprint() {
79 return fingerprint;
80 }
81
82 public byte[] getKey() {
83 return key;
84 }
85
86 public byte[] getIv() {
87 return iv;
88 }
89 }
90
91 private XmppAxolotlMessage(final Element axolotlMessage, final Jid from) throws IllegalArgumentException {
92 this.from = from;
93 Element header = axolotlMessage.findChild(HEADER);
94 this.sourceDeviceId = Integer.parseInt(header.getAttribute(SOURCEID));
95 List<Element> keyElements = header.getChildren();
96 this.keys = new HashMap<>(keyElements.size());
97 for (Element keyElement : keyElements) {
98 switch (keyElement.getName()) {
99 case KEYTAG:
100 try {
101 Integer recipientId = Integer.parseInt(keyElement.getAttribute(REMOTEID));
102 byte[] key = Base64.decode(keyElement.getContent(), Base64.DEFAULT);
103 this.keys.put(recipientId, key);
104 } catch (NumberFormatException e) {
105 throw new IllegalArgumentException(e);
106 }
107 break;
108 case IVTAG:
109 if (this.iv != null) {
110 throw new IllegalArgumentException("Duplicate iv entry");
111 }
112 iv = Base64.decode(keyElement.getContent(), Base64.DEFAULT);
113 break;
114 default:
115 Log.w(Config.LOGTAG, "Unexpected element in header: " + keyElement.toString());
116 break;
117 }
118 }
119 Element payloadElement = axolotlMessage.findChild(PAYLOAD);
120 if (payloadElement != null) {
121 ciphertext = Base64.decode(payloadElement.getContent(), Base64.DEFAULT);
122 }
123 }
124
125 public XmppAxolotlMessage(Jid from, int sourceDeviceId) {
126 this.from = from;
127 this.sourceDeviceId = sourceDeviceId;
128 this.keys = new HashMap<>();
129 this.iv = generateIv();
130 this.innerKey = generateKey();
131 }
132
133 public static XmppAxolotlMessage fromElement(Element element, Jid from) {
134 return new XmppAxolotlMessage(element, from);
135 }
136
137 private static byte[] generateKey() {
138 try {
139 KeyGenerator generator = KeyGenerator.getInstance(KEYTYPE);
140 generator.init(128);
141 return generator.generateKey().getEncoded();
142 } catch (NoSuchAlgorithmException e) {
143 Log.e(Config.LOGTAG, e.getMessage());
144 return null;
145 }
146 }
147
148 private static byte[] generateIv() {
149 SecureRandom random = new SecureRandom();
150 byte[] iv = new byte[16];
151 random.nextBytes(iv);
152 return iv;
153 }
154
155 public void encrypt(String plaintext) throws CryptoFailedException {
156 try {
157 SecretKey secretKey = new SecretKeySpec(innerKey, KEYTYPE);
158 IvParameterSpec ivSpec = new IvParameterSpec(iv);
159 Cipher cipher = Cipher.getInstance(CIPHERMODE, PROVIDER);
160 cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
161 this.ciphertext = cipher.doFinal(plaintext.getBytes());
162 } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
163 | IllegalBlockSizeException | BadPaddingException | NoSuchProviderException
164 | InvalidAlgorithmParameterException e) {
165 throw new CryptoFailedException(e);
166 }
167 }
168
169 public Jid getFrom() {
170 return this.from;
171 }
172
173 public int getSenderDeviceId() {
174 return sourceDeviceId;
175 }
176
177 public byte[] getCiphertext() {
178 return ciphertext;
179 }
180
181 public void addDevice(XmppAxolotlSession session) {
182 byte[] key = session.processSending(innerKey);
183 if (key != null) {
184 keys.put(session.getRemoteAddress().getDeviceId(), key);
185 }
186 }
187
188 public byte[] getInnerKey() {
189 return innerKey;
190 }
191
192 public byte[] getIV() {
193 return this.iv;
194 }
195
196 public Element toElement() {
197 Element encryptionElement = new Element(CONTAINERTAG, AxolotlService.PEP_PREFIX);
198 Element headerElement = encryptionElement.addChild(HEADER);
199 headerElement.setAttribute(SOURCEID, sourceDeviceId);
200 for (Map.Entry<Integer, byte[]> keyEntry : keys.entrySet()) {
201 Element keyElement = new Element(KEYTAG);
202 keyElement.setAttribute(REMOTEID, keyEntry.getKey());
203 keyElement.setContent(Base64.encodeToString(keyEntry.getValue(), Base64.DEFAULT));
204 headerElement.addChild(keyElement);
205 }
206 headerElement.addChild(IVTAG).setContent(Base64.encodeToString(iv, Base64.DEFAULT));
207 if (ciphertext != null) {
208 Element payload = encryptionElement.addChild(PAYLOAD);
209 payload.setContent(Base64.encodeToString(ciphertext, Base64.DEFAULT));
210 }
211 return encryptionElement;
212 }
213
214 private byte[] unpackKey(XmppAxolotlSession session, Integer sourceDeviceId) {
215 byte[] encryptedKey = keys.get(sourceDeviceId);
216 return (encryptedKey != null) ? session.processReceiving(encryptedKey) : null;
217 }
218
219 public XmppAxolotlKeyTransportMessage getParameters(XmppAxolotlSession session, Integer sourceDeviceId) {
220 byte[] key = unpackKey(session, sourceDeviceId);
221 return (key != null)
222 ? new XmppAxolotlKeyTransportMessage(session.getFingerprint(), key, getIV())
223 : null;
224 }
225
226 public XmppAxolotlPlaintextMessage decrypt(XmppAxolotlSession session, Integer sourceDeviceId) throws CryptoFailedException {
227 XmppAxolotlPlaintextMessage plaintextMessage = null;
228 byte[] key = unpackKey(session, sourceDeviceId);
229 if (key != null) {
230 try {
231 Cipher cipher = Cipher.getInstance(CIPHERMODE, PROVIDER);
232 SecretKeySpec keySpec = new SecretKeySpec(key, KEYTYPE);
233 IvParameterSpec ivSpec = new IvParameterSpec(iv);
234
235 cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
236
237 String plaintext = new String(cipher.doFinal(ciphertext));
238 plaintextMessage = new XmppAxolotlPlaintextMessage(plaintext, session.getFingerprint());
239
240 } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
241 | InvalidAlgorithmParameterException | IllegalBlockSizeException
242 | BadPaddingException | NoSuchProviderException e) {
243 throw new CryptoFailedException(e);
244 }
245 }
246 return plaintextMessage;
247 }
248}