include openpgp-api-lib, again

This commit is contained in:
Vincent Breitmoser 2015-12-12 16:03:40 +01:00
parent 93df7525c4
commit f483426a12
79 changed files with 3926 additions and 1 deletions

View file

@ -23,12 +23,12 @@ dependencies {
compile project(':k9mail-library') compile project(':k9mail-library')
compile project(':plugins:Android-PullToRefresh:library') compile project(':plugins:Android-PullToRefresh:library')
compile project(':plugins:HoloColorPicker') compile project(':plugins:HoloColorPicker')
compile project(':plugins:openpgp-api-lib:openpgp-api')
compile 'commons-io:commons-io:2.4' compile 'commons-io:commons-io:2.4'
compile "com.android.support:support-v4:${project.supportLibraryVersion}" compile "com.android.support:support-v4:${project.supportLibraryVersion}"
compile 'net.sourceforge.htmlcleaner:htmlcleaner:2.16' compile 'net.sourceforge.htmlcleaner:htmlcleaner:2.16'
compile 'de.cketti.library.changelog:ckchangelog:1.2.1' compile 'de.cketti.library.changelog:ckchangelog:1.2.1'
compile 'com.github.bumptech.glide:glide:3.6.1' compile 'com.github.bumptech.glide:glide:3.6.1'
compile 'org.sufficientlysecure:openpgp-api:8.0'
compile 'com.splitwise:tokenautocomplete:2.0.2' compile 'com.splitwise:tokenautocomplete:2.0.2'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1' androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'

33
plugins/openpgp-api-lib/.gitignore vendored Normal file
View file

@ -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/*

View file

@ -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-<lang>/strings.xml
source_file = openpgp-api/src/main/res/values/strings.xml
source_lang = en

View file

@ -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<String> 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

View file

@ -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.

View file

@ -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!

View file

@ -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()
}
}

View file

@ -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/*

View file

@ -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
}
}

Binary file not shown.

View file

@ -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

164
plugins/openpgp-api-lib/example/gradlew vendored Executable file
View file

@ -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 "$@"

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

View file

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.openintents.openpgp.example">
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="OpenPGP API Example">
<activity
android:name=".BaseActivity"
android:label="OpenPGP API Example">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".OpenPgpApiActivity"
android:label="OpenPGP API"
android:windowSoftInputMode="stateHidden" />
</application>
</manifest>

View file

@ -0,0 +1,74 @@
/*
* Copyright (C) 2012-2014 Dominik Schürmann <dominik@dominikschuermann.de>
*
* 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 <alice@example.com>");
}
@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...
}
}

View file

@ -0,0 +1,21 @@
/*
* Copyright (C) 2013-2015 Dominik Schürmann <dominik@dominikschuermann.de>
*
* 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";
}

View file

@ -0,0 +1,462 @@
/*
* Copyright (C) 2013-2015 Dominik Schürmann <dominik@dominikschuermann.de>
*
* 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();
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

View file

@ -0,0 +1,190 @@
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/parent_scroll"
android:fillViewport="true"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:padding="8dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Encrypt UserIds (split with &apos;,&apos;)"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/crypto_provider_demo_encrypt_user_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="dominik@dominikschuermann.de"
android:textAppearance="@android:style/TextAppearance.Small" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Message"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ScrollView
android:id="@+id/child_scroll1"
android:fillViewport="true"
android:layout_width="match_parent"
android:layout_height="120dp">
<EditText
android:id="@+id/crypto_provider_demo_message"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollHorizontally="true"
android:scrollbars="vertical"
android:text="message"
android:hint="cleartext message"
android:textAppearance="@android:style/TextAppearance.Small" />
</ScrollView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Ciphertext"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ScrollView
android:id="@+id/child_scroll2"
android:fillViewport="true"
android:layout_width="match_parent"
android:layout_height="120dp">
<EditText
android:id="@+id/crypto_provider_demo_ciphertext"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="ciphertext"
android:hint="ciphertext"
android:textAppearance="@android:style/TextAppearance.Small" />
</ScrollView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Detached signature"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ScrollView
android:id="@+id/child_scroll3"
android:fillViewport="true"
android:layout_width="match_parent"
android:layout_height="60dp">
<EditText
android:id="@+id/crypto_provider_demo_detached_signature"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="detached signature"
android:hint="detached signature"
android:textAppearance="@android:style/TextAppearance.Small" />
</ScrollView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/crypto_provider_demo_cleartext_sign"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Cleartext Sign"
android:layout_gravity="center_vertical" />
<Button
android:id="@+id/crypto_provider_demo_detached_sign"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Detached Sign"
android:layout_gravity="center_vertical" />
<Button
android:id="@+id/crypto_provider_demo_encrypt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Encrypt"
android:layout_gravity="center_vertical" />
<Button
android:id="@+id/crypto_provider_demo_sign_and_encrypt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Sign and Encrypt"
android:layout_gravity="center_vertical" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/crypto_provider_demo_decrypt_and_verify"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="Decrypt and Verify" />
<Button
android:id="@+id/crypto_provider_demo_verify_detached_signature"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="Verify detached signature" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get key:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="0x718c070100012282"
android:id="@+id/crypto_provider_demo_get_key_edit" />
<Button
android:id="@+id/crypto_provider_demo_get_key"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Get key" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get key ids:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="dominik@dominikschuermann.de"
android:id="@+id/crypto_provider_demo_get_key_ids_edit" />
<Button
android:id="@+id/crypto_provider_demo_get_key_ids"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Get key ids" />
</LinearLayout>
</ScrollView>

View file

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="OpenPGP API">
<org.openintents.openpgp.util.OpenPgpAppPreference
android:key="openpgp_provider_list"
android:title="Select OpenPGP app!" />
<org.openintents.openpgp.util.OpenPgpKeyPreference
android:key="openpgp_key"
android:title="Select key!" />
<Preference
android:key="openpgp_provider_demo"
android:title="OpenPGP API Example" />
</PreferenceCategory>
</PreferenceScreen>

View file

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Intents (org.sufficientlysecure.keychain.action.)">
<Preference
android:key="ENCRYPT"
android:title="ENCRYPT" />
<Preference
android:key="ENCRYPT_URI"
android:title="ENCRYPT with Uri" />
<Preference
android:key="DECRYPT"
android:title="DECRYPT" />
<Preference
android:key="IMPORT_KEY"
android:title="IMPORT_KEY" />
<Preference
android:key="IMPORT_KEY_FROM_KEYSERVER"
android:title="IMPORT_KEY_FROM_KEYSERVER" />
<Preference
android:key="IMPORT_KEY_FROM_QR_CODE"
android:title="IMPORT_KEY_FROM_QR_CODE" />
</PreferenceCategory>
<PreferenceCategory android:title="Special Intents">
<Preference
android:key="openpgp4fpr"
android:title="VIEW openpgp4fpr:73EE2314F65FA92EC2390D3A718C070100012282" />
</PreferenceCategory>
</PreferenceScreen>

Binary file not shown.

View file

@ -0,0 +1,6 @@
#Mon Aug 10 21:47:49 CEST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.5-all.zip

164
plugins/openpgp-api-lib/gradlew vendored Executable file
View file

@ -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 "$@"

90
plugins/openpgp-api-lib/gradlew.bat vendored Normal file
View file

@ -0,0 +1,90 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

Binary file not shown.

View file

@ -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/*

View file

@ -0,0 +1,30 @@
apply plugin: 'com.android.library'
// apply plugin: 'bintray-release' // must be applied after your artifact generating plugin (eg. java / com.android.library)
android {
compileSdkVersion 22
buildToolsVersion '21.1.2'
defaultConfig {
versionCode 8
versionName '9.0' // API-Version . minor
minSdkVersion 9
targetSdkVersion 22
}
// Do not abort build if lint finds errors
lintOptions {
abortOnError false
}
}
/*
publish {
userOrg = 'sufficientlysecure'
groupId = 'org.sufficientlysecure'
artifactId = 'openpgp-api'
version = '9.0'
description = 'The OpenPGP API provides methods to execute OpenPGP operations, such as sign, encrypt, decrypt, verify, and more without user interaction from background threads.'
website = 'https://github.com/open-keychain/openpgp-api'
}
*/

View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.openintents.openpgp">
<application/>
</manifest>

View file

@ -0,0 +1,27 @@
/*
* Copyright (C) 2014-2015 Dominik Schürmann <dominik@dominikschuermann.de>
*
* 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;
interface IOpenPgpService {
/**
* do NOT use this, data returned from the service through "output" may be truncated
* @deprecated
*/
Intent execute(in Intent data, in ParcelFileDescriptor input, in ParcelFileDescriptor output);
}

View file

@ -0,0 +1,30 @@
/*
* Copyright (C) 2015 Dominik Schürmann <dominik@dominikschuermann.de>
*
* 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;
interface IOpenPgpService2 {
/**
* see org.openintents.openpgp.util.OpenPgpApi for documentation
*/
ParcelFileDescriptor createOutputPipe(in int pipeId);
/**
* see org.openintents.openpgp.util.OpenPgpApi for documentation
*/
Intent execute(in Intent data, in ParcelFileDescriptor input, int pipeId);
}

View file

@ -0,0 +1,108 @@
/*
* Copyright (C) 2015 Dominik Schürmann <dominik@dominikschuermann.de>
*
* 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;
import android.os.Parcel;
import android.os.Parcelable;
public class OpenPgpDecryptionResult implements Parcelable {
/**
* Since there might be a case where new versions of the client using the library getting
* old versions of the protocol (and thus old versions of this class), we need a versioning
* system for the parcels sent between the clients and the providers.
*/
public static final int PARCELABLE_VERSION = 1;
// content not encrypted
public static final int RESULT_NOT_ENCRYPTED = -1;
// insecure!
public static final int RESULT_INSECURE = 0;
// encrypted
public static final int RESULT_ENCRYPTED = 1;
int result;
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
public OpenPgpDecryptionResult() {
}
public OpenPgpDecryptionResult(int result) {
this.result = result;
}
public OpenPgpDecryptionResult(OpenPgpDecryptionResult b) {
this.result = b.result;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
/**
* NOTE: When adding fields in the process of updating this API, make sure to bump
* {@link #PARCELABLE_VERSION}.
*/
dest.writeInt(PARCELABLE_VERSION);
// Inject a placeholder that will store the parcel size from this point on
// (not including the size itself).
int sizePosition = dest.dataPosition();
dest.writeInt(0);
int startPosition = dest.dataPosition();
// version 1
dest.writeInt(result);
// Go back and write the size
int parcelableSize = dest.dataPosition() - startPosition;
dest.setDataPosition(sizePosition);
dest.writeInt(parcelableSize);
dest.setDataPosition(startPosition + parcelableSize);
}
public static final Creator<OpenPgpDecryptionResult> CREATOR = new Creator<OpenPgpDecryptionResult>() {
public OpenPgpDecryptionResult createFromParcel(final Parcel source) {
source.readInt(); // parcelableVersion
int parcelableSize = source.readInt();
int startPosition = source.dataPosition();
OpenPgpDecryptionResult vr = new OpenPgpDecryptionResult();
vr.result = source.readInt();
// skip over all fields added in future versions of this parcel
source.setDataPosition(startPosition + parcelableSize);
return vr;
}
public OpenPgpDecryptionResult[] newArray(final int size) {
return new OpenPgpDecryptionResult[size];
}
};
@Override
public String toString() {
return "\nresult: " + result;
}
}

View file

@ -0,0 +1,114 @@
/*
* Copyright (C) 2014-2015 Dominik Schürmann <dominik@dominikschuermann.de>
*
* 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;
import android.os.Parcel;
import android.os.Parcelable;
public class OpenPgpError implements Parcelable {
/**
* Since there might be a case where new versions of the client using the library getting
* old versions of the protocol (and thus old versions of this class), we need a versioning
* system for the parcels sent between the clients and the providers.
*/
public static final int PARCELABLE_VERSION = 1;
// possible values for errorId
public static final int CLIENT_SIDE_ERROR = -1;
public static final int GENERIC_ERROR = 0;
public static final int INCOMPATIBLE_API_VERSIONS = 1;
public static final int NO_OR_WRONG_PASSPHRASE = 2;
public static final int NO_USER_IDS = 3;
int errorId;
String message;
public OpenPgpError() {
}
public OpenPgpError(int errorId, String message) {
this.errorId = errorId;
this.message = message;
}
public OpenPgpError(OpenPgpError b) {
this.errorId = b.errorId;
this.message = b.message;
}
public int getErrorId() {
return errorId;
}
public void setErrorId(int errorId) {
this.errorId = errorId;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
/**
* NOTE: When adding fields in the process of updating this API, make sure to bump
* {@link #PARCELABLE_VERSION}.
*/
dest.writeInt(PARCELABLE_VERSION);
// Inject a placeholder that will store the parcel size from this point on
// (not including the size itself).
int sizePosition = dest.dataPosition();
dest.writeInt(0);
int startPosition = dest.dataPosition();
// version 1
dest.writeInt(errorId);
dest.writeString(message);
// Go back and write the size
int parcelableSize = dest.dataPosition() - startPosition;
dest.setDataPosition(sizePosition);
dest.writeInt(parcelableSize);
dest.setDataPosition(startPosition + parcelableSize);
}
public static final Creator<OpenPgpError> CREATOR = new Creator<OpenPgpError>() {
public OpenPgpError createFromParcel(final Parcel source) {
source.readInt(); // parcelableVersion
int parcelableSize = source.readInt();
int startPosition = source.dataPosition();
OpenPgpError error = new OpenPgpError();
error.errorId = source.readInt();
error.message = source.readString();
// skip over all fields added in future versions of this parcel
source.setDataPosition(startPosition + parcelableSize);
return error;
}
public OpenPgpError[] newArray(final int size) {
return new OpenPgpError[size];
}
};
}

View file

@ -0,0 +1,148 @@
/*
* Copyright (C) 2014-2015 Dominik Schürmann <dominik@dominikschuermann.de>
*
* 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;
import android.os.Parcel;
import android.os.Parcelable;
public class OpenPgpMetadata implements Parcelable {
/**
* Since there might be a case where new versions of the client using the library getting
* old versions of the protocol (and thus old versions of this class), we need a versioning
* system for the parcels sent between the clients and the providers.
*/
public static final int PARCELABLE_VERSION = 2;
String filename;
String mimeType;
String charset;
long modificationTime;
long originalSize;
public String getFilename() {
return filename;
}
public String getMimeType() {
return mimeType;
}
public long getModificationTime() {
return modificationTime;
}
public long getOriginalSize() {
return originalSize;
}
public String getCharset() {
return charset;
}
public OpenPgpMetadata() {
}
public OpenPgpMetadata(String filename, String mimeType, long modificationTime,
long originalSize, String charset) {
this.filename = filename;
this.mimeType = mimeType;
this.modificationTime = modificationTime;
this.originalSize = originalSize;
this.charset = charset;
}
public OpenPgpMetadata(String filename, String mimeType, long modificationTime,
long originalSize) {
this.filename = filename;
this.mimeType = mimeType;
this.modificationTime = modificationTime;
this.originalSize = originalSize;
}
public OpenPgpMetadata(OpenPgpMetadata b) {
this.filename = b.filename;
this.mimeType = b.mimeType;
this.modificationTime = b.modificationTime;
this.originalSize = b.originalSize;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
/**
* NOTE: When adding fields in the process of updating this API, make sure to bump
* {@link #PARCELABLE_VERSION}.
*/
dest.writeInt(PARCELABLE_VERSION);
// Inject a placeholder that will store the parcel size from this point on
// (not including the size itself).
int sizePosition = dest.dataPosition();
dest.writeInt(0);
int startPosition = dest.dataPosition();
// version 1
dest.writeString(filename);
dest.writeString(mimeType);
dest.writeLong(modificationTime);
dest.writeLong(originalSize);
// version 2
dest.writeString(charset);
// Go back and write the size
int parcelableSize = dest.dataPosition() - startPosition;
dest.setDataPosition(sizePosition);
dest.writeInt(parcelableSize);
dest.setDataPosition(startPosition + parcelableSize);
}
public static final Creator<OpenPgpMetadata> CREATOR = new Creator<OpenPgpMetadata>() {
public OpenPgpMetadata createFromParcel(final Parcel source) {
int version = source.readInt(); // parcelableVersion
int parcelableSize = source.readInt();
int startPosition = source.dataPosition();
OpenPgpMetadata vr = new OpenPgpMetadata();
vr.filename = source.readString();
vr.mimeType = source.readString();
vr.modificationTime = source.readLong();
vr.originalSize = source.readLong();
if (version >= 2) {
vr.charset = source.readString();
}
// skip over all fields added in future versions of this parcel
source.setDataPosition(startPosition + parcelableSize);
return vr;
}
public OpenPgpMetadata[] newArray(final int size) {
return new OpenPgpMetadata[size];
}
};
@Override
public String toString() {
String out = "\nfilename: " + filename;
out += "\nmimeType: " + mimeType;
out += "\nmodificationTime: " + modificationTime;
out += "\noriginalSize: " + originalSize;
out += "\ncharset: " + charset;
return out;
}
}

View file

@ -0,0 +1,184 @@
/*
* Copyright (C) 2014-2015 Dominik Schürmann <dominik@dominikschuermann.de>
*
* 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;
import android.os.Parcel;
import android.os.Parcelable;
import org.openintents.openpgp.util.OpenPgpUtils;
import java.util.ArrayList;
public class OpenPgpSignatureResult implements Parcelable {
/**
* Since there might be a case where new versions of the client using the library getting
* old versions of the protocol (and thus old versions of this class), we need a versioning
* system for the parcels sent between the clients and the providers.
*/
public static final int PARCELABLE_VERSION = 2;
// content not signed
public static final int RESULT_NO_SIGNATURE = -1;
// invalid signature!
public static final int RESULT_INVALID_SIGNATURE = 0;
// successfully verified signature, with confirmed key
public static final int RESULT_VALID_CONFIRMED = 1;
// no key was found for this signature verification
public static final int RESULT_KEY_MISSING = 2;
// successfully verified signature, but with unconfirmed key
public static final int RESULT_VALID_UNCONFIRMED = 3;
// key has been revoked -> invalid signature!
public static final int RESULT_INVALID_KEY_REVOKED = 4;
// key is expired -> invalid signature!
public static final int RESULT_INVALID_KEY_EXPIRED = 5;
// insecure cryptographic algorithms/protocol -> invalid signature!
public static final int RESULT_INVALID_INSECURE = 6;
int result;
boolean signatureOnly;
String primaryUserId;
ArrayList<String> userIds;
long keyId;
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
/** @deprecated This information should be obtained from OpenPgpDecryptionResult! */
public boolean isSignatureOnly() {
return signatureOnly;
}
/** @deprecated This information should be obtained from OpenPgpDecryptionResult! */
public void setSignatureOnly(boolean signatureOnly) {
this.signatureOnly = signatureOnly;
}
public String getPrimaryUserId() {
return primaryUserId;
}
public void setPrimaryUserId(String primaryUserId) {
this.primaryUserId = primaryUserId;
}
public ArrayList<String> getUserIds() {
return userIds;
}
public void setUserIds(ArrayList<String> userIds) {
this.userIds = userIds;
}
public long getKeyId() {
return keyId;
}
public void setKeyId(long keyId) {
this.keyId = keyId;
}
public OpenPgpSignatureResult() {
}
public OpenPgpSignatureResult(int signatureStatus, String signatureUserId,
boolean signatureOnly, long keyId, ArrayList<String> userIds) {
this.result = signatureStatus;
this.signatureOnly = signatureOnly;
this.primaryUserId = signatureUserId;
this.keyId = keyId;
this.userIds = userIds;
}
public OpenPgpSignatureResult(OpenPgpSignatureResult b) {
this.result = b.result;
this.primaryUserId = b.primaryUserId;
this.signatureOnly = b.signatureOnly;
this.keyId = b.keyId;
this.userIds = b.userIds;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
/**
* NOTE: When adding fields in the process of updating this API, make sure to bump
* {@link #PARCELABLE_VERSION}.
*/
dest.writeInt(PARCELABLE_VERSION);
// Inject a placeholder that will store the parcel size from this point on
// (not including the size itself).
int sizePosition = dest.dataPosition();
dest.writeInt(0);
int startPosition = dest.dataPosition();
// version 1
dest.writeInt(result);
dest.writeByte((byte) (signatureOnly ? 1 : 0));
dest.writeString(primaryUserId);
dest.writeLong(keyId);
// version 2
dest.writeStringList(userIds);
// Go back and write the size
int parcelableSize = dest.dataPosition() - startPosition;
dest.setDataPosition(sizePosition);
dest.writeInt(parcelableSize);
dest.setDataPosition(startPosition + parcelableSize);
}
public static final Creator<OpenPgpSignatureResult> CREATOR = new Creator<OpenPgpSignatureResult>() {
public OpenPgpSignatureResult createFromParcel(final Parcel source) {
source.readInt(); // parcelableVersion
int parcelableSize = source.readInt();
int startPosition = source.dataPosition();
OpenPgpSignatureResult vr = new OpenPgpSignatureResult();
vr.result = source.readInt();
vr.signatureOnly = source.readByte() == 1;
vr.primaryUserId = source.readString();
vr.keyId = source.readLong();
vr.userIds = new ArrayList<String>();
source.readStringList(vr.userIds);
// skip over all fields added in future versions of this parcel
source.setDataPosition(startPosition + parcelableSize);
return vr;
}
public OpenPgpSignatureResult[] newArray(final int size) {
return new OpenPgpSignatureResult[size];
}
};
@Override
public String toString() {
String out = "\nresult: " + result;
out += "\nprimaryUserId: " + primaryUserId;
out += "\nuserIds: " + userIds;
out += "\nsignatureOnly: " + signatureOnly;
out += "\nkeyId: " + OpenPgpUtils.convertKeyIdToHex(keyId);
return out;
}
}

View file

@ -0,0 +1,378 @@
/*
* Copyright (C) 2014-2015 Dominik Schürmann <dominik@dominikschuermann.de>
*
* 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.util;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import org.openintents.openpgp.IOpenPgpService2;
import org.openintents.openpgp.OpenPgpError;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.atomic.AtomicInteger;
public class OpenPgpApi {
public static final String TAG = "OpenPgp API";
public static final String SERVICE_INTENT_2 = "org.openintents.openpgp.IOpenPgpService2";
/**
* see CHANGELOG.md
*/
public static final int API_VERSION = 10;
/**
* General extras
* --------------
*
* required extras:
* int EXTRA_API_VERSION (always required)
*
* returned extras:
* int RESULT_CODE (RESULT_CODE_ERROR, RESULT_CODE_SUCCESS or RESULT_CODE_USER_INTERACTION_REQUIRED)
* OpenPgpError RESULT_ERROR (if RESULT_CODE == RESULT_CODE_ERROR)
* PendingIntent RESULT_INTENT (if RESULT_CODE == RESULT_CODE_USER_INTERACTION_REQUIRED)
*/
/**
* DEPRECATED
* Same as ACTION_CLEARTEXT_SIGN
* <p/>
* optional extras:
* boolean EXTRA_REQUEST_ASCII_ARMOR (DEPRECATED: this makes no sense here)
* char[] EXTRA_PASSPHRASE (key passphrase)
*/
public static final String ACTION_SIGN = "org.openintents.openpgp.action.SIGN";
/**
* Sign text resulting in a cleartext signature
* Some magic pre-processing of the text is done to convert it to a format usable for
* cleartext signatures per RFC 4880 before the text is actually signed:
* - end cleartext with newline
* - remove whitespaces on line endings
* <p/>
* required extras:
* long EXTRA_SIGN_KEY_ID (key id of signing key)
* <p/>
* optional extras:
* char[] EXTRA_PASSPHRASE (key passphrase)
*/
public static final String ACTION_CLEARTEXT_SIGN = "org.openintents.openpgp.action.CLEARTEXT_SIGN";
/**
* Sign text or binary data resulting in a detached signature.
* No OutputStream necessary for ACTION_DETACHED_SIGN (No magic pre-processing like in ACTION_CLEARTEXT_SIGN)!
* The detached signature is returned separately in RESULT_DETACHED_SIGNATURE.
* <p/>
* required extras:
* long EXTRA_SIGN_KEY_ID (key id of signing key)
* <p/>
* optional extras:
* boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for detached signature)
* char[] EXTRA_PASSPHRASE (key passphrase)
* <p/>
* returned extras:
* byte[] RESULT_DETACHED_SIGNATURE
*/
public static final String ACTION_DETACHED_SIGN = "org.openintents.openpgp.action.DETACHED_SIGN";
/**
* Encrypt
* <p/>
* required extras:
* String[] EXTRA_USER_IDS (=emails of recipients, if more than one key has a user_id, a PendingIntent is returned via RESULT_INTENT)
* or
* long[] EXTRA_KEY_IDS
* <p/>
* optional extras:
* boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for output)
* char[] EXTRA_PASSPHRASE (key passphrase)
* String EXTRA_ORIGINAL_FILENAME (original filename to be encrypted as metadata)
* boolean EXTRA_ENABLE_COMPRESSION (enable ZLIB compression, default ist true)
*/
public static final String ACTION_ENCRYPT = "org.openintents.openpgp.action.ENCRYPT";
/**
* Sign and encrypt
* <p/>
* required extras:
* String[] EXTRA_USER_IDS (=emails of recipients, if more than one key has a user_id, a PendingIntent is returned via RESULT_INTENT)
* or
* long[] EXTRA_KEY_IDS
* <p/>
* optional extras:
* long EXTRA_SIGN_KEY_ID (key id of signing key)
* boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for output)
* char[] EXTRA_PASSPHRASE (key passphrase)
* String EXTRA_ORIGINAL_FILENAME (original filename to be encrypted as metadata)
* boolean EXTRA_ENABLE_COMPRESSION (enable ZLIB compression, default ist true)
*/
public static final String ACTION_SIGN_AND_ENCRYPT = "org.openintents.openpgp.action.SIGN_AND_ENCRYPT";
/**
* Decrypts and verifies given input stream. This methods handles encrypted-only, signed-and-encrypted,
* and also signed-only input.
* OutputStream is optional, e.g., for verifying detached signatures!
* <p/>
* If OpenPgpSignatureResult.getResult() == OpenPgpSignatureResult.RESULT_KEY_MISSING
* in addition a PendingIntent is returned via RESULT_INTENT to download missing keys.
* On all other status, in addition a PendingIntent is returned via RESULT_INTENT to open
* the key view in OpenKeychain.
* <p/>
* optional extras:
* byte[] EXTRA_DETACHED_SIGNATURE (detached signature)
* <p/>
* returned extras:
* OpenPgpSignatureResult RESULT_SIGNATURE
* OpenPgpDecryptionResult RESULT_DECRYPTION
* OpenPgpDecryptMetadata RESULT_METADATA
* String RESULT_CHARSET (charset which was specified in the headers of ascii armored input, if any)
*/
public static final String ACTION_DECRYPT_VERIFY = "org.openintents.openpgp.action.DECRYPT_VERIFY";
/**
* Decrypts the header of an encrypted file to retrieve metadata such as original filename.
* <p/>
* This does not decrypt the actual content of the file.
* <p/>
* returned extras:
* OpenPgpDecryptMetadata RESULT_METADATA
* String RESULT_CHARSET (charset which was specified in the headers of ascii armored input, if any)
*/
public static final String ACTION_DECRYPT_METADATA = "org.openintents.openpgp.action.DECRYPT_METADATA";
/**
* Select key id for signing
* <p/>
* optional extras:
* String EXTRA_USER_ID
* <p/>
* returned extras:
* long EXTRA_SIGN_KEY_ID
*/
public static final String ACTION_GET_SIGN_KEY_ID = "org.openintents.openpgp.action.GET_SIGN_KEY_ID";
/**
* Get key ids based on given user ids (=emails)
* <p/>
* required extras:
* String[] EXTRA_USER_IDS
* <p/>
* returned extras:
* long[] RESULT_KEY_IDS
*/
public static final String ACTION_GET_KEY_IDS = "org.openintents.openpgp.action.GET_KEY_IDS";
/**
* This action returns RESULT_CODE_SUCCESS if the OpenPGP Provider already has the key
* corresponding to the given key id in its database.
* <p/>
* It returns RESULT_CODE_USER_INTERACTION_REQUIRED if the Provider does not have the key.
* The PendingIntent from RESULT_INTENT can be used to retrieve those from a keyserver.
* <p/>
* If an Output stream has been defined the whole public key is returned.
* required extras:
* long EXTRA_KEY_ID
* <p/>
* optional extras:
* String EXTRA_REQUEST_ASCII_ARMOR (request that the returned key is encoded in ASCII Armor)
*
*/
public static final String ACTION_GET_KEY = "org.openintents.openpgp.action.GET_KEY";
/* Intent extras */
public static final String EXTRA_API_VERSION = "api_version";
// DEPRECATED!!!
public static final String EXTRA_ACCOUNT_NAME = "account_name";
// ACTION_DETACHED_SIGN, ENCRYPT, SIGN_AND_ENCRYPT, DECRYPT_VERIFY
// request ASCII Armor for output
// OpenPGP Radix-64, 33 percent overhead compared to binary, see http://tools.ietf.org/html/rfc4880#page-53)
public static final String EXTRA_REQUEST_ASCII_ARMOR = "ascii_armor";
// ACTION_DETACHED_SIGN
public static final String RESULT_DETACHED_SIGNATURE = "detached_signature";
public static final String RESULT_MICALG = "micalg";
// ENCRYPT, SIGN_AND_ENCRYPT
public static final String EXTRA_USER_IDS = "user_ids";
public static final String EXTRA_KEY_IDS = "key_ids";
public static final String EXTRA_SIGN_KEY_ID = "sign_key_id";
// optional extras:
public static final String EXTRA_PASSPHRASE = "passphrase";
public static final String EXTRA_ORIGINAL_FILENAME = "original_filename";
public static final String EXTRA_ENABLE_COMPRESSION = "enable_compression";
// GET_SIGN_KEY_ID
public static final String EXTRA_USER_ID = "user_id";
// GET_KEY
public static final String EXTRA_KEY_ID = "key_id";
public static final String RESULT_KEY_IDS = "key_ids";
/* Service Intent returns */
public static final String RESULT_CODE = "result_code";
// get actual error object from RESULT_ERROR
public static final int RESULT_CODE_ERROR = 0;
// success!
public static final int RESULT_CODE_SUCCESS = 1;
// get PendingIntent from RESULT_INTENT, start PendingIntent with startIntentSenderForResult,
// and execute service method again in onActivityResult
public static final int RESULT_CODE_USER_INTERACTION_REQUIRED = 2;
public static final String RESULT_ERROR = "error";
public static final String RESULT_INTENT = "intent";
// DECRYPT_VERIFY
public static final String EXTRA_DETACHED_SIGNATURE = "detached_signature";
public static final String RESULT_SIGNATURE = "signature";
public static final String RESULT_DECRYPTION = "decryption";
public static final String RESULT_METADATA = "metadata";
// This will be the charset which was specified in the headers of ascii armored input, if any
public static final String RESULT_CHARSET = "charset";
// INTERNAL, should not be used
public static final String EXTRA_CALL_UUID1 = "call_uuid1";
public static final String EXTRA_CALL_UUID2 = "call_uuid2";
IOpenPgpService2 mService;
Context mContext;
final AtomicInteger mPipeIdGen = new AtomicInteger();
public OpenPgpApi(Context context, IOpenPgpService2 service) {
this.mContext = context;
this.mService = service;
}
public interface IOpenPgpCallback {
void onReturn(final Intent result);
}
private class OpenPgpAsyncTask extends AsyncTask<Void, Integer, Intent> {
Intent data;
InputStream is;
OutputStream os;
IOpenPgpCallback callback;
private OpenPgpAsyncTask(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) {
this.data = data;
this.is = is;
this.os = os;
this.callback = callback;
}
@Override
protected Intent doInBackground(Void... unused) {
return executeApi(data, is, os);
}
protected void onPostExecute(Intent result) {
callback.onReturn(result);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void executeApiAsync(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) {
OpenPgpAsyncTask task = new OpenPgpAsyncTask(data, is, os, callback);
// don't serialize async tasks!
// http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
} else {
task.execute((Void[]) null);
}
}
/**
* InputStream and OutputStreams are always closed after operating on them!
*/
public Intent executeApi(Intent data, InputStream is, OutputStream os) {
ParcelFileDescriptor input = null;
ParcelFileDescriptor output = null;
try {
// always send version from client
data.putExtra(EXTRA_API_VERSION, OpenPgpApi.API_VERSION);
Intent result;
if (is != null) {
input = ParcelFileDescriptorUtil.pipeFrom(is);
}
Thread pumpThread =null;
int outputPipeId = 0;
if (os != null) {
outputPipeId = mPipeIdGen.incrementAndGet();
output = mService.createOutputPipe(outputPipeId);
pumpThread = ParcelFileDescriptorUtil.pipeTo(os, output);
}
// blocks until result is ready
result = mService.execute(data, input, outputPipeId);
// set class loader to current context to allow unparcelling
// of OpenPgpError and OpenPgpSignatureResult
// http://stackoverflow.com/a/3806769
result.setExtrasClassLoader(mContext.getClassLoader());
//wait for ALL data being pumped from remote side
if (pumpThread != null) {
pumpThread.join();
}
return result;
} catch (Exception e) {
Log.e(OpenPgpApi.TAG, "Exception in executeApi call", e);
Intent result = new Intent();
result.putExtra(RESULT_CODE, RESULT_CODE_ERROR);
result.putExtra(RESULT_ERROR,
new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage()));
return result;
} finally {
// close() is required to halt the TransferThread
if (output != null) {
try {
output.close();
} catch (IOException e) {
Log.e(OpenPgpApi.TAG, "IOException when closing ParcelFileDescriptor!", e);
}
}
if (input != null) {
try {
input.close();
} catch (IOException e) {
Log.e(OpenPgpApi.TAG, "IOException when closing ParcelFileDescriptor!", e);
}
}
}
}
}

View file

@ -0,0 +1,327 @@
/*
* Copyright (C) 2014-2015 Dominik Schürmann <dominik@dominikschuermann.de>
*
* 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.util;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.preference.DialogPreference;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.TextView;
import org.openintents.openpgp.R;
import java.util.ArrayList;
import java.util.List;
/**
* Does not extend ListPreference, but is very similar to it!
* http://grepcode.com/file_/repository.grepcode.com/java/ext/com.google.android/android/4.4_r1/android/preference/ListPreference.java/?v=source
*/
public class OpenPgpAppPreference extends DialogPreference {
private static final String OPENKEYCHAIN_PACKAGE = "org.sufficientlysecure.keychain";
private static final String MARKET_INTENT_URI_BASE = "market://details?id=%s";
private static final Intent MARKET_INTENT = new Intent(Intent.ACTION_VIEW, Uri.parse(
String.format(MARKET_INTENT_URI_BASE, OPENKEYCHAIN_PACKAGE)));
private static final ArrayList<String> PROVIDER_BLACKLIST = new ArrayList<String>();
static {
// Unfortunately, the current released version of APG includes a broken version of the API
PROVIDER_BLACKLIST.add("org.thialfihar.android.apg");
}
private ArrayList<OpenPgpProviderEntry> mLegacyList = new ArrayList<>();
private ArrayList<OpenPgpProviderEntry> mList = new ArrayList<>();
private String mSelectedPackage;
public OpenPgpAppPreference(Context context, AttributeSet attrs) {
super(context, attrs);
populateAppList();
}
public OpenPgpAppPreference(Context context) {
this(context, null);
}
/**
* Public method to add new entries for legacy applications
*
* @param packageName
* @param simpleName
* @param icon
*/
public void addLegacyProvider(int position, String packageName, String simpleName, Drawable icon) {
mLegacyList.add(position, new OpenPgpProviderEntry(packageName, simpleName, icon));
}
@Override
protected void onPrepareDialogBuilder(Builder builder) {
// do again, maybe an app has now been installed
populateAppList();
// Init ArrayAdapter with OpenPGP Providers
ListAdapter adapter = new ArrayAdapter<OpenPgpProviderEntry>(getContext(),
android.R.layout.select_dialog_singlechoice, android.R.id.text1, mList) {
public View getView(int position, View convertView, ViewGroup parent) {
// User super class to create the View
View v = super.getView(position, convertView, parent);
TextView tv = (TextView) v.findViewById(android.R.id.text1);
// Put the image on the TextView
tv.setCompoundDrawablesWithIntrinsicBounds(mList.get(position).icon, null,
null, null);
// Add margin between image and text (support various screen densities)
int dp10 = (int) (10 * getContext().getResources().getDisplayMetrics().density + 0.5f);
tv.setCompoundDrawablePadding(dp10);
return v;
}
};
builder.setSingleChoiceItems(adapter, getIndexOfProviderList(mSelectedPackage),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
OpenPgpProviderEntry entry = mList.get(which);
if (entry.intent != null) {
/*
* Intents are called as activity
*
* Current approach is to assume the user installed the app.
* If he does not, the selected package is not valid.
*
* However applications should always consider this could happen,
* as the user might remove the currently used OpenPGP app.
*/
getContext().startActivity(entry.intent);
return;
}
mSelectedPackage = entry.packageName;
/*
* Clicking on an item simulates the positive button click, and dismisses
* the dialog.
*/
OpenPgpAppPreference.this.onClick(dialog, DialogInterface.BUTTON_POSITIVE);
dialog.dismiss();
}
});
/*
* The typical interaction for list-based dialogs is to have click-on-an-item dismiss the
* dialog instead of the user having to press 'Ok'.
*/
builder.setPositiveButton(null, null);
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult && (mSelectedPackage != null)) {
save();
}
}
private void save() {
// Give the client a chance to ignore this change if they deem it
// invalid
if (!callChangeListener(mSelectedPackage)) {
// They don't want the value to be set
return;
}
setAndPersist(mSelectedPackage);
}
private void setAndPersist(String packageName) {
mSelectedPackage = packageName;
// Save to persistent storage (this method will make sure this
// preference should be persistent, along with other useful checks)
persistString(mSelectedPackage);
// Data has changed, notify so UI can be refreshed!
notifyChanged();
// also update summary with selected provider
updateSummary(mSelectedPackage);
}
private void updateSummary(String packageName) {
String summary = getEntryByValue(packageName);
setSummary(summary);
}
@Override
public CharSequence getSummary() {
return getEntryByValue(mSelectedPackage);
}
private int getIndexOfProviderList(String packageName) {
for (OpenPgpProviderEntry app : mList) {
if (app.packageName.equals(packageName)) {
return mList.indexOf(app);
}
}
// default is "none"
return 0;
}
/**
* Public API
*/
public String getEntry() {
return getEntryByValue(mSelectedPackage);
}
/**
* Public API
*/
public String getValue() {
return mSelectedPackage;
}
/**
* Public API
*/
public void setValue(String packageName) {
setAndPersist(packageName);
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getString(index);
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
if (restoreValue) {
// Restore state
mSelectedPackage = getPersistedString(mSelectedPackage);
updateSummary(mSelectedPackage);
} else {
String value = (String) defaultValue;
setAndPersist(value);
updateSummary(value);
}
}
public String getEntryByValue(String packageName) {
for (OpenPgpProviderEntry app : mList) {
if (app.packageName.equals(packageName) && app.intent == null) {
return app.simpleName;
}
}
return getContext().getString(R.string.openpgp_list_preference_none);
}
private void populateAppList() {
mList.clear();
// add "none"-entry
mList.add(0, new OpenPgpProviderEntry("",
getContext().getString(R.string.openpgp_list_preference_none),
getContext().getResources().getDrawable(R.drawable.ic_action_cancel_launchersize)));
// add all additional (legacy) providers
mList.addAll(mLegacyList);
// search for OpenPGP providers...
ArrayList<OpenPgpProviderEntry> providerList = new ArrayList<>();
Intent intent = new Intent(OpenPgpApi.SERVICE_INTENT_2);
List<ResolveInfo> resInfo = getContext().getPackageManager().queryIntentServices(intent, 0);
if (!resInfo.isEmpty()) {
for (ResolveInfo resolveInfo : resInfo) {
if (resolveInfo.serviceInfo == null)
continue;
String packageName = resolveInfo.serviceInfo.packageName;
String simpleName = String.valueOf(resolveInfo.serviceInfo.loadLabel(getContext()
.getPackageManager()));
Drawable icon = resolveInfo.serviceInfo.loadIcon(getContext().getPackageManager());
if (!PROVIDER_BLACKLIST.contains(packageName)) {
providerList.add(new OpenPgpProviderEntry(packageName, simpleName, icon));
}
}
}
if (providerList.isEmpty()) {
// add install links if provider list is empty
resInfo = getContext().getPackageManager().queryIntentActivities
(MARKET_INTENT, 0);
for (ResolveInfo resolveInfo : resInfo) {
Intent marketIntent = new Intent(MARKET_INTENT);
marketIntent.setPackage(resolveInfo.activityInfo.packageName);
Drawable icon = resolveInfo.activityInfo.loadIcon(getContext().getPackageManager());
String marketName = String.valueOf(resolveInfo.activityInfo.applicationInfo
.loadLabel(getContext().getPackageManager()));
String simpleName = String.format(getContext().getString(R.string
.openpgp_install_openkeychain_via), marketName);
mList.add(new OpenPgpProviderEntry(OPENKEYCHAIN_PACKAGE, simpleName,
icon, marketIntent));
}
} else {
// add provider
mList.addAll(providerList);
}
}
private static class OpenPgpProviderEntry {
private String packageName;
private String simpleName;
private Drawable icon;
private Intent intent;
public OpenPgpProviderEntry(String packageName, String simpleName, Drawable icon) {
this.packageName = packageName;
this.simpleName = simpleName;
this.icon = icon;
}
public OpenPgpProviderEntry(String packageName, String simpleName, Drawable icon, Intent intent) {
this(packageName, simpleName, icon);
this.intent = intent;
}
@Override
public String toString() {
return simpleName;
}
}
}

View file

@ -0,0 +1,293 @@
/*
* Copyright (C) 2015 Dominik Schürmann <dominik@dominikschuermann.de>
*
* 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.util;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.res.TypedArray;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.Preference;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import org.openintents.openpgp.IOpenPgpService2;
import org.openintents.openpgp.OpenPgpError;
import org.openintents.openpgp.R;
public class OpenPgpKeyPreference extends Preference {
private long mKeyId;
private String mOpenPgpProvider;
private OpenPgpServiceConnection mServiceConnection;
private String mDefaultUserId;
public static final int REQUEST_CODE_KEY_PREFERENCE = 9999;
private static final int NO_KEY = 0;
public OpenPgpKeyPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public CharSequence getSummary() {
return (mKeyId == NO_KEY) ? getContext().getString(R.string.openpgp_no_key_selected)
: getContext().getString(R.string.openpgp_key_selected);
}
private void updateEnabled() {
if (TextUtils.isEmpty(mOpenPgpProvider)) {
setEnabled(false);
} else {
setEnabled(true);
}
}
public void setOpenPgpProvider(String packageName) {
mOpenPgpProvider = packageName;
updateEnabled();
}
public void setDefaultUserId(String userId) {
mDefaultUserId = userId;
}
@Override
protected void onClick() {
// bind to service
mServiceConnection = new OpenPgpServiceConnection(
getContext().getApplicationContext(),
mOpenPgpProvider,
new OpenPgpServiceConnection.OnBound() {
@Override
public void onBound(IOpenPgpService2 service) {
getSignKeyId(new Intent());
}
@Override
public void onError(Exception e) {
Log.e(OpenPgpApi.TAG, "exception on binding!", e);
}
}
);
mServiceConnection.bindToService();
}
private void getSignKeyId(Intent data) {
data.setAction(OpenPgpApi.ACTION_GET_SIGN_KEY_ID);
data.putExtra(OpenPgpApi.EXTRA_USER_ID, mDefaultUserId);
OpenPgpApi api = new OpenPgpApi(getContext(), mServiceConnection.getService());
api.executeApiAsync(data, null, null, new MyCallback(REQUEST_CODE_KEY_PREFERENCE));
}
private class MyCallback implements OpenPgpApi.IOpenPgpCallback {
int requestCode;
private MyCallback(int requestCode) {
this.requestCode = requestCode;
}
@Override
public void onReturn(Intent result) {
switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) {
case OpenPgpApi.RESULT_CODE_SUCCESS: {
long keyId = result.getLongExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, NO_KEY);
save(keyId);
break;
}
case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED: {
PendingIntent pi = result.getParcelableExtra(OpenPgpApi.RESULT_INTENT);
try {
Activity act = (Activity) getContext();
act.startIntentSenderFromChild(
act, pi.getIntentSender(),
requestCode, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.e(OpenPgpApi.TAG, "SendIntentException", e);
}
break;
}
case OpenPgpApi.RESULT_CODE_ERROR: {
OpenPgpError error = result.getParcelableExtra(OpenPgpApi.RESULT_ERROR);
Log.e(OpenPgpApi.TAG, "RESULT_CODE_ERROR: " + error.getMessage());
break;
}
}
}
}
private void save(long newValue) {
// Give the client a chance to ignore this change if they deem it
// invalid
if (!callChangeListener(newValue)) {
// They don't want the value to be set
return;
}
setAndPersist(newValue);
}
/**
* Public API
*/
public void setValue(long keyId) {
setAndPersist(keyId);
}
/**
* Public API
*/
public long getValue() {
return mKeyId;
}
private void setAndPersist(long newValue) {
mKeyId = newValue;
// Save to persistent storage (this method will make sure this
// preference should be persistent, along with other useful checks)
persistLong(mKeyId);
// Data has changed, notify so UI can be refreshed!
notifyChanged();
// also update summary
setSummary(getSummary());
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
// This preference type's value type is Long, so we read the default
// value from the attributes as an Integer.
return (long) a.getInteger(index, NO_KEY);
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
if (restoreValue) {
// Restore state
mKeyId = getPersistedLong(mKeyId);
} else {
// Set state
long value = (Long) defaultValue;
setAndPersist(value);
}
}
@Override
protected Parcelable onSaveInstanceState() {
/*
* Suppose a client uses this preference type without persisting. We
* must save the instance state so it is able to, for example, survive
* orientation changes.
*/
final Parcelable superState = super.onSaveInstanceState();
if (isPersistent()) {
// No need to save instance state since it's persistent
return superState;
}
// Save the instance state
final SavedState myState = new SavedState(superState);
myState.keyId = mKeyId;
myState.openPgpProvider = mOpenPgpProvider;
myState.defaultUserId = mDefaultUserId;
return myState;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (!state.getClass().equals(SavedState.class)) {
// Didn't save state for us in onSaveInstanceState
super.onRestoreInstanceState(state);
return;
}
// Restore the instance state
SavedState myState = (SavedState) state;
super.onRestoreInstanceState(myState.getSuperState());
mKeyId = myState.keyId;
mOpenPgpProvider = myState.openPgpProvider;
mDefaultUserId = myState.defaultUserId;
notifyChanged();
}
/**
* SavedState, a subclass of {@link BaseSavedState}, will store the state
* of MyPreference, a subclass of Preference.
* <p/>
* It is important to always call through to super methods.
*/
private static class SavedState extends BaseSavedState {
long keyId;
String openPgpProvider;
String defaultUserId;
public SavedState(Parcel source) {
super(source);
keyId = source.readInt();
openPgpProvider = source.readString();
defaultUserId = source.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeLong(keyId);
dest.writeString(openPgpProvider);
dest.writeString(defaultUserId);
}
public SavedState(Parcelable superState) {
super(superState);
}
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
public boolean handleOnActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_KEY_PREFERENCE && resultCode == Activity.RESULT_OK) {
getSignKeyId(data);
return true;
} else {
return false;
}
}
}

View file

@ -0,0 +1,124 @@
/*
* Copyright (C) 2014-2015 Dominik Schürmann <dominik@dominikschuermann.de>
*
* 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.util;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import org.openintents.openpgp.IOpenPgpService2;
public class OpenPgpServiceConnection {
// callback interface
public interface OnBound {
public void onBound(IOpenPgpService2 service);
public void onError(Exception e);
}
private Context mApplicationContext;
private IOpenPgpService2 mService;
private String mProviderPackageName;
private OnBound mOnBoundListener;
/**
* Create new connection
*
* @param context
* @param providerPackageName specify package name of OpenPGP provider,
* e.g., "org.sufficientlysecure.keychain"
*/
public OpenPgpServiceConnection(Context context, String providerPackageName) {
this.mApplicationContext = context.getApplicationContext();
this.mProviderPackageName = providerPackageName;
}
/**
* Create new connection with callback
*
* @param context
* @param providerPackageName specify package name of OpenPGP provider,
* e.g., "org.sufficientlysecure.keychain"
* @param onBoundListener callback, executed when connection to service has been established
*/
public OpenPgpServiceConnection(Context context, String providerPackageName,
OnBound onBoundListener) {
this(context, providerPackageName);
this.mOnBoundListener = onBoundListener;
}
public IOpenPgpService2 getService() {
return mService;
}
public boolean isBound() {
return (mService != null);
}
private ServiceConnection mServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
mService = IOpenPgpService2.Stub.asInterface(service);
if (mOnBoundListener != null) {
mOnBoundListener.onBound(mService);
}
}
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
};
/**
* If not already bound, bind to service!
*
* @return
*/
public void bindToService() {
// if not already bound...
if (mService == null) {
try {
Intent serviceIntent = new Intent(OpenPgpApi.SERVICE_INTENT_2);
// NOTE: setPackage is very important to restrict the intent to this provider only!
serviceIntent.setPackage(mProviderPackageName);
boolean connect = mApplicationContext.bindService(serviceIntent, mServiceConnection,
Context.BIND_AUTO_CREATE);
if (!connect) {
throw new Exception("bindService() returned false!");
}
} catch (Exception e) {
if (mOnBoundListener != null) {
mOnBoundListener.onError(e);
}
}
} else {
// already bound, but also inform client about it with callback
if (mOnBoundListener != null) {
mOnBoundListener.onBound(mService);
}
}
}
public void unbindFromService() {
mApplicationContext.unbindService(mServiceConnection);
}
}

View file

@ -0,0 +1,127 @@
/*
* Copyright (C) 2014-2015 Dominik Schürmann <dominik@dominikschuermann.de>
*
* 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.util;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.text.TextUtils;
public class OpenPgpUtils {
public static final Pattern PGP_MESSAGE = Pattern.compile(
".*?(-----BEGIN PGP MESSAGE-----.*?-----END PGP MESSAGE-----).*",
Pattern.DOTALL);
public static final Pattern PGP_SIGNED_MESSAGE = Pattern.compile(
".*?(-----BEGIN PGP SIGNED MESSAGE-----.*?-----BEGIN PGP SIGNATURE-----.*?-----END PGP SIGNATURE-----).*",
Pattern.DOTALL);
public static final int PARSE_RESULT_NO_PGP = -1;
public static final int PARSE_RESULT_MESSAGE = 0;
public static final int PARSE_RESULT_SIGNED_MESSAGE = 1;
public static int parseMessage(String message) {
Matcher matcherSigned = PGP_SIGNED_MESSAGE.matcher(message);
Matcher matcherMessage = PGP_MESSAGE.matcher(message);
if (matcherMessage.matches()) {
return PARSE_RESULT_MESSAGE;
} else if (matcherSigned.matches()) {
return PARSE_RESULT_SIGNED_MESSAGE;
} else {
return PARSE_RESULT_NO_PGP;
}
}
public static boolean isAvailable(Context context) {
Intent intent = new Intent(OpenPgpApi.SERVICE_INTENT_2);
List<ResolveInfo> resInfo = context.getPackageManager().queryIntentServices(intent, 0);
return !resInfo.isEmpty();
}
public static String convertKeyIdToHex(long keyId) {
return "0x" + convertKeyIdToHex32bit(keyId >> 32) + convertKeyIdToHex32bit(keyId);
}
private static String convertKeyIdToHex32bit(long keyId) {
String hexString = Long.toHexString(keyId & 0xffffffffL).toLowerCase(Locale.ENGLISH);
while (hexString.length() < 8) {
hexString = "0" + hexString;
}
return hexString;
}
private static final Pattern USER_ID_PATTERN = Pattern.compile("^(.*?)(?: \\((.*)\\))?(?: <(.*)>)?$");
/**
* Splits userId string into naming part, email part, and comment part
* <p/>
* User ID matching:
* http://fiddle.re/t4p6f
*
* @param userId
* @return theParsedUserInfo
*/
public static UserId splitUserId(final String userId) {
if (!TextUtils.isEmpty(userId)) {
final Matcher matcher = USER_ID_PATTERN.matcher(userId);
if (matcher.matches()) {
return new UserId(matcher.group(1), matcher.group(3), matcher.group(2));
}
}
return new UserId(null, null, null);
}
/**
* Returns a composed user id. Returns null if name is null!
*
* @param name
* @param email
* @param comment
* @return
*/
public static String createUserId(UserId userId) {
String userIdString = userId.name; // consider name a required value
if (userIdString != null && !TextUtils.isEmpty(userId.comment)) {
userIdString += " (" + userId.comment + ")";
}
if (userIdString != null && !TextUtils.isEmpty(userId.email)) {
userIdString += " <" + userId.email + ">";
}
return userIdString;
}
public static class UserId {
public final String name;
public final String email;
public final String comment;
public UserId(String name, String email, String comment) {
this.name = name;
this.email = email;
this.comment = comment;
}
}
}

View file

@ -0,0 +1,87 @@
/*
* Copyright (C) 2014-2015 Dominik Schürmann <dominik@dominikschuermann.de>
* 2013 Florian Schmaus <flo@geekplace.eu>
*
* 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.util;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ParcelFileDescriptorUtil {
public static ParcelFileDescriptor pipeFrom(InputStream inputStream)
throws IOException {
ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
ParcelFileDescriptor readSide = pipe[0];
ParcelFileDescriptor writeSide = pipe[1];
new TransferThread(inputStream, new ParcelFileDescriptor.AutoCloseOutputStream(writeSide))
.start();
return readSide;
}
public static TransferThread pipeTo(OutputStream outputStream, ParcelFileDescriptor output)
throws IOException {
TransferThread t = new TransferThread(new ParcelFileDescriptor.AutoCloseInputStream(output), outputStream);
t.start();
return t;
}
static class TransferThread extends Thread {
final InputStream mIn;
final OutputStream mOut;
TransferThread(InputStream in, OutputStream out) {
super("IPC Transfer Thread");
mIn = in;
mOut = out;
setDaemon(true);
}
@Override
public void run() {
byte[] buf = new byte[4096];
int len;
try {
while ((len = mIn.read(buf)) > 0) {
mOut.write(buf, 0, len);
}
} catch (IOException e) {
Log.e(OpenPgpApi.TAG, "IOException when writing to out", e);
} finally {
try {
mIn.close();
} catch (IOException ignored) {
}
try {
mOut.close();
} catch (IOException ignored) {
}
}
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

View file

@ -0,0 +1,2 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources/>

View file

@ -0,0 +1,2 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources/>

View file

@ -0,0 +1,5 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources>
<string name="openpgp_list_preference_none">Žádný</string>
<string name="openpgp_install_openkeychain_via">Instalovat OpenKeychain pomocí %s</string>
</resources>

View file

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources>
<string name="openpgp_list_preference_none">Keine Auswahl</string>
<string name="openpgp_install_openkeychain_via">Installiere OpenKeychain über %s</string>
<string name="openpgp_no_key_selected">Kein Schlüssel ausgewählt</string>
<string name="openpgp_key_selected">Schlüssel wurde ausgewählt</string>
</resources>

View file

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources>
<string name="openpgp_list_preference_none">Ninguno</string>
<string name="openpgp_install_openkeychain_via">Instalar OpenKeychain mediante %s</string>
<string name="openpgp_no_key_selected">No se seleccionó clave</string>
<string name="openpgp_key_selected">Se ha seleccionado clave</string>
</resources>

View file

@ -0,0 +1,2 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources/>

View file

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources>
<string name="openpgp_list_preference_none">Ezer ez</string>
<string name="openpgp_install_openkeychain_via">Ezarri OpenKeychain %s bidez</string>
<string name="openpgp_no_key_selected">Ez da giltzarik hautatu</string>
<string name="openpgp_key_selected">Giltza hautatu da</string>
</resources>

View file

@ -0,0 +1,2 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources/>

View file

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources>
<string name="openpgp_list_preference_none">Aucun</string>
<string name="openpgp_install_openkeychain_via">Installer OpenKeychain par %s</string>
<string name="openpgp_no_key_selected">Aucune clef sélectionnée</string>
<string name="openpgp_key_selected">La clef a été sélectionnée</string>
</resources>

View file

@ -0,0 +1,2 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources/>

View file

@ -0,0 +1,5 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources>
<string name="openpgp_list_preference_none">Nessuno</string>
<string name="openpgp_install_openkeychain_via">Installa OpenKeychain via %s</string>
</resources>

View file

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources>
<string name="openpgp_list_preference_none">無し</string>
<string name="openpgp_install_openkeychain_via">%s 経由でOpenKeychainをインストール</string>
<string name="openpgp_no_key_selected">鍵が選択されていません</string>
<string name="openpgp_key_selected">鍵は選択済みです</string>
</resources>

View file

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources>
<string name="openpgp_list_preference_none">Geen</string>
<string name="openpgp_install_openkeychain_via">Installeer OpenKeychain via %s</string>
<string name="openpgp_no_key_selected">Geen sleutel geselecteerd</string>
<string name="openpgp_key_selected">Sleutel is geselecteerd</string>
</resources>

View file

@ -0,0 +1,5 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources>
<string name="openpgp_list_preference_none">Brak</string>
<string name="openpgp_install_openkeychain_via">Instaluj OpenKeychain przez %s</string>
</resources>

View file

@ -0,0 +1,2 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources/>

View file

@ -0,0 +1,2 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources/>

View file

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources>
<string name="openpgp_list_preference_none">Нет</string>
<string name="openpgp_install_openkeychain_via">Установить OpenKeychain через %s</string>
<string name="openpgp_no_key_selected">Ключ не выбран</string>
<string name="openpgp_key_selected">Ключ был выбран</string>
</resources>

View file

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources>
<string name="openpgp_list_preference_none">Brez</string>
<string name="openpgp_install_openkeychain_via">Namesti OpenKeychain prek %s</string>
<string name="openpgp_no_key_selected">Izbran ni noben ključ</string>
<string name="openpgp_key_selected">Ključ je bil izbran</string>
</resources>

View file

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources>
<string name="openpgp_list_preference_none">Ништа</string>
<string name="openpgp_install_openkeychain_via">Инсталирај Отворени кључарник преко %s</string>
<string name="openpgp_no_key_selected">Није изабран кључ</string>
<string name="openpgp_key_selected">Кључ је изабран</string>
</resources>

View file

@ -0,0 +1,5 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources>
<string name="openpgp_list_preference_none">Ingen</string>
<string name="openpgp_install_openkeychain_via">Installera OpenKeychain via %s</string>
</resources>

View file

@ -0,0 +1,5 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources>
<string name="openpgp_list_preference_none">Hiç</string>
<string name="openpgp_install_openkeychain_via">%s aracılığıyla OpenKeychain\'i yükle</string>
</resources>

View file

@ -0,0 +1,5 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources>
<string name="openpgp_list_preference_none">Жоден</string>
<string name="openpgp_install_openkeychain_via">Встановити OpenKeychain через %s</string>
</resources>

View file

@ -0,0 +1,4 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources>
<string name="openpgp_list_preference_none"></string>
</resources>

View file

@ -0,0 +1,5 @@
<?xml version='1.0' encoding='UTF-8'?>
<resources>
<string name="openpgp_no_key_selected">尚未选择密钥</string>
<string name="openpgp_key_selected">已经选中密钥</string>
</resources>

View file

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="openpgp_list_preference_none">None</string>
<string name="openpgp_install_openkeychain_via">Install OpenKeychain via %s</string>
<string name="openpgp_no_key_selected">No key selected</string>
<string name="openpgp_key_selected">Key has been selected</string>
</resources>

View file

@ -0,0 +1,2 @@
include ':example'
include ':openpgp-api'

View file

@ -2,3 +2,4 @@ include ':k9mail'
include ':k9mail-library' include ':k9mail-library'
include ':plugins:Android-PullToRefresh:library' include ':plugins:Android-PullToRefresh:library'
include ':plugins:HoloColorPicker' include ':plugins:HoloColorPicker'
include ':plugins:openpgp-api-lib:openpgp-api'