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 try {
95 this.sourceDeviceId = Integer.parseInt(header.getAttribute(SOURCEID));
96 } catch (NumberFormatException e) {
97 throw new IllegalArgumentException("invalid source id");
98 }
99 List<Element> keyElements = header.getChildren();
100 this.keys = new HashMap<>(keyElements.size());
101 for (Element keyElement : keyElements) {
102 switch (keyElement.getName()) {
103 case KEYTAG:
104 try {
105 Integer recipientId = Integer.parseInt(keyElement.getAttribute(REMOTEID));
106 byte[] key = Base64.decode(keyElement.getContent().trim(), Base64.DEFAULT);
107 this.keys.put(recipientId, key);
108 } catch (NumberFormatException e) {
109 throw new IllegalArgumentException("invalid remote id");
110 }
111 break;
112 case IVTAG:
113 if (this.iv != null) {
114 throw new IllegalArgumentException("Duplicate iv entry");
115 }
116 iv = Base64.decode(keyElement.getContent().trim(), Base64.DEFAULT);
117 break;
118 default:
119 Log.w(Config.LOGTAG, "Unexpected element in header: " + keyElement.toString());
120 break;
121 }
122 }
123 Element payloadElement = axolotlMessage.findChild(PAYLOAD);
124 if (payloadElement != null) {
125 ciphertext = Base64.decode(payloadElement.getContent().trim(), Base64.DEFAULT);
126 }
127 }
128
129 public XmppAxolotlMessage(Jid from, int sourceDeviceId) {
130 this.from = from;
131 this.sourceDeviceId = sourceDeviceId;
132 this.keys = new HashMap<>();
133 this.iv = generateIv();
134 this.innerKey = generateKey();
135 }
136
137 public static XmppAxolotlMessage fromElement(Element element, Jid from) {
138 return new XmppAxolotlMessage(element, from);
139 }
140
141 private static byte[] generateKey() {
142 try {
143 KeyGenerator generator = KeyGenerator.getInstance(KEYTYPE);
144 generator.init(128);
145 return generator.generateKey().getEncoded();
146 } catch (NoSuchAlgorithmException e) {
147 Log.e(Config.LOGTAG, e.getMessage());
148 return null;
149 }
150 }
151
152 private static byte[] generateIv() {
153 SecureRandom random = new SecureRandom();
154 byte[] iv = new byte[16];
155 random.nextBytes(iv);
156 return iv;
157 }
158
159 public void encrypt(String plaintext) throws CryptoFailedException {
160 try {
161 SecretKey secretKey = new SecretKeySpec(innerKey, KEYTYPE);
162 IvParameterSpec ivSpec = new IvParameterSpec(iv);
163 Cipher cipher = Cipher.getInstance(CIPHERMODE, PROVIDER);
164 cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
165 this.ciphertext = cipher.doFinal(plaintext.getBytes());
166 } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
167 | IllegalBlockSizeException | BadPaddingException | NoSuchProviderException
168 | InvalidAlgorithmParameterException e) {
169 throw new CryptoFailedException(e);
170 }
171 }
172
173 public Jid getFrom() {
174 return this.from;
175 }
176
177 public int getSenderDeviceId() {
178 return sourceDeviceId;
179 }
180
181 public byte[] getCiphertext() {
182 return ciphertext;
183 }
184
185 public void addDevice(XmppAxolotlSession session) {
186 byte[] key = session.processSending(innerKey);
187 if (key != null) {
188 keys.put(session.getRemoteAddress().getDeviceId(), key);
189 }
190 }
191
192 public byte[] getInnerKey() {
193 return innerKey;
194 }
195
196 public byte[] getIV() {
197 return this.iv;
198 }
199
200 public Element toElement() {
201 Element encryptionElement = new Element(CONTAINERTAG, AxolotlService.PEP_PREFIX);
202 Element headerElement = encryptionElement.addChild(HEADER);
203 headerElement.setAttribute(SOURCEID, sourceDeviceId);
204 for (Map.Entry<Integer, byte[]> keyEntry : keys.entrySet()) {
205 Element keyElement = new Element(KEYTAG);
206 keyElement.setAttribute(REMOTEID, keyEntry.getKey());
207 keyElement.setContent(Base64.encodeToString(keyEntry.getValue(), Base64.NO_WRAP));
208 headerElement.addChild(keyElement);
209 }
210 headerElement.addChild(IVTAG).setContent(Base64.encodeToString(iv, Base64.NO_WRAP));
211 if (ciphertext != null) {
212 Element payload = encryptionElement.addChild(PAYLOAD);
213 payload.setContent(Base64.encodeToString(ciphertext, Base64.NO_WRAP));
214 }
215 return encryptionElement;
216 }
217
218 private byte[] unpackKey(XmppAxolotlSession session, Integer sourceDeviceId) {
219 byte[] encryptedKey = keys.get(sourceDeviceId);
220 return (encryptedKey != null) ? session.processReceiving(encryptedKey) : null;
221 }
222
223 public XmppAxolotlKeyTransportMessage getParameters(XmppAxolotlSession session, Integer sourceDeviceId) {
224 byte[] key = unpackKey(session, sourceDeviceId);
225 return (key != null)
226 ? new XmppAxolotlKeyTransportMessage(session.getFingerprint(), key, getIV())
227 : null;
228 }
229
230 public XmppAxolotlPlaintextMessage decrypt(XmppAxolotlSession session, Integer sourceDeviceId) throws CryptoFailedException {
231 XmppAxolotlPlaintextMessage plaintextMessage = null;
232 byte[] key = unpackKey(session, sourceDeviceId);
233 if (key != null) {
234 try {
235 Cipher cipher = Cipher.getInstance(CIPHERMODE, PROVIDER);
236 SecretKeySpec keySpec = new SecretKeySpec(key, KEYTYPE);
237 IvParameterSpec ivSpec = new IvParameterSpec(iv);
238
239 cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
240
241 String plaintext = new String(cipher.doFinal(ciphertext));
242 plaintextMessage = new XmppAxolotlPlaintextMessage(plaintext, session.getFingerprint());
243
244 } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
245 | InvalidAlgorithmParameterException | IllegalBlockSizeException
246 | BadPaddingException | NoSuchProviderException e) {
247 throw new CryptoFailedException(e);
248 }
249 }
250 return plaintextMessage;
251 }
252}