PgpEngine.java

  1package eu.siacs.conversations.crypto;
  2
  3import java.io.ByteArrayInputStream;
  4import java.io.ByteArrayOutputStream;
  5import java.io.FileInputStream;
  6import java.io.FileNotFoundException;
  7import java.io.FileOutputStream;
  8import java.io.IOException;
  9import java.io.InputStream;
 10import java.io.OutputStream;
 11
 12import org.openintents.openpgp.OpenPgpError;
 13import org.openintents.openpgp.OpenPgpSignatureResult;
 14import org.openintents.openpgp.util.OpenPgpApi;
 15import org.openintents.openpgp.util.OpenPgpApi.IOpenPgpCallback;
 16
 17import eu.siacs.conversations.Config;
 18import eu.siacs.conversations.R;
 19import eu.siacs.conversations.entities.Account;
 20import eu.siacs.conversations.entities.Contact;
 21import eu.siacs.conversations.entities.Conversation;
 22import eu.siacs.conversations.entities.Message;
 23import eu.siacs.conversations.services.XmppConnectionService;
 24import eu.siacs.conversations.ui.UiCallback;
 25import eu.siacs.conversations.xmpp.jingle.JingleFile;
 26import android.app.PendingIntent;
 27import android.content.Intent;
 28import android.graphics.BitmapFactory;
 29import android.util.Log;
 30
 31public class PgpEngine {
 32	private OpenPgpApi api;
 33	private XmppConnectionService mXmppConnectionService;
 34
 35	public PgpEngine(OpenPgpApi api, XmppConnectionService service) {
 36		this.api = api;
 37		this.mXmppConnectionService = service;
 38	}
 39
 40	public void decrypt(final Message message,
 41			final UiCallback<Message> callback) {
 42		Log.d(Config.LOGTAG, "decrypting message " + message.getUuid());
 43		Intent params = new Intent();
 44		params.setAction(OpenPgpApi.ACTION_DECRYPT_VERIFY);
 45		params.putExtra(OpenPgpApi.EXTRA_ACCOUNT_NAME, message
 46				.getConversation().getAccount().getJid());
 47		if (message.getType() == Message.TYPE_TEXT) {
 48			InputStream is = new ByteArrayInputStream(message.getBody()
 49					.getBytes());
 50			final OutputStream os = new ByteArrayOutputStream();
 51			api.executeApiAsync(params, is, os, new IOpenPgpCallback() {
 52
 53				@Override
 54				public void onReturn(Intent result) {
 55					switch (result.getIntExtra(OpenPgpApi.RESULT_CODE,
 56							OpenPgpApi.RESULT_CODE_ERROR)) {
 57					case OpenPgpApi.RESULT_CODE_SUCCESS:
 58						try {
 59							os.flush();
 60							if (message.getEncryption() == Message.ENCRYPTION_PGP) {
 61								message.setBody(os.toString());
 62								message.setEncryption(Message.ENCRYPTION_DECRYPTED);
 63								callback.success(message);
 64							}
 65						} catch (IOException e) {
 66							callback.error(R.string.openpgp_error, message);
 67							return;
 68						}
 69
 70						return;
 71					case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED:
 72						callback.userInputRequried((PendingIntent) result
 73								.getParcelableExtra(OpenPgpApi.RESULT_INTENT),
 74								message);
 75						return;
 76					case OpenPgpApi.RESULT_CODE_ERROR:
 77						OpenPgpError error = result
 78								.getParcelableExtra(OpenPgpApi.RESULT_ERROR);
 79						Log.d(Config.LOGTAG, error.getMessage());
 80						callback.error(R.string.openpgp_error, message);
 81						return;
 82					default:
 83						return;
 84					}
 85				}
 86			});
 87		} else if (message.getType() == Message.TYPE_IMAGE) {
 88			try {
 89				final JingleFile inputFile = this.mXmppConnectionService
 90						.getFileBackend().getJingleFile(message, false);
 91				final JingleFile outputFile = this.mXmppConnectionService
 92						.getFileBackend().getJingleFile(message, true);
 93				outputFile.createNewFile();
 94				InputStream is = new FileInputStream(inputFile);
 95				OutputStream os = new FileOutputStream(outputFile);
 96				api.executeApiAsync(params, is, os, new IOpenPgpCallback() {
 97
 98					@Override
 99					public void onReturn(Intent result) {
100						switch (result.getIntExtra(OpenPgpApi.RESULT_CODE,
101								OpenPgpApi.RESULT_CODE_ERROR)) {
102						case OpenPgpApi.RESULT_CODE_SUCCESS:
103							BitmapFactory.Options options = new BitmapFactory.Options();
104							options.inJustDecodeBounds = true;
105							BitmapFactory.decodeFile(
106									outputFile.getAbsolutePath(), options);
107							int imageHeight = options.outHeight;
108							int imageWidth = options.outWidth;
109							message.setBody("" + outputFile.getSize() + ","
110									+ imageWidth + "," + imageHeight);
111							message.setEncryption(Message.ENCRYPTION_DECRYPTED);
112							PgpEngine.this.mXmppConnectionService
113									.updateMessage(message);
114							PgpEngine.this.mXmppConnectionService
115									.updateConversationUi();
116							callback.success(message);
117							return;
118						case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED:
119							callback.userInputRequried(
120									(PendingIntent) result
121											.getParcelableExtra(OpenPgpApi.RESULT_INTENT),
122									message);
123							return;
124						case OpenPgpApi.RESULT_CODE_ERROR:
125							callback.error(R.string.openpgp_error, message);
126							return;
127						default:
128							return;
129						}
130					}
131				});
132			} catch (FileNotFoundException e) {
133				callback.error(R.string.error_decrypting_file, message);
134			} catch (IOException e) {
135				callback.error(R.string.error_decrypting_file, message);
136			}
137
138		}
139	}
140
141	public void encrypt(final Message message,
142			final UiCallback<Message> callback) {
143
144		Intent params = new Intent();
145		params.setAction(OpenPgpApi.ACTION_ENCRYPT);
146		if (message.getConversation().getMode() == Conversation.MODE_SINGLE) {
147			long[] keys = { message.getConversation().getContact()
148					.getPgpKeyId() };
149			params.putExtra(OpenPgpApi.EXTRA_KEY_IDS, keys);
150		} else {
151			params.putExtra(OpenPgpApi.EXTRA_KEY_IDS, message.getConversation()
152					.getMucOptions().getPgpKeyIds());
153		}
154		params.putExtra(OpenPgpApi.EXTRA_ACCOUNT_NAME, message
155				.getConversation().getAccount().getJid());
156
157		if (message.getType() == Message.TYPE_TEXT) {
158			params.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true);
159
160			InputStream is = new ByteArrayInputStream(message.getBody()
161					.getBytes());
162			final OutputStream os = new ByteArrayOutputStream();
163			api.executeApiAsync(params, is, os, new IOpenPgpCallback() {
164
165				@Override
166				public void onReturn(Intent result) {
167					switch (result.getIntExtra(OpenPgpApi.RESULT_CODE,
168							OpenPgpApi.RESULT_CODE_ERROR)) {
169					case OpenPgpApi.RESULT_CODE_SUCCESS:
170						try {
171							os.flush();
172							StringBuilder encryptedMessageBody = new StringBuilder();
173							String[] lines = os.toString().split("\n");
174							for (int i = 3; i < lines.length - 1; ++i) {
175								encryptedMessageBody.append(lines[i].trim());
176							}
177							message.setEncryptedBody(encryptedMessageBody
178									.toString());
179							callback.success(message);
180						} catch (IOException e) {
181							callback.error(R.string.openpgp_error, message);
182						}
183
184						break;
185					case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED:
186						callback.userInputRequried((PendingIntent) result
187								.getParcelableExtra(OpenPgpApi.RESULT_INTENT),
188								message);
189						break;
190					case OpenPgpApi.RESULT_CODE_ERROR:
191						callback.error(R.string.openpgp_error, message);
192						break;
193					}
194				}
195			});
196		} else if (message.getType() == Message.TYPE_IMAGE) {
197			try {
198				JingleFile inputFile = this.mXmppConnectionService
199						.getFileBackend().getJingleFile(message, true);
200				JingleFile outputFile = this.mXmppConnectionService
201						.getFileBackend().getJingleFile(message, false);
202				outputFile.createNewFile();
203				InputStream is = new FileInputStream(inputFile);
204				OutputStream os = new FileOutputStream(outputFile);
205				api.executeApiAsync(params, is, os, new IOpenPgpCallback() {
206
207					@Override
208					public void onReturn(Intent result) {
209						switch (result.getIntExtra(OpenPgpApi.RESULT_CODE,
210								OpenPgpApi.RESULT_CODE_ERROR)) {
211						case OpenPgpApi.RESULT_CODE_SUCCESS:
212							callback.success(message);
213							break;
214						case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED:
215							callback.userInputRequried(
216									(PendingIntent) result
217											.getParcelableExtra(OpenPgpApi.RESULT_INTENT),
218									message);
219							break;
220						case OpenPgpApi.RESULT_CODE_ERROR:
221							callback.error(R.string.openpgp_error, message);
222							break;
223						}
224					}
225				});
226			} catch (FileNotFoundException e) {
227				Log.d(Config.LOGTAG, "file not found: " + e.getMessage());
228			} catch (IOException e) {
229				Log.d(Config.LOGTAG, "io exception during file encrypt");
230			}
231		}
232	}
233
234	public long fetchKeyId(Account account, String status, String signature) {
235		if ((signature == null) || (api == null)) {
236			return 0;
237		}
238		if (status == null) {
239			status = "";
240		}
241		StringBuilder pgpSig = new StringBuilder();
242		pgpSig.append("-----BEGIN PGP SIGNED MESSAGE-----");
243		pgpSig.append('\n');
244		pgpSig.append('\n');
245		pgpSig.append(status);
246		pgpSig.append('\n');
247		pgpSig.append("-----BEGIN PGP SIGNATURE-----");
248		pgpSig.append('\n');
249		pgpSig.append('\n');
250		pgpSig.append(signature.replace("\n", "").trim());
251		pgpSig.append('\n');
252		pgpSig.append("-----END PGP SIGNATURE-----");
253		Intent params = new Intent();
254		params.setAction(OpenPgpApi.ACTION_DECRYPT_VERIFY);
255		params.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true);
256		params.putExtra(OpenPgpApi.EXTRA_ACCOUNT_NAME, account.getJid());
257		InputStream is = new ByteArrayInputStream(pgpSig.toString().getBytes());
258		ByteArrayOutputStream os = new ByteArrayOutputStream();
259		Intent result = api.executeApi(params, is, os);
260		switch (result.getIntExtra(OpenPgpApi.RESULT_CODE,
261				OpenPgpApi.RESULT_CODE_ERROR)) {
262		case OpenPgpApi.RESULT_CODE_SUCCESS:
263			OpenPgpSignatureResult sigResult = result
264					.getParcelableExtra(OpenPgpApi.RESULT_SIGNATURE);
265			if (sigResult != null) {
266				return sigResult.getKeyId();
267			} else {
268				return 0;
269			}
270		case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED:
271			return 0;
272		case OpenPgpApi.RESULT_CODE_ERROR:
273			Log.d(Config.LOGTAG,
274					"openpgp error: "
275							+ ((OpenPgpError) result
276									.getParcelableExtra(OpenPgpApi.RESULT_ERROR))
277									.getMessage());
278			return 0;
279		}
280		return 0;
281	}
282
283	public void generateSignature(final Account account, String status,
284			final UiCallback<Account> callback) {
285		Intent params = new Intent();
286		params.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true);
287		params.setAction(OpenPgpApi.ACTION_SIGN);
288		params.putExtra(OpenPgpApi.EXTRA_ACCOUNT_NAME, account.getJid());
289		InputStream is = new ByteArrayInputStream(status.getBytes());
290		final OutputStream os = new ByteArrayOutputStream();
291		api.executeApiAsync(params, is, os, new IOpenPgpCallback() {
292
293			@Override
294			public void onReturn(Intent result) {
295				switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, 0)) {
296				case OpenPgpApi.RESULT_CODE_SUCCESS:
297					StringBuilder signatureBuilder = new StringBuilder();
298					String[] lines = os.toString().split("\n");
299					for (int i = 7; i < lines.length - 1; ++i) {
300						signatureBuilder.append(lines[i].trim());
301					}
302					account.setKey("pgp_signature", signatureBuilder.toString());
303					callback.success(account);
304					return;
305				case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED:
306					callback.userInputRequried((PendingIntent) result
307							.getParcelableExtra(OpenPgpApi.RESULT_INTENT),
308							account);
309					return;
310				case OpenPgpApi.RESULT_CODE_ERROR:
311					callback.error(R.string.openpgp_error, account);
312					return;
313				}
314			}
315		});
316	}
317
318	public void hasKey(final Contact contact, final UiCallback<Contact> callback) {
319		Intent params = new Intent();
320		params.setAction(OpenPgpApi.ACTION_GET_KEY);
321		params.putExtra(OpenPgpApi.EXTRA_KEY_ID, contact.getPgpKeyId());
322		params.putExtra(OpenPgpApi.EXTRA_ACCOUNT_NAME, contact.getAccount()
323				.getJid());
324		api.executeApiAsync(params, null, null, new IOpenPgpCallback() {
325
326			@Override
327			public void onReturn(Intent result) {
328				switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, 0)) {
329				case OpenPgpApi.RESULT_CODE_SUCCESS:
330					callback.success(contact);
331					return;
332				case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED:
333					callback.userInputRequried((PendingIntent) result
334							.getParcelableExtra(OpenPgpApi.RESULT_INTENT),
335							contact);
336					return;
337				case OpenPgpApi.RESULT_CODE_ERROR:
338					callback.error(R.string.openpgp_error, contact);
339					return;
340				}
341			}
342		});
343	}
344
345	public PendingIntent getIntentForKey(Contact contact) {
346		Intent params = new Intent();
347		params.setAction(OpenPgpApi.ACTION_GET_KEY);
348		params.putExtra(OpenPgpApi.EXTRA_KEY_ID, contact.getPgpKeyId());
349		params.putExtra(OpenPgpApi.EXTRA_ACCOUNT_NAME, contact.getAccount()
350				.getJid());
351		Intent result = api.executeApi(params, null, null);
352		return (PendingIntent) result
353				.getParcelableExtra(OpenPgpApi.RESULT_INTENT);
354	}
355
356	public PendingIntent getIntentForKey(Account account, long pgpKeyId) {
357		Intent params = new Intent();
358		params.setAction(OpenPgpApi.ACTION_GET_KEY);
359		params.putExtra(OpenPgpApi.EXTRA_KEY_ID, pgpKeyId);
360		params.putExtra(OpenPgpApi.EXTRA_ACCOUNT_NAME, account.getJid());
361		Intent result = api.executeApi(params, null, null);
362		return (PendingIntent) result
363				.getParcelableExtra(OpenPgpApi.RESULT_INTENT);
364	}
365}