XmppAxolotlMessage.java

  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.innerKey = secretKey.getEncoded();
162			this.ciphertext = cipher.doFinal(plaintext.getBytes());
163		} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
164				| IllegalBlockSizeException | BadPaddingException | NoSuchProviderException
165				| InvalidAlgorithmParameterException e) {
166			throw new CryptoFailedException(e);
167		}
168	}
169
170	public Jid getFrom() {
171		return this.from;
172	}
173
174	public int getSenderDeviceId() {
175		return sourceDeviceId;
176	}
177
178	public byte[] getCiphertext() {
179		return ciphertext;
180	}
181
182	public void addDevice(XmppAxolotlSession session) {
183		byte[] key = session.processSending(innerKey);
184		if (key != null) {
185			keys.put(session.getRemoteAddress().getDeviceId(), key);
186		}
187	}
188
189	public byte[] getInnerKey() {
190		return innerKey;
191	}
192
193	public byte[] getIV() {
194		return this.iv;
195	}
196
197	public Element toElement() {
198		Element encryptionElement = new Element(CONTAINERTAG, AxolotlService.PEP_PREFIX);
199		Element headerElement = encryptionElement.addChild(HEADER);
200		headerElement.setAttribute(SOURCEID, sourceDeviceId);
201		for (Map.Entry<Integer, byte[]> keyEntry : keys.entrySet()) {
202			Element keyElement = new Element(KEYTAG);
203			keyElement.setAttribute(REMOTEID, keyEntry.getKey());
204			keyElement.setContent(Base64.encodeToString(keyEntry.getValue(), Base64.DEFAULT));
205			headerElement.addChild(keyElement);
206		}
207		headerElement.addChild(IVTAG).setContent(Base64.encodeToString(iv, Base64.DEFAULT));
208		if (ciphertext != null) {
209			Element payload = encryptionElement.addChild(PAYLOAD);
210			payload.setContent(Base64.encodeToString(ciphertext, Base64.DEFAULT));
211		}
212		return encryptionElement;
213	}
214
215	private byte[] unpackKey(XmppAxolotlSession session, Integer sourceDeviceId) {
216		byte[] encryptedKey = keys.get(sourceDeviceId);
217		return (encryptedKey != null) ? session.processReceiving(encryptedKey) : null;
218	}
219
220	public XmppAxolotlKeyTransportMessage getParameters(XmppAxolotlSession session, Integer sourceDeviceId) {
221		byte[] key = unpackKey(session, sourceDeviceId);
222		return (key != null)
223				? new XmppAxolotlKeyTransportMessage(session.getFingerprint(), key, getIV())
224				: null;
225	}
226
227	public XmppAxolotlPlaintextMessage decrypt(XmppAxolotlSession session, Integer sourceDeviceId) throws CryptoFailedException {
228		XmppAxolotlPlaintextMessage plaintextMessage = null;
229		byte[] key = unpackKey(session, sourceDeviceId);
230		if (key != null) {
231			try {
232				Cipher cipher = Cipher.getInstance(CIPHERMODE, PROVIDER);
233				SecretKeySpec keySpec = new SecretKeySpec(key, KEYTYPE);
234				IvParameterSpec ivSpec = new IvParameterSpec(iv);
235
236				cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
237
238				String plaintext = new String(cipher.doFinal(ciphertext));
239				plaintextMessage = new XmppAxolotlPlaintextMessage(plaintext, session.getFingerprint());
240
241			} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
242					| InvalidAlgorithmParameterException | IllegalBlockSizeException
243					| BadPaddingException | NoSuchProviderException e) {
244				throw new CryptoFailedException(e);
245			}
246		}
247		return plaintextMessage;
248	}
249}