diff --git a/k9mail/build.gradle b/k9mail/build.gradle index ebbb379c5..4c17376aa 100644 --- a/k9mail/build.gradle +++ b/k9mail/build.gradle @@ -23,12 +23,12 @@ dependencies { compile project(':k9mail-library') compile project(':plugins:Android-PullToRefresh:library') compile project(':plugins:HoloColorPicker') + compile project(':plugins:openpgp-api-lib:openpgp-api') compile 'commons-io:commons-io:2.4' compile "com.android.support:support-v4:${project.supportLibraryVersion}" compile 'net.sourceforge.htmlcleaner:htmlcleaner:2.16' compile 'de.cketti.library.changelog:ckchangelog:1.2.1' compile 'com.github.bumptech.glide:glide:3.6.1' - compile 'org.sufficientlysecure:openpgp-api:8.0' compile 'com.splitwise:tokenautocomplete:2.0.2' androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1' diff --git a/plugins/openpgp-api-lib/.gitignore b/plugins/openpgp-api-lib/.gitignore new file mode 100644 index 000000000..a44cc0f0f --- /dev/null +++ b/plugins/openpgp-api-lib/.gitignore @@ -0,0 +1,33 @@ +#Android specific +bin +gen +obj +lint.xml +local.properties +release.properties +ant.properties +*.class +*.apk + +#Gradle +.gradle +build +gradle.properties + +#Maven +target +pom.xml.* + +#Eclipse +.project +.classpath +.settings +.metadata + +#IntelliJ IDEA +.idea +*.iml + +#Lint output +lint-report.html +lint-report_files/* \ No newline at end of file diff --git a/plugins/openpgp-api-lib/.tx/config b/plugins/openpgp-api-lib/.tx/config new file mode 100644 index 000000000..ab194a8a1 --- /dev/null +++ b/plugins/openpgp-api-lib/.tx/config @@ -0,0 +1,8 @@ +[main] +host = https://www.transifex.com +lang_map = af_ZA: af-rZA, am_ET: am-rET, ar_AE: ar-rAE, ar_BH: ar-rBH, ar_DZ: ar-rDZ, ar_EG: ar-rEG, ar_IQ: ar-rIQ, ar_JO: ar-rJO, ar_KW: ar-rKW, ar_LB: ar-rLB, ar_LY: ar-rLY, ar_MA: ar-rMA, ar_OM: ar-rOM, ar_QA: ar-rQA, ar_SA: ar-rSA, ar_SY: ar-rSY, ar_TN: ar-rTN, ar_YE: ar-rYE, arn_CL: arn-rCL, as_IN: as-rIN, az_AZ: az-rAZ, ba_RU: ba-rRU, be_BY: be-rBY, bg_BG: bg-rBG, bn_BD: bn-rBD, bn_IN: bn-rIN, bo_CN: bo-rCN, br_FR: br-rFR, bs_BA: bs-rBA, ca_ES: ca-rES, co_FR: co-rFR, cs_CZ: cs-rCZ, cy_GB: cy-rGB, da_DK: da-rDK, de_AT: de-rAT, de_CH: de-rCH, de_DE: de-rDE, de_LI: de-rLI, de_LU: de-rLU, dsb_DE: dsb-rDE, dv_MV: dv-rMV, el_GR: el-rGR, en_AU: en-rAU, en_BZ: en-rBZ, en_CA: en-rCA, en_GB: en-rGB, en_IE: en-rIE, en_IN: en-rIN, en_JM: en-rJM, en_MY: en-rMY, en_NZ: en-rNZ, en_PH: en-rPH, en_SG: en-rSG, en_TT: en-rTT, en_US: en-rUS, en_ZA: en-rZA, en_ZW: en-rZW, es_AR: es-rAR, es_BO: es-rBO, es_CL: es-rCL, es_CO: es-rCO, es_CR: es-rCR, es_DO: es-rDO, es_EC: es-rEC, es_ES: es-rES, es_GT: es-rGT, es_HN: es-rHN, es_MX: es-rMX, es_NI: es-rNI, es_PA: es-rPA, es_PE: es-rPE, es_PR: es-rPR, es_PY: es-rPY, es_SV: es-rSV, es_US: es-rUS, es_UY: es-rUY, es_VE: es-rVE, et_EE: et-rEE, eu_ES: eu-rES, fa_IR: fa-rIR, fi_FI: fi-rFI, fil_PH: fil-rPH, fo_FO: fo-rFO, fr_BE: fr-rBE, fr_CA: fr-rCA, fr_CH: fr-rCH, fr_FR: fr-rFR, fr_LU: fr-rLU, fr_MC: fr-rMC, fy_NL: fy-rNL, ga_IE: ga-rIE, gd_GB: gd-rGB, gl_ES: gl-rES, gsw_FR: gsw-rFR, gu_IN: gu-rIN, ha_NG: ha-rNG, hi_IN: hi-rIN, hr_BA: hr-rBA, hr_HR: hr-rHR, hsb_DE: hsb-rDE, hu_HU: hu-rHU, hy_AM: hy-rAM, id_ID: id-rID, ig_NG: ig-rNG, ii_CN: ii-rCN, is_IS: is-rIS, it_CH: it-rCH, it_IT: it-rIT, iu_CA: iu-rCA, ja_JP: ja-rJP, ka_GE: ka-rGE, kk_KZ: kk-rKZ, kl_GL: kl-rGL, km_KH: km-rKH, kn_IN: kn-rIN, ko_KR: ko-rKR, kok_IN: kok-rIN, ky_KG: ky-rKG, lb_LU: lb-rLU, lo_LA: lo-rLA, lt_LT: lt-rLT, lv_LV: lv-rLV, mi_NZ: mi-rNZ, mk_MK: mk-rMK, ml_IN: ml-rIN, mn_CN: mn-rCN, mn_MN: mn-rMN, moh_CA: moh-rCA, mr_IN: mr-rIN, ms_BN: ms-rBN, ms_MY: ms-rMY, mt_MT: mt-rMT, nb_NO: nb-rNO, ne_NP: ne-rNP, nl_BE: nl-rBE, nl_NL: nl-rNL, nn_NO: nn-rNO, nso_ZA: nso-rZA, oc_FR: oc-rFR, or_IN: or-rIN, pa_IN: pa-rIN, pl_PL: pl-rPL, prs_AF: prs-rAF, ps_AF: ps-rAF, pt_BR: pt-rBR, pt_PT: pt-rPT, qut_GT: qut-rGT, quz_BO: quz-rBO, quz_EC: quz-rEC, quz_PE: quz-rPE, rm_CH: rm-rCH, ro_RO: ro-rRO, ru_RU: ru-rRU, rw_RW: rw-rRW, sa_IN: sa-rIN, sah_RU: sah-rRU, se_FI: se-rFI, se_NO: se-rNO, se_SE: se-rSE, si_LK: si-rLK, sk_SK: sk-rSK, sl_SI: sl-rSI, sma_NO: sma-rNO, sma_SE: sma-rSE, smj_NO: smj-rNO, smj_SE: smj-rSE, smn_FI: smn-rFI, sms_FI: sms-rFI, sq_AL: sq-rAL, sr_BA: sr-rBA, sr_CS: sr-rCS, sr_ME: sr-rME, sr_RS: sr-rRS, sv_FI: sv-rFI, sv_SE: sv-rSE, sw_KE: sw-rKE, syr_SY: syr-rSY, ta_IN: ta-rIN, te_IN: te-rIN, tg_TJ: tg-rTJ, th_TH: th-rTH, tk_TM: tk-rTM, tn_ZA: tn-rZA, tr_TR: tr-rTR, tt_RU: tt-rRU, tzm_DZ: tzm-rDZ, ug_CN: ug-rCN, uk_UA: uk-rUA, ur_PK: ur-rPK, uz_UZ: uz-rUZ, vi_VN: vi-rVN, wo_SN: wo-rSN, xh_ZA: xh-rZA, yo_NG: yo-rNG, zh_CN: zh-rCN, zh_HK: zh-rHK, zh_MO: zh-rMO, zh_SG: zh-rSG, zh_TW: zh-rTW, zu_ZA: zu-rZA, no_NO: no-rNO, he_IL: iw-rIL, he: iw + +[open-keychain.api-strings] +file_filter = openpgp-api/src/main/res/values-/strings.xml +source_file = openpgp-api/src/main/res/values/strings.xml +source_lang = en diff --git a/plugins/openpgp-api-lib/CHANGELOG.md b/plugins/openpgp-api-lib/CHANGELOG.md new file mode 100644 index 000000000..93b6824ea --- /dev/null +++ b/plugins/openpgp-api-lib/CHANGELOG.md @@ -0,0 +1,48 @@ +# Version history + +## Version 10 + * Retrieve whole public key via ACTION_GET_KEY + +## Version 9 + * AIDL Service has been changed from IOpenPgpService.aidl to IOpenPgpService2.aidl + This fixes truncated data streams (thanks to 'mgeier63'). + * Fix for OpenPgpKeyPreference: Properly execute pending user interactions + * Charset moved to OpenPgpMetadata + +## Version 8 + * OpenPgpSignatureResult: + method getStatus() renamed to getResult() + constants have been renamed for clarity + new constants: RESULT_NO_SIGNATURE, RESULT_INVALID_INSECURE + isSignatureOnly() has been deprecated + * RESULT_TYPES have been removed + * new OpenPgpDecryptionResult returned via RESULT_DECRYPTION + * OpenPgpSignatureResult and OpenPgpDecryptionResult are never null, they are always returned. + +## Version 7 + * Deprecation of ACCOUNT_NAME, please use ACTION_GET_SIGN_KEY_ID to get key id + * Introduce EXTRA_SIGN_KEY_ID + * New extra for ACTION_ENCRYPT and ACTION_SIGN_AND_ENCRYPT: EXTRA_ENABLE_COMPRESSION (default to true) + * Return PendingIntent to view key for signatures + * New result for ACTION_DECRYPT_VERIFY: RESULT_TYPE + * New ACTION_GET_SIGN_KEY_ID + * EXTRA_PASSPHRASE changed from String to char[] + +## Version 6 + * Deprecate ACTION_SIGN + * Introduce ACTION_CLEARTEXT_SIGN and ACTION_DETACHED_SIGN + * New extra for ACTION_DETACHED_SIGN: EXTRA_DETACHED_SIGNATURE + * New result for ACTION_DECRYPT_VERIFY: RESULT_DETACHED_SIGNATURE + * New result for ACTION_DECRYPT_VERIFY: RESULT_CHARSET + +## Version 5 + * OpenPgpSignatureResult: new consts RESULT_INVALID_KEY_REVOKED and RESULT_INVALID_KEY_EXPIRED + * OpenPgpSignatureResult: ArrayList userIds + +## Version 4 + * No changes to existing methods -> backward compatible + * Introduction of ACTION_DECRYPT_METADATA, RESULT_METADATA, EXTRA_ORIGINAL_FILENAME, and OpenPgpMetadata parcel + * Introduction of internal NFC extras: EXTRA_NFC_SIGNED_HASH, EXTRA_NFC_SIG_CREATION_TIMESTAMP + +## Version 3 + * First public stable version \ No newline at end of file diff --git a/plugins/openpgp-api-lib/LICENSE b/plugins/openpgp-api-lib/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/plugins/openpgp-api-lib/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/plugins/openpgp-api-lib/README.md b/plugins/openpgp-api-lib/README.md new file mode 100644 index 000000000..8cb6e5e6d --- /dev/null +++ b/plugins/openpgp-api-lib/README.md @@ -0,0 +1,169 @@ +# OpenPGP API library + +The OpenPGP API provides methods to execute OpenPGP operations, such as sign, encrypt, decrypt, verify, and more without user interaction from background threads. This is done by connecting your client application to a remote service provided by [OpenKeychain](http://www.openkeychain.org) or other OpenPGP providers. + +### News + +#### Version 10 + * Retrieve whole public key via ACTION_GET_KEY + +[Full changelog here…](https://github.com/open-keychain/openpgp-api/blob/master/CHANGELOG.md) + +### License +While OpenKeychain itself is GPLv3+, the API library is licensed under Apache License v2. +Thus, you are allowed to also use it in closed source applications as long as you respect the [Apache License v2](https://github.com/open-keychain/openpgp-api/blob/master/LICENSE). + +### Add the API library to your project + +Add this to your build.gradle: + +```gradle +repositories { + jcenter() +} + +dependencies { + compile 'org.sufficientlysecure:openpgp-api:10.0' +} +``` + +### Full example +A full working example is available in the [example project](https://github.com/open-keychain/openpgp-api/blob/master/example). The [``OpenPgpApiActivity.java``](https://github.com/open-keychain/openpgp-api/blob/master/example/src/main/java/org/openintents/openpgp/example/OpenPgpApiActivity.java) contains most relevant sourcecode. + +### API + +[OpenPgpApi](https://github.com/open-keychain/openpgp-api/blob/master/openpgp-api/src/main/java/org/openintents/openpgp/util/OpenPgpApi.java) contains all possible Intents and available extras. + +### Short tutorial + +**This tutorial only covers the basics, please consult the full example for a complete overview over all methods** + +The API is **not** designed around ``Intents`` which are started via ``startActivityForResult``. These Intent actions typically start an activity for user interaction, so they are not suitable for background tasks. Most API design decisions are explained at [the bottom of this wiki page](https://github.com/open-keychain/open-keychain/wiki/OpenPGP-API#internal-design-decisions). + +We will go through the basic steps to understand how this API works, following this (greatly simplified) sequence diagram: +![](https://github.com/open-keychain/open-keychain/raw/master/Resources/docs/openpgp_api_1.jpg) + +In this diagram the client app is depicted on the left side, the OpenPGP provider (in this case OpenKeychain) is depicted on the right. +The remote service is defined via the [AIDL](http://developer.android.com/guide/components/aidl.html) file [``IOpenPgpService``](https://github.com/open-keychain/openpgp-api/blob/master/openpgp-api/src/main/aidl/org/openintents/openpgp/IOpenPgpService.aidl). +It contains only one exposed method which can be invoked remotely: +```java +interface IOpenPgpService { + Intent execute(in Intent data, in ParcelFileDescriptor input, in ParcelFileDescriptor output); +} +``` +The interaction between the apps is done by binding from your client app to the remote service of OpenKeychain. +``OpenPgpServiceConnection`` is a helper class from the library to ease this step: +```java +OpenPgpServiceConnection mServiceConnection; + +public void onCreate(Bundle savedInstance) { + [...] + mServiceConnection = new OpenPgpServiceConnection(this, "org.sufficientlysecure.keychain"); + mServiceConnection.bindToService(); +} + +public void onDestroy() { + [...] + if (mServiceConnection != null) { + mServiceConnection.unbindFromService(); + } +} +``` + +Following the sequence diagram, these steps are executed: + +1. Define an ``Intent`` containing the actual PGP instructions which should be done, e.g. + ```java +Intent data = new Intent(); +data.setAction(OpenPgpApi.ACTION_ENCRYPT); +data.putExtra(OpenPgpApi.EXTRA_USER_IDS, new String[]{"dominik@dominikschuermann.de"}); +data.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true); + ``` + Define an ``InputStream`` currently holding the plaintext, and an ``OutputStream`` where you want the ciphertext to be written by OpenKeychain's remote service: + ```java +InputStream is = new ByteArrayInputStream("Hello world!".getBytes("UTF-8")); +ByteArrayOutputStream os = new ByteArrayOutputStream(); + ``` + Using a helper class from the library, ``is`` and ``os`` are passed via ``ParcelFileDescriptors`` as ``input`` and ``output`` together with ``Intent data``, as depicted in the sequence diagram, from the client to the remote service. + Programmatically, this can be done with: + ```java +OpenPgpApi api = new OpenPgpApi(this, mServiceConnection.getService()); +Intent result = api.executeApi(data, is, os); + ``` + +2. The PGP operation is executed by OpenKeychain and the produced ciphertext is written into ``os`` which can then be accessed by the client app. + +3. A result Intent is returned containing one of these result codes: + * ``OpenPgpApi.RESULT_CODE_ERROR`` + * ``OpenPgpApi.RESULT_CODE_SUCCESS`` + * ``OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED`` + + If ``RESULT_CODE_USER_INTERACTION_REQUIRED`` is returned, an additional ``PendingIntent`` is returned to the client, which must be used to get user input required to process the request. + A ``PendingIntent`` is executed with ``startIntentSenderForResult``, which starts an activity, originally belonging to OpenKeychain, on the [task stack](http://developer.android.com/guide/components/tasks-and-back-stack.html) of the client. + Only if ``RESULT_CODE_SUCCESS`` is returned, ``os`` actually contains data. + A nearly complete example looks like this: + ```java + switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) { + case OpenPgpApi.RESULT_CODE_SUCCESS: { + try { + Log.d(OpenPgpApi.TAG, "output: " + os.toString("UTF-8")); + } catch (UnsupportedEncodingException e) { + Log.e(Constants.TAG, "UnsupportedEncodingException", e); + } + + if (result.hasExtra(OpenPgpApi.RESULT_SIGNATURE)) { + OpenPgpSignatureResult sigResult + = result.getParcelableExtra(OpenPgpApi.RESULT_SIGNATURE); + [...] + } + break; + } + case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED: { + PendingIntent pi = result.getParcelableExtra(OpenPgpApi.RESULT_INTENT); + try { + startIntentSenderForResult(pi.getIntentSender(), 42, null, 0, 0, 0); + } catch (IntentSender.SendIntentException e) { + Log.e(Constants.TAG, "SendIntentException", e); + } + break; + } + case OpenPgpApi.RESULT_CODE_ERROR: { + OpenPgpError error = result.getParcelableExtra(OpenPgpApi.RESULT_ERROR); + [...] + break; + } + } + ``` + +4. Results from a ``PendingIntent`` are returned in ``onActivityResult`` of the activity, which executed ``startIntentSenderForResult``. + The returned ``Intent data`` in ``onActivityResult`` contains the original PGP operation definition and new values acquired from the user interaction. + Thus, you can now execute the ``Intent`` again, like done in step 1. + This time it should return with ``RESULT_CODE_SUCCESS`` because all required information has been obtained by the previous user interaction stored in this ``Intent``. + ```java + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + [...] + // try again after user interaction + if (resultCode == RESULT_OK) { + switch (requestCode) { + case 42: { + encrypt(data); // defined like in step 1 + break; + } + } + } + } + ``` + + +### Tipps +* ``api.executeApi(data, is, os);`` is a blocking call. If you want a convenient asynchronous call, use ``api.executeApiAsync(data, is, os, new MyCallback([... ]));``, where ``MyCallback`` is an private class implementing ``OpenPgpApi.IOpenPgpCallback``. + See [``OpenPgpApiActivity.java``](https://github.com/open-keychain/openpgp-api/blob/master/example/src/main/java/org/openintents/openpgp/example/OpenPgpApiActivity.java) for an example. +* Using + + ```java + mServiceConnection = new OpenPgpServiceConnection(this, "org.sufficientlysecure.keychain"); + ``` + connects to OpenKeychain directly. + If you want to let the user choose between OpenPGP providers, you can implement the [``OpenPgpAppPreference.java``](https://github.com/open-keychain/openpgp-api/tree/master/openpgp-api/src/main/java/org/openintents/openpgp/util/OpenPgpAppPreference.java) like done in the example app. + +* To enable installing a debug and release version at the same time, the `debug` build of OpenKeychain uses `org.sufficientlysecure.keychain.debug` as a package name. Make sure you connect to the right one during development! diff --git a/plugins/openpgp-api-lib/build.gradle b/plugins/openpgp-api-lib/build.gradle new file mode 100644 index 000000000..309f3fb15 --- /dev/null +++ b/plugins/openpgp-api-lib/build.gradle @@ -0,0 +1,15 @@ +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.3.0' + classpath 'com.novoda:bintray-release:0.2.7' + } +} + +allprojects { + repositories { + jcenter() + } +} diff --git a/plugins/openpgp-api-lib/example/.gitignore b/plugins/openpgp-api-lib/example/.gitignore new file mode 100644 index 000000000..a44cc0f0f --- /dev/null +++ b/plugins/openpgp-api-lib/example/.gitignore @@ -0,0 +1,33 @@ +#Android specific +bin +gen +obj +lint.xml +local.properties +release.properties +ant.properties +*.class +*.apk + +#Gradle +.gradle +build +gradle.properties + +#Maven +target +pom.xml.* + +#Eclipse +.project +.classpath +.settings +.metadata + +#IntelliJ IDEA +.idea +*.iml + +#Lint output +lint-report.html +lint-report_files/* \ No newline at end of file diff --git a/plugins/openpgp-api-lib/example/build.gradle b/plugins/openpgp-api-lib/example/build.gradle new file mode 100644 index 000000000..c73848ca4 --- /dev/null +++ b/plugins/openpgp-api-lib/example/build.gradle @@ -0,0 +1,24 @@ +apply plugin: 'com.android.application' + +dependencies { + compile 'com.android.support:support-v4:22.2.1' + compile project(':openpgp-api') +} + +android { + compileSdkVersion 22 + buildToolsVersion '21.1.2' + + defaultConfig { + minSdkVersion 9 + targetSdkVersion 22 + applicationId 'org.openintents.openpgp.example' + versionCode 6 + versionName '7.0' + } + + // Do not abort build if lint finds errors + lintOptions { + abortOnError false + } +} diff --git a/plugins/openpgp-api-lib/example/gradle/wrapper/gradle-wrapper.jar b/plugins/openpgp-api-lib/example/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..cb5ccd9f1 Binary files /dev/null and b/plugins/openpgp-api-lib/example/gradle/wrapper/gradle-wrapper.jar differ diff --git a/plugins/openpgp-api-lib/example/gradle/wrapper/gradle-wrapper.properties b/plugins/openpgp-api-lib/example/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..6e00d9230 --- /dev/null +++ b/plugins/openpgp-api-lib/example/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +#Mon Mar 23 19:39:48 CET 2015 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.3-bin.zip +distributionSha256Sum=010dd9f31849abc3d5644e282943b1c1c355f8e2635c5789833979ce590a3774 \ No newline at end of file diff --git a/plugins/openpgp-api-lib/example/gradlew b/plugins/openpgp-api-lib/example/gradlew new file mode 100755 index 000000000..91a7e269e --- /dev/null +++ b/plugins/openpgp-api-lib/example/gradlew @@ -0,0 +1,164 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# For Cygwin, ensure paths are in UNIX format before anything is touched. +if $cygwin ; then + [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` +fi + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >&- +APP_HOME="`pwd -P`" +cd "$SAVED" >&- + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/plugins/openpgp-api-lib/example/ic_launcher-web.png b/plugins/openpgp-api-lib/example/ic_launcher-web.png new file mode 100644 index 000000000..ae4cd0976 Binary files /dev/null and b/plugins/openpgp-api-lib/example/ic_launcher-web.png differ diff --git a/plugins/openpgp-api-lib/example/src/main/AndroidManifest.xml b/plugins/openpgp-api-lib/example/src/main/AndroidManifest.xml new file mode 100644 index 000000000..e9bf09687 --- /dev/null +++ b/plugins/openpgp-api-lib/example/src/main/AndroidManifest.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/plugins/openpgp-api-lib/example/src/main/java/org/openintents/openpgp/example/BaseActivity.java b/plugins/openpgp-api-lib/example/src/main/java/org/openintents/openpgp/example/BaseActivity.java new file mode 100644 index 000000000..8d1381bb6 --- /dev/null +++ b/plugins/openpgp-api-lib/example/src/main/java/org/openintents/openpgp/example/BaseActivity.java @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2012-2014 Dominik Schürmann + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openintents.openpgp.example; + +import android.content.Intent; +import android.os.Bundle; +import android.preference.Preference; +import android.preference.Preference.OnPreferenceClickListener; +import android.preference.PreferenceActivity; + +import org.openintents.openpgp.util.OpenPgpAppPreference; +import org.openintents.openpgp.util.OpenPgpKeyPreference; + +public class BaseActivity extends PreferenceActivity { + OpenPgpKeyPreference mKey; + OpenPgpAppPreference mProvider; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // load preferences from xml + addPreferencesFromResource(R.xml.base_preference); + + // find preferences + Preference openKeychainIntents = findPreference("intent_demo"); + Preference openPgpApi = findPreference("openpgp_provider_demo"); + mProvider = (OpenPgpAppPreference) findPreference("openpgp_provider_list"); + mKey = (OpenPgpKeyPreference) findPreference("openpgp_key"); + + openPgpApi.setOnPreferenceClickListener(new OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + startActivity(new Intent(BaseActivity.this, OpenPgpApiActivity.class)); + + return false; + } + }); + + mKey.setOpenPgpProvider(mProvider.getValue()); + mProvider.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + mKey.setOpenPgpProvider((String) newValue); + return true; + } + }); + mKey.setDefaultUserId("Alice "); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (mKey.handleOnActivityResult(requestCode, resultCode, data)) { + // handled by OpenPgpKeyPreference + return; + } + // other request codes... + } +} diff --git a/plugins/openpgp-api-lib/example/src/main/java/org/openintents/openpgp/example/Constants.java b/plugins/openpgp-api-lib/example/src/main/java/org/openintents/openpgp/example/Constants.java new file mode 100644 index 000000000..79a0e8b1b --- /dev/null +++ b/plugins/openpgp-api-lib/example/src/main/java/org/openintents/openpgp/example/Constants.java @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2013-2015 Dominik Schürmann + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openintents.openpgp.example; + +public final class Constants { + public static final String TAG = "Keychain"; +} diff --git a/plugins/openpgp-api-lib/example/src/main/java/org/openintents/openpgp/example/OpenPgpApiActivity.java b/plugins/openpgp-api-lib/example/src/main/java/org/openintents/openpgp/example/OpenPgpApiActivity.java new file mode 100644 index 000000000..823c202cf --- /dev/null +++ b/plugins/openpgp-api-lib/example/src/main/java/org/openintents/openpgp/example/OpenPgpApiActivity.java @@ -0,0 +1,462 @@ +/* + * Copyright (C) 2013-2015 Dominik Schürmann + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openintents.openpgp.example; + +import android.app.Activity; +import android.app.PendingIntent; +import android.content.Intent; +import android.content.IntentSender; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.text.TextUtils; +import android.util.Log; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; +import android.widget.Toast; + +import org.openintents.openpgp.IOpenPgpService2; +import org.openintents.openpgp.OpenPgpDecryptionResult; +import org.openintents.openpgp.OpenPgpError; +import org.openintents.openpgp.OpenPgpSignatureResult; +import org.openintents.openpgp.util.OpenPgpApi; +import org.openintents.openpgp.util.OpenPgpServiceConnection; +import org.openintents.openpgp.util.OpenPgpUtils; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; + +public class OpenPgpApiActivity extends Activity { + private EditText mMessage; + private EditText mCiphertext; + private EditText mDetachedSignature; + private EditText mEncryptUserIds; + private EditText mGetKeyEdit; + + private OpenPgpServiceConnection mServiceConnection; + + private long mSignKeyId; + + public static final int REQUEST_CODE_CLEARTEXT_SIGN = 9910; + public static final int REQUEST_CODE_ENCRYPT = 9911; + public static final int REQUEST_CODE_SIGN_AND_ENCRYPT = 9912; + public static final int REQUEST_CODE_DECRYPT_AND_VERIFY = 9913; + public static final int REQUEST_CODE_GET_KEY = 9914; + public static final int REQUEST_CODE_GET_KEY_IDS = 9915; + public static final int REQUEST_CODE_DETACHED_SIGN = 9916; + public static final int REQUEST_CODE_DECRYPT_AND_VERIFY_DETACHED = 9917; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.openpgp_provider); + + mMessage = (EditText) findViewById(R.id.crypto_provider_demo_message); + mCiphertext = (EditText) findViewById(R.id.crypto_provider_demo_ciphertext); + mDetachedSignature = (EditText) findViewById(R.id.crypto_provider_demo_detached_signature); + mEncryptUserIds = (EditText) findViewById(R.id.crypto_provider_demo_encrypt_user_id); + Button cleartextSign = (Button) findViewById(R.id.crypto_provider_demo_cleartext_sign); + Button detachedSign = (Button) findViewById(R.id.crypto_provider_demo_detached_sign); + Button encrypt = (Button) findViewById(R.id.crypto_provider_demo_encrypt); + Button signAndEncrypt = (Button) findViewById(R.id.crypto_provider_demo_sign_and_encrypt); + Button decryptAndVerify = (Button) findViewById(R.id.crypto_provider_demo_decrypt_and_verify); + Button verifyDetachedSignature = (Button) findViewById(R.id.crypto_provider_demo_verify_detached_signature); + mGetKeyEdit = (EditText) findViewById(R.id.crypto_provider_demo_get_key_edit); + EditText getKeyIdsEdit = (EditText) findViewById(R.id.crypto_provider_demo_get_key_ids_edit); + Button getKey = (Button) findViewById(R.id.crypto_provider_demo_get_key); + Button getKeyIds = (Button) findViewById(R.id.crypto_provider_demo_get_key_ids); + + cleartextSign.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + cleartextSign(new Intent()); + } + }); + detachedSign.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + detachedSign(new Intent()); + } + }); + encrypt.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + encrypt(new Intent()); + } + }); + signAndEncrypt.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + signAndEncrypt(new Intent()); + } + }); + decryptAndVerify.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + decryptAndVerify(new Intent()); + } + }); + verifyDetachedSignature.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + decryptAndVerifyDetached(new Intent()); + } + }); + getKey.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + getKey(new Intent()); + } + }); + getKeyIds.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + getKeyIds(new Intent()); + } + }); + + SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); + String providerPackageName = settings.getString("openpgp_provider_list", ""); + mSignKeyId = settings.getLong("openpgp_key", 0); + if (TextUtils.isEmpty(providerPackageName)) { + Toast.makeText(this, "No OpenPGP app selected!", Toast.LENGTH_LONG).show(); + finish(); + } else if (mSignKeyId == 0) { + Toast.makeText(this, "No key selected!", Toast.LENGTH_LONG).show(); + finish(); + } else { + // bind to service + mServiceConnection = new OpenPgpServiceConnection( + OpenPgpApiActivity.this.getApplicationContext(), + providerPackageName, + new OpenPgpServiceConnection.OnBound() { + @Override + public void onBound(IOpenPgpService2 service) { + Log.d(OpenPgpApi.TAG, "onBound!"); + } + + @Override + public void onError(Exception e) { + Log.e(OpenPgpApi.TAG, "exception when binding!", e); + } + } + ); + mServiceConnection.bindToService(); + } + } + + private void handleError(final OpenPgpError error) { + runOnUiThread(new Runnable() { + + @Override + public void run() { + Toast.makeText(OpenPgpApiActivity.this, + "onError id:" + error.getErrorId() + "\n\n" + error.getMessage(), + Toast.LENGTH_LONG).show(); + Log.e(Constants.TAG, "onError getErrorId:" + error.getErrorId()); + Log.e(Constants.TAG, "onError getMessage:" + error.getMessage()); + } + }); + } + + private void showToast(final String message) { + runOnUiThread(new Runnable() { + + @Override + public void run() { + Toast.makeText(OpenPgpApiActivity.this, + message, + Toast.LENGTH_SHORT).show(); + } + }); + } + + /** + * Takes input from message or ciphertext EditText and turns it into a ByteArrayInputStream + */ + private InputStream getInputstream(boolean ciphertext) { + InputStream is = null; + try { + String inputStr; + if (ciphertext) { + inputStr = mCiphertext.getText().toString(); + } else { + inputStr = mMessage.getText().toString(); + } + is = new ByteArrayInputStream(inputStr.getBytes("UTF-8")); + } catch (UnsupportedEncodingException e) { + Log.e(Constants.TAG, "UnsupportedEncodingException", e); + } + + return is; + } + + private class MyCallback implements OpenPgpApi.IOpenPgpCallback { + boolean returnToCiphertextField; + ByteArrayOutputStream os; + int requestCode; + + private MyCallback(boolean returnToCiphertextField, ByteArrayOutputStream os, int requestCode) { + this.returnToCiphertextField = returnToCiphertextField; + this.os = os; + this.requestCode = requestCode; + } + + @Override + public void onReturn(Intent result) { + switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) { + case OpenPgpApi.RESULT_CODE_SUCCESS: { + showToast("RESULT_CODE_SUCCESS"); + + // encrypt/decrypt/sign/verify + if (os != null) { + try { + Log.d(OpenPgpApi.TAG, "result: " + os.toByteArray().length + + " str=" + os.toString("UTF-8")); + + if (returnToCiphertextField) { + mCiphertext.setText(os.toString("UTF-8")); + } else { + mMessage.setText(os.toString("UTF-8")); + } + } catch (UnsupportedEncodingException e) { + Log.e(Constants.TAG, "UnsupportedEncodingException", e); + } + } + + switch (requestCode) { + case REQUEST_CODE_DECRYPT_AND_VERIFY: + case REQUEST_CODE_DECRYPT_AND_VERIFY_DETACHED: { + // RESULT_SIGNATURE and RESULT_DECRYPTION are never null! + + OpenPgpSignatureResult signatureResult + = result.getParcelableExtra(OpenPgpApi.RESULT_SIGNATURE); + showToast(signatureResult.toString()); + OpenPgpDecryptionResult decryptionResult + = result.getParcelableExtra(OpenPgpApi.RESULT_DECRYPTION); + showToast(decryptionResult.toString()); + + break; + } + case REQUEST_CODE_DETACHED_SIGN: { + byte[] detachedSig + = result.getByteArrayExtra(OpenPgpApi.RESULT_DETACHED_SIGNATURE); + Log.d(OpenPgpApi.TAG, "RESULT_DETACHED_SIGNATURE: " + detachedSig.length + + " str=" + new String(detachedSig)); + mDetachedSignature.setText(new String(detachedSig)); + + break; + } + case REQUEST_CODE_GET_KEY_IDS: { + long[] keyIds = result.getLongArrayExtra(OpenPgpApi.RESULT_KEY_IDS); + String out = "keyIds: "; + for (long keyId : keyIds) { + out += OpenPgpUtils.convertKeyIdToHex(keyId) + ", "; + } + showToast(out); + + break; + } + default: { + + } + } + + break; + } + case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED: { + showToast("RESULT_CODE_USER_INTERACTION_REQUIRED"); + + PendingIntent pi = result.getParcelableExtra(OpenPgpApi.RESULT_INTENT); + try { + OpenPgpApiActivity.this.startIntentSenderFromChild( + OpenPgpApiActivity.this, pi.getIntentSender(), + requestCode, null, 0, 0, 0); + } catch (IntentSender.SendIntentException e) { + Log.e(Constants.TAG, "SendIntentException", e); + } + break; + } + case OpenPgpApi.RESULT_CODE_ERROR: { + showToast("RESULT_CODE_ERROR"); + + OpenPgpError error = result.getParcelableExtra(OpenPgpApi.RESULT_ERROR); + handleError(error); + break; + } + } + } + } + + public void cleartextSign(Intent data) { + data.setAction(OpenPgpApi.ACTION_CLEARTEXT_SIGN); + data.putExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, mSignKeyId); + + InputStream is = getInputstream(false); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + + OpenPgpApi api = new OpenPgpApi(this, mServiceConnection.getService()); + api.executeApiAsync(data, is, os, new MyCallback(true, os, REQUEST_CODE_CLEARTEXT_SIGN)); + } + + public void detachedSign(Intent data) { + data.setAction(OpenPgpApi.ACTION_DETACHED_SIGN); + data.putExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, mSignKeyId); + + InputStream is = getInputstream(false); + // no output stream needed, detached signature is returned as RESULT_DETACHED_SIGNATURE + + OpenPgpApi api = new OpenPgpApi(this, mServiceConnection.getService()); + api.executeApiAsync(data, is, null, new MyCallback(true, null, REQUEST_CODE_DETACHED_SIGN)); + } + + public void encrypt(Intent data) { + data.setAction(OpenPgpApi.ACTION_ENCRYPT); + if (!TextUtils.isEmpty(mEncryptUserIds.getText().toString())) { + data.putExtra(OpenPgpApi.EXTRA_USER_IDS, mEncryptUserIds.getText().toString().split(",")); + } + data.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true); + + InputStream is = getInputstream(false); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + + OpenPgpApi api = new OpenPgpApi(this, mServiceConnection.getService()); + api.executeApiAsync(data, is, os, new MyCallback(true, os, REQUEST_CODE_ENCRYPT)); + } + + public void signAndEncrypt(Intent data) { + data.setAction(OpenPgpApi.ACTION_SIGN_AND_ENCRYPT); + data.putExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, mSignKeyId); + if (!TextUtils.isEmpty(mEncryptUserIds.getText().toString())) { + data.putExtra(OpenPgpApi.EXTRA_USER_IDS, mEncryptUserIds.getText().toString().split(",")); + } + data.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true); + + InputStream is = getInputstream(false); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + + OpenPgpApi api = new OpenPgpApi(this, mServiceConnection.getService()); + api.executeApiAsync(data, is, os, new MyCallback(true, os, REQUEST_CODE_SIGN_AND_ENCRYPT)); + } + + public void decryptAndVerify(Intent data) { + data.setAction(OpenPgpApi.ACTION_DECRYPT_VERIFY); + + InputStream is = getInputstream(true); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + + OpenPgpApi api = new OpenPgpApi(this, mServiceConnection.getService()); + api.executeApiAsync(data, is, os, new MyCallback(false, os, REQUEST_CODE_DECRYPT_AND_VERIFY)); + } + + public void decryptAndVerifyDetached(Intent data) { + data.setAction(OpenPgpApi.ACTION_DECRYPT_VERIFY); + data.putExtra(OpenPgpApi.EXTRA_DETACHED_SIGNATURE, mDetachedSignature.getText().toString().getBytes()); + + // use from text from mMessage + InputStream is = getInputstream(false); + + OpenPgpApi api = new OpenPgpApi(this, mServiceConnection.getService()); + api.executeApiAsync(data, is, null, new MyCallback(false, null, REQUEST_CODE_DECRYPT_AND_VERIFY_DETACHED)); + } + + public void getKey(Intent data) { + data.setAction(OpenPgpApi.ACTION_GET_KEY); + data.putExtra(OpenPgpApi.EXTRA_KEY_ID, Long.decode(mGetKeyEdit.getText().toString())); + + OpenPgpApi api = new OpenPgpApi(this, mServiceConnection.getService()); + api.executeApiAsync(data, null, null, new MyCallback(false, null, REQUEST_CODE_GET_KEY)); + } + + public void getKeyIds(Intent data) { + data.setAction(OpenPgpApi.ACTION_GET_KEY_IDS); + + OpenPgpApi api = new OpenPgpApi(this, mServiceConnection.getService()); + api.executeApiAsync(data, null, null, new MyCallback(false, null, REQUEST_CODE_GET_KEY_IDS)); + } + + public void getAnyKeyIds(Intent data) { + data.setAction(OpenPgpApi.ACTION_GET_KEY_IDS); +// data.putExtra(OpenPgpApi.EXTRA_USER_IDS, mGetKeyIdsEdit.getText().toString().split(",")); + + OpenPgpApi api = new OpenPgpApi(this, mServiceConnection.getService()); + api.executeApiAsync(data, null, null, new MyCallback(false, null, REQUEST_CODE_GET_KEY_IDS)); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + Log.d(Constants.TAG, "onActivityResult resultCode: " + resultCode); + + // try again after user interaction + if (resultCode == RESULT_OK) { + /* + * The data originally given to one of the methods above, is again + * returned here to be used when calling the method again after user + * interaction. The Intent now also contains results from the user + * interaction, for example selected key ids. + */ + switch (requestCode) { + case REQUEST_CODE_CLEARTEXT_SIGN: { + cleartextSign(data); + break; + } + case REQUEST_CODE_DETACHED_SIGN: { + detachedSign(data); + break; + } + case REQUEST_CODE_ENCRYPT: { + encrypt(data); + break; + } + case REQUEST_CODE_SIGN_AND_ENCRYPT: { + signAndEncrypt(data); + break; + } + case REQUEST_CODE_DECRYPT_AND_VERIFY: { + decryptAndVerify(data); + break; + } + case REQUEST_CODE_DECRYPT_AND_VERIFY_DETACHED: { + decryptAndVerifyDetached(data); + break; + } + case REQUEST_CODE_GET_KEY: { + getKey(data); + break; + } + case REQUEST_CODE_GET_KEY_IDS: { + getKeyIds(data); + break; + } + } + } + } + + @Override + public void onDestroy() { + super.onDestroy(); + + if (mServiceConnection != null) { + mServiceConnection.unbindFromService(); + } + } + +} diff --git a/plugins/openpgp-api-lib/example/src/main/res/drawable-hdpi/ic_launcher.png b/plugins/openpgp-api-lib/example/src/main/res/drawable-hdpi/ic_launcher.png new file mode 100644 index 000000000..cf114d7db Binary files /dev/null and b/plugins/openpgp-api-lib/example/src/main/res/drawable-hdpi/ic_launcher.png differ diff --git a/plugins/openpgp-api-lib/example/src/main/res/drawable-mdpi/ic_launcher.png b/plugins/openpgp-api-lib/example/src/main/res/drawable-mdpi/ic_launcher.png new file mode 100644 index 000000000..d55318843 Binary files /dev/null and b/plugins/openpgp-api-lib/example/src/main/res/drawable-mdpi/ic_launcher.png differ diff --git a/plugins/openpgp-api-lib/example/src/main/res/drawable-xhdpi/ic_launcher.png b/plugins/openpgp-api-lib/example/src/main/res/drawable-xhdpi/ic_launcher.png new file mode 100644 index 000000000..13ed3d450 Binary files /dev/null and b/plugins/openpgp-api-lib/example/src/main/res/drawable-xhdpi/ic_launcher.png differ diff --git a/plugins/openpgp-api-lib/example/src/main/res/drawable-xxhdpi/ic_launcher.png b/plugins/openpgp-api-lib/example/src/main/res/drawable-xxhdpi/ic_launcher.png new file mode 100644 index 000000000..831c993d4 Binary files /dev/null and b/plugins/openpgp-api-lib/example/src/main/res/drawable-xxhdpi/ic_launcher.png differ diff --git a/plugins/openpgp-api-lib/example/src/main/res/layout/openpgp_provider.xml b/plugins/openpgp-api-lib/example/src/main/res/layout/openpgp_provider.xml new file mode 100644 index 000000000..13096b4c6 --- /dev/null +++ b/plugins/openpgp-api-lib/example/src/main/res/layout/openpgp_provider.xml @@ -0,0 +1,190 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +