From 6f2333b7d3ff892697e993e4af2053a695f19402 Mon Sep 17 00:00:00 2001 From: senecaso Date: Thu, 6 Oct 2011 15:31:16 +0900 Subject: [PATCH 1/2] -mavenizing the project -moving all org.bouncycastl2.* dependencies to Sponcy Castle instead. This way multiple people dont need to maintain rebased versions of BC --- AndroidManifest.xml | 3 +- pom.xml | 62 +++++++++++++ src/org/thialfihar/android/apg/Apg.java | 87 ++++++++++--------- .../apg/AskForSecretKeyPassPhrase.java | 9 +- .../android/apg/DecryptActivity.java | 6 +- .../android/apg/EditKeyActivity.java | 6 +- .../android/apg/EncryptActivity.java | 10 +-- src/org/thialfihar/android/apg/Id.java | 2 +- .../android/apg/KeyListActivity.java | 6 +- .../thialfihar/android/apg/Preferences.java | 4 +- .../android/apg/PreferencesActivity.java | 4 +- .../android/apg/PublicKeyListActivity.java | 2 +- .../android/apg/provider/Database.java | 10 +-- .../android/apg/ui/widget/KeyEditor.java | 4 +- .../android/apg/ui/widget/SectionView.java | 4 +- 15 files changed, 142 insertions(+), 77 deletions(-) create mode 100644 pom.xml diff --git a/AndroidManifest.xml b/AndroidManifest.xml index 47197a129..8c7dd53fe 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -17,8 +17,7 @@ + android:versionCode="10900" android:versionName="1.0.9 beta 00"> + 4.0.0 + 1.0.9-SNAPSHOT + org.thialfihar.android + apg + apk + APG + + + http://code.google.com/p/android-privacy-guard/ + + + UTF-8 + 1.6_r2 + + + + + com.google.android + android + provided + 1.6_r2 + + + com.madgag + scprov-jdk15 + 1.46.99.4-UNOFFICIAL-ROBERTO-RELEASE-SNAPSHOT + jar + provided + + + + src + test + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + + + com.jayway.maven.plugins.android.generation2 + android-maven-plugin + 3.0.0-alpha-11 + + + ${user.home}/android-sdk-linux_x86/ + 4 + + true + true + + true + + + + diff --git a/src/org/thialfihar/android/apg/Apg.java b/src/org/thialfihar/android/apg/Apg.java index 34c2acc6b..3ec12ced6 100644 --- a/src/org/thialfihar/android/apg/Apg.java +++ b/src/org/thialfihar/android/apg/Apg.java @@ -45,42 +45,42 @@ import java.util.Map; import java.util.Vector; import java.util.regex.Pattern; -import org.bouncycastle2.bcpg.ArmoredInputStream; -import org.bouncycastle2.bcpg.ArmoredOutputStream; -import org.bouncycastle2.bcpg.BCPGOutputStream; -import org.bouncycastle2.bcpg.CompressionAlgorithmTags; -import org.bouncycastle2.bcpg.HashAlgorithmTags; -import org.bouncycastle2.bcpg.SymmetricKeyAlgorithmTags; -import org.bouncycastle2.bcpg.sig.KeyFlags; -import org.bouncycastle2.jce.provider.BouncyCastleProvider; -import org.bouncycastle2.jce.spec.ElGamalParameterSpec; -import org.bouncycastle2.openpgp.PGPCompressedData; -import org.bouncycastle2.openpgp.PGPCompressedDataGenerator; -import org.bouncycastle2.openpgp.PGPEncryptedData; -import org.bouncycastle2.openpgp.PGPEncryptedDataGenerator; -import org.bouncycastle2.openpgp.PGPEncryptedDataList; -import org.bouncycastle2.openpgp.PGPException; -import org.bouncycastle2.openpgp.PGPKeyPair; -import org.bouncycastle2.openpgp.PGPKeyRingGenerator; -import org.bouncycastle2.openpgp.PGPLiteralData; -import org.bouncycastle2.openpgp.PGPLiteralDataGenerator; -import org.bouncycastle2.openpgp.PGPObjectFactory; -import org.bouncycastle2.openpgp.PGPOnePassSignature; -import org.bouncycastle2.openpgp.PGPOnePassSignatureList; -import org.bouncycastle2.openpgp.PGPPBEEncryptedData; -import org.bouncycastle2.openpgp.PGPPrivateKey; -import org.bouncycastle2.openpgp.PGPPublicKey; -import org.bouncycastle2.openpgp.PGPPublicKeyEncryptedData; -import org.bouncycastle2.openpgp.PGPPublicKeyRing; -import org.bouncycastle2.openpgp.PGPSecretKey; -import org.bouncycastle2.openpgp.PGPSecretKeyRing; -import org.bouncycastle2.openpgp.PGPSignature; -import org.bouncycastle2.openpgp.PGPSignatureGenerator; -import org.bouncycastle2.openpgp.PGPSignatureList; -import org.bouncycastle2.openpgp.PGPSignatureSubpacketGenerator; -import org.bouncycastle2.openpgp.PGPSignatureSubpacketVector; -import org.bouncycastle2.openpgp.PGPUtil; -import org.bouncycastle2.openpgp.PGPV3SignatureGenerator; +import org.spongycastle.bcpg.ArmoredInputStream; +import org.spongycastle.bcpg.ArmoredOutputStream; +import org.spongycastle.bcpg.BCPGOutputStream; +import org.spongycastle.bcpg.CompressionAlgorithmTags; +import org.spongycastle.bcpg.HashAlgorithmTags; +import org.spongycastle.bcpg.SymmetricKeyAlgorithmTags; +import org.spongycastle.bcpg.sig.KeyFlags; +import org.spongycastle.jce.provider.BouncyCastleProvider; +import org.spongycastle.jce.spec.ElGamalParameterSpec; +import org.spongycastle.openpgp.PGPCompressedData; +import org.spongycastle.openpgp.PGPCompressedDataGenerator; +import org.spongycastle.openpgp.PGPEncryptedData; +import org.spongycastle.openpgp.PGPEncryptedDataGenerator; +import org.spongycastle.openpgp.PGPEncryptedDataList; +import org.spongycastle.openpgp.PGPException; +import org.spongycastle.openpgp.PGPKeyPair; +import org.spongycastle.openpgp.PGPKeyRingGenerator; +import org.spongycastle.openpgp.PGPLiteralData; +import org.spongycastle.openpgp.PGPLiteralDataGenerator; +import org.spongycastle.openpgp.PGPObjectFactory; +import org.spongycastle.openpgp.PGPOnePassSignature; +import org.spongycastle.openpgp.PGPOnePassSignatureList; +import org.spongycastle.openpgp.PGPPBEEncryptedData; +import org.spongycastle.openpgp.PGPPrivateKey; +import org.spongycastle.openpgp.PGPPublicKey; +import org.spongycastle.openpgp.PGPPublicKeyEncryptedData; +import org.spongycastle.openpgp.PGPPublicKeyRing; +import org.spongycastle.openpgp.PGPSecretKey; +import org.spongycastle.openpgp.PGPSecretKeyRing; +import org.spongycastle.openpgp.PGPSignature; +import org.spongycastle.openpgp.PGPSignatureGenerator; +import org.spongycastle.openpgp.PGPSignatureList; +import org.spongycastle.openpgp.PGPSignatureSubpacketGenerator; +import org.spongycastle.openpgp.PGPSignatureSubpacketVector; +import org.spongycastle.openpgp.PGPUtil; +import org.spongycastle.openpgp.PGPV3SignatureGenerator; import org.thialfihar.android.apg.provider.DataProvider; import org.thialfihar.android.apg.provider.Database; import org.thialfihar.android.apg.provider.KeyRings; @@ -739,6 +739,7 @@ public class Apg { return key.getPublicKey().getCreationTime(); } + @SuppressWarnings("unchecked") public static PGPPublicKey getMasterKey(PGPPublicKeyRing keyRing) { if (keyRing == null) { return null; @@ -752,6 +753,7 @@ public class Apg { return null; } + @SuppressWarnings("unchecked") public static PGPSecretKey getMasterKey(PGPSecretKeyRing keyRing) { if (keyRing == null) { return null; @@ -765,6 +767,7 @@ public class Apg { return null; } + @SuppressWarnings("unchecked") public static Vector getEncryptKeys(PGPPublicKeyRing keyRing) { Vector encryptKeys = new Vector(); @@ -777,6 +780,7 @@ public class Apg { return encryptKeys; } + @SuppressWarnings("unchecked") public static Vector getSigningKeys(PGPSecretKeyRing keyRing) { Vector signingKeys = new Vector(); @@ -884,6 +888,7 @@ public class Apg { return signingKeys.get(0); } + @SuppressWarnings("unchecked") public static String getMainUserId(PGPPublicKey key) { for (String userId : new IterableIterator(key.getUserIDs())) { return userId; @@ -891,6 +896,7 @@ public class Apg { return null; } + @SuppressWarnings("unchecked") public static String getMainUserId(PGPSecretKey key) { for (String userId : new IterableIterator(key.getUserIDs())) { return userId; @@ -914,6 +920,7 @@ public class Apg { return userId; } + @SuppressWarnings("unchecked") public static boolean isEncryptionKey(PGPPublicKey key) { if (!key.isEncryptionKey()) { return false; @@ -958,6 +965,7 @@ public class Apg { return isEncryptionKey(key.getPublicKey()); } + @SuppressWarnings("unchecked") public static boolean isSigningKey(PGPPublicKey key) { if (key.getVersion() <= 3) { return true; @@ -1129,11 +1137,8 @@ public class Apg { if (keyRing == null) { return null; } - try { - return keyRing.getPublicKey(keyId); - } catch (PGPException e) { - return null; - } + + return keyRing.getPublicKey(keyId); } public static Vector getKeyRingIds(int type) { diff --git a/src/org/thialfihar/android/apg/AskForSecretKeyPassPhrase.java b/src/org/thialfihar/android/apg/AskForSecretKeyPassPhrase.java index 829244e0d..dc65ff762 100644 --- a/src/org/thialfihar/android/apg/AskForSecretKeyPassPhrase.java +++ b/src/org/thialfihar/android/apg/AskForSecretKeyPassPhrase.java @@ -16,11 +16,10 @@ package org.thialfihar.android.apg; -import org.bouncycastle2.jce.provider.BouncyCastleProvider; -import org.bouncycastle2.openpgp.PGPException; -import org.bouncycastle2.openpgp.PGPPrivateKey; -import org.bouncycastle2.openpgp.PGPSecretKey; -import org.thialfihar.android.apg.Apg.GeneralException; +import org.spongycastle.jce.provider.BouncyCastleProvider; +import org.spongycastle.openpgp.PGPException; +import org.spongycastle.openpgp.PGPPrivateKey; +import org.spongycastle.openpgp.PGPSecretKey; import android.app.Activity; import android.app.AlertDialog; diff --git a/src/org/thialfihar/android/apg/DecryptActivity.java b/src/org/thialfihar/android/apg/DecryptActivity.java index 576b6d531..22d23087b 100644 --- a/src/org/thialfihar/android/apg/DecryptActivity.java +++ b/src/org/thialfihar/android/apg/DecryptActivity.java @@ -26,9 +26,9 @@ import java.security.Security; import java.security.SignatureException; import java.util.regex.Matcher; -import org.bouncycastle2.jce.provider.BouncyCastleProvider; -import org.bouncycastle2.openpgp.PGPException; -import org.bouncycastle2.openpgp.PGPPublicKeyRing; +import org.spongycastle.jce.provider.BouncyCastleProvider; +import org.spongycastle.openpgp.PGPException; +import org.spongycastle.openpgp.PGPPublicKeyRing; import org.thialfihar.android.apg.provider.DataProvider; import android.app.AlertDialog; diff --git a/src/org/thialfihar/android/apg/EditKeyActivity.java b/src/org/thialfihar/android/apg/EditKeyActivity.java index 4bb8899ca..54007f2bc 100644 --- a/src/org/thialfihar/android/apg/EditKeyActivity.java +++ b/src/org/thialfihar/android/apg/EditKeyActivity.java @@ -22,9 +22,9 @@ import java.security.NoSuchProviderException; import java.security.SignatureException; import java.util.Vector; -import org.bouncycastle2.openpgp.PGPException; -import org.bouncycastle2.openpgp.PGPSecretKey; -import org.bouncycastle2.openpgp.PGPSecretKeyRing; +import org.spongycastle.openpgp.PGPException; +import org.spongycastle.openpgp.PGPSecretKey; +import org.spongycastle.openpgp.PGPSecretKeyRing; import org.thialfihar.android.apg.provider.Database; import org.thialfihar.android.apg.ui.widget.KeyEditor; import org.thialfihar.android.apg.ui.widget.SectionView; diff --git a/src/org/thialfihar/android/apg/EncryptActivity.java b/src/org/thialfihar/android/apg/EncryptActivity.java index 9ba71f570..9c5f77462 100644 --- a/src/org/thialfihar/android/apg/EncryptActivity.java +++ b/src/org/thialfihar/android/apg/EncryptActivity.java @@ -26,11 +26,11 @@ import java.security.NoSuchProviderException; import java.security.SignatureException; import java.util.Vector; -import org.bouncycastle2.openpgp.PGPException; -import org.bouncycastle2.openpgp.PGPPublicKey; -import org.bouncycastle2.openpgp.PGPPublicKeyRing; -import org.bouncycastle2.openpgp.PGPSecretKey; -import org.bouncycastle2.openpgp.PGPSecretKeyRing; +import org.spongycastle.openpgp.PGPException; +import org.spongycastle.openpgp.PGPPublicKey; +import org.spongycastle.openpgp.PGPPublicKeyRing; +import org.spongycastle.openpgp.PGPSecretKey; +import org.spongycastle.openpgp.PGPSecretKeyRing; import org.thialfihar.android.apg.provider.DataProvider; import org.thialfihar.android.apg.utils.Choice; diff --git a/src/org/thialfihar/android/apg/Id.java b/src/org/thialfihar/android/apg/Id.java index ebc1ecf87..1ce53eabd 100644 --- a/src/org/thialfihar/android/apg/Id.java +++ b/src/org/thialfihar/android/apg/Id.java @@ -16,7 +16,7 @@ package org.thialfihar.android.apg; -import org.bouncycastle2.bcpg.CompressionAlgorithmTags; +import org.spongycastle.bcpg.CompressionAlgorithmTags; public final class Id { public static final class menu { diff --git a/src/org/thialfihar/android/apg/KeyListActivity.java b/src/org/thialfihar/android/apg/KeyListActivity.java index 57a7f5de1..585d0259b 100644 --- a/src/org/thialfihar/android/apg/KeyListActivity.java +++ b/src/org/thialfihar/android/apg/KeyListActivity.java @@ -26,9 +26,9 @@ import java.io.InputStream; import java.io.OutputStream; import java.util.Vector; -import org.bouncycastle2.openpgp.PGPException; -import org.bouncycastle2.openpgp.PGPPublicKeyRing; -import org.bouncycastle2.openpgp.PGPSecretKeyRing; +import org.spongycastle.openpgp.PGPException; +import org.spongycastle.openpgp.PGPPublicKeyRing; +import org.spongycastle.openpgp.PGPSecretKeyRing; import org.thialfihar.android.apg.provider.KeyRings; import org.thialfihar.android.apg.provider.Keys; import org.thialfihar.android.apg.provider.UserIds; diff --git a/src/org/thialfihar/android/apg/Preferences.java b/src/org/thialfihar/android/apg/Preferences.java index 36325a126..f1a538282 100644 --- a/src/org/thialfihar/android/apg/Preferences.java +++ b/src/org/thialfihar/android/apg/Preferences.java @@ -2,8 +2,8 @@ package org.thialfihar.android.apg; import java.util.Vector; -import org.bouncycastle2.bcpg.HashAlgorithmTags; -import org.bouncycastle2.openpgp.PGPEncryptedData; +import org.spongycastle.bcpg.HashAlgorithmTags; +import org.spongycastle.openpgp.PGPEncryptedData; import android.content.Context; import android.content.SharedPreferences; diff --git a/src/org/thialfihar/android/apg/PreferencesActivity.java b/src/org/thialfihar/android/apg/PreferencesActivity.java index 0d0d76318..175bc10c8 100644 --- a/src/org/thialfihar/android/apg/PreferencesActivity.java +++ b/src/org/thialfihar/android/apg/PreferencesActivity.java @@ -20,8 +20,8 @@ import java.util.Arrays; import java.util.HashSet; import java.util.Vector; -import org.bouncycastle2.bcpg.HashAlgorithmTags; -import org.bouncycastle2.openpgp.PGPEncryptedData; +import org.spongycastle.bcpg.HashAlgorithmTags; +import org.spongycastle.openpgp.PGPEncryptedData; import org.thialfihar.android.apg.ui.widget.IntegerListPreference; import android.content.Intent; diff --git a/src/org/thialfihar/android/apg/PublicKeyListActivity.java b/src/org/thialfihar/android/apg/PublicKeyListActivity.java index 4cc3b4df9..509a81374 100644 --- a/src/org/thialfihar/android/apg/PublicKeyListActivity.java +++ b/src/org/thialfihar/android/apg/PublicKeyListActivity.java @@ -16,7 +16,7 @@ package org.thialfihar.android.apg; -import org.bouncycastle2.openpgp.PGPPublicKeyRing; +import org.spongycastle.openpgp.PGPPublicKeyRing; import android.content.Intent; import android.os.Bundle; diff --git a/src/org/thialfihar/android/apg/provider/Database.java b/src/org/thialfihar/android/apg/provider/Database.java index 05beb980d..064d90f7f 100644 --- a/src/org/thialfihar/android/apg/provider/Database.java +++ b/src/org/thialfihar/android/apg/provider/Database.java @@ -5,11 +5,11 @@ import java.util.Date; import java.util.HashMap; import java.util.Vector; -import org.bouncycastle2.openpgp.PGPException; -import org.bouncycastle2.openpgp.PGPPublicKey; -import org.bouncycastle2.openpgp.PGPPublicKeyRing; -import org.bouncycastle2.openpgp.PGPSecretKey; -import org.bouncycastle2.openpgp.PGPSecretKeyRing; +import org.spongycastle.openpgp.PGPException; +import org.spongycastle.openpgp.PGPPublicKey; +import org.spongycastle.openpgp.PGPPublicKeyRing; +import org.spongycastle.openpgp.PGPSecretKey; +import org.spongycastle.openpgp.PGPSecretKeyRing; import org.thialfihar.android.apg.Apg; import org.thialfihar.android.apg.Id; import org.thialfihar.android.apg.utils.IterableIterator; diff --git a/src/org/thialfihar/android/apg/ui/widget/KeyEditor.java b/src/org/thialfihar/android/apg/ui/widget/KeyEditor.java index dbdae9def..2266a266b 100644 --- a/src/org/thialfihar/android/apg/ui/widget/KeyEditor.java +++ b/src/org/thialfihar/android/apg/ui/widget/KeyEditor.java @@ -22,8 +22,8 @@ import java.util.Date; import java.util.GregorianCalendar; import java.util.Vector; -import org.bouncycastle2.openpgp.PGPPublicKey; -import org.bouncycastle2.openpgp.PGPSecretKey; +import org.spongycastle.openpgp.PGPPublicKey; +import org.spongycastle.openpgp.PGPSecretKey; import org.thialfihar.android.apg.Apg; import org.thialfihar.android.apg.Id; import org.thialfihar.android.apg.R; diff --git a/src/org/thialfihar/android/apg/ui/widget/SectionView.java b/src/org/thialfihar/android/apg/ui/widget/SectionView.java index 124c1c9da..f726903f7 100644 --- a/src/org/thialfihar/android/apg/ui/widget/SectionView.java +++ b/src/org/thialfihar/android/apg/ui/widget/SectionView.java @@ -22,8 +22,8 @@ import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.util.Vector; -import org.bouncycastle2.openpgp.PGPException; -import org.bouncycastle2.openpgp.PGPSecretKey; +import org.spongycastle.openpgp.PGPException; +import org.spongycastle.openpgp.PGPSecretKey; import org.thialfihar.android.apg.Apg; import org.thialfihar.android.apg.Id; import org.thialfihar.android.apg.R; From debb90409a0a90ce9351c83e42cb72f8935bacb1 Mon Sep 17 00:00:00 2001 From: senecaso Date: Mon, 17 Oct 2011 10:07:37 +0900 Subject: [PATCH 2/2] -implementation of "--send-key" -implementation of "--sign-key" -partial implementation of exchanging/verifying keys via QR Code --- AndroidManifest.xml | 16 + pom.xml | 7 +- res/layout/key_server_export_layout.xml | 42 +++ res/layout/sign_key_layout.xml | 40 +++ res/values/strings.xml | 12 + src/org/thialfihar/android/apg/Apg.java | 184 +++++++----- .../thialfihar/android/apg/BaseActivity.java | 7 + .../thialfihar/android/apg/HkpKeyServer.java | 94 ++++-- src/org/thialfihar/android/apg/Id.java | 12 +- .../android/apg/ImportFromQRCodeActivity.java | 133 ++++++++ .../android/apg/KeyListActivity.java | 7 +- src/org/thialfihar/android/apg/KeyServer.java | 9 + .../android/apg/KeyServerQueryActivity.java | 14 +- .../thialfihar/android/apg/MainActivity.java | 6 + .../android/apg/PublicKeyListActivity.java | 62 +++- .../android/apg/SecretKeyListActivity.java | 13 +- .../android/apg/SendKeyActivity.java | 93 ++++++ .../android/apg/SignKeyActivity.java | 284 ++++++++++++++++++ 18 files changed, 923 insertions(+), 112 deletions(-) create mode 100644 res/layout/key_server_export_layout.xml create mode 100644 res/layout/sign_key_layout.xml create mode 100644 src/org/thialfihar/android/apg/ImportFromQRCodeActivity.java create mode 100644 src/org/thialfihar/android/apg/SendKeyActivity.java create mode 100644 src/org/thialfihar/android/apg/SignKeyActivity.java diff --git a/AndroidManifest.xml b/AndroidManifest.xml index 8c7dd53fe..b8f738795 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -183,6 +183,11 @@ android:label="@string/title_keyServerQuery" android:configChanges="keyboardHidden|orientation|keyboard"/> + + + + + + + scprov-jdk15 1.46.99.4-UNOFFICIAL-ROBERTO-RELEASE-SNAPSHOT jar - provided + + + com.google.zxing + android-integration + 1.6-SNAPSHOT + jar diff --git a/res/layout/key_server_export_layout.xml b/res/layout/key_server_export_layout.xml new file mode 100644 index 000000000..b2270417d --- /dev/null +++ b/res/layout/key_server_export_layout.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + diff --git a/res/values/strings.xml b/res/values/strings.xml index 5b29e4f12..d81ac3a3d 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -42,7 +42,10 @@ Key Not Found Getting Started Query Key Server + Export to Key Server Unknown Signature Key + Import from QR Code + Sign Key User IDs @@ -74,6 +77,7 @@ Change Pass Phrase Set Pass Phrase Search + Export To Server About @@ -92,6 +96,10 @@ Help Key Server Update + Export To Server + Share + Scan QR Code + Sign Key Sign @@ -124,6 +132,7 @@ Name Comment Email + Send Key to Server? Select 1 Selected @@ -217,6 +226,9 @@ Key editing is still kind of beta. %s bad secret key(s) ignored. Perhaps you exported with the option\n --export-secret-subkeys\nMake sure you export with\n --export-secret-keys\ninstead. Unknown key %s, do you want to try finding it on a keyserver? + Successfully sent key to server + Successfully signed key + Successfully validated and imported key diff --git a/src/org/thialfihar/android/apg/Apg.java b/src/org/thialfihar/android/apg/Apg.java index 3ec12ced6..180afd93b 100644 --- a/src/org/thialfihar/android/apg/Apg.java +++ b/src/org/thialfihar/android/apg/Apg.java @@ -61,6 +61,7 @@ import org.spongycastle.openpgp.PGPEncryptedDataGenerator; import org.spongycastle.openpgp.PGPEncryptedDataList; import org.spongycastle.openpgp.PGPException; import org.spongycastle.openpgp.PGPKeyPair; +import org.spongycastle.openpgp.PGPKeyRing; import org.spongycastle.openpgp.PGPKeyRingGenerator; import org.spongycastle.openpgp.PGPLiteralData; import org.spongycastle.openpgp.PGPLiteralDataGenerator; @@ -81,6 +82,7 @@ import org.spongycastle.openpgp.PGPSignatureSubpacketGenerator; import org.spongycastle.openpgp.PGPSignatureSubpacketVector; import org.spongycastle.openpgp.PGPUtil; import org.spongycastle.openpgp.PGPV3SignatureGenerator; +import org.thialfihar.android.apg.KeyServer.AddKeyException; import org.thialfihar.android.apg.provider.DataProvider; import org.thialfihar.android.apg.provider.Database; import org.thialfihar.android.apg.provider.KeyRings; @@ -119,6 +121,8 @@ public class Apg { public static final String LOOK_UP_KEY_ID = "org.thialfihar.android.apg.intent.LOOK_UP_KEY_ID"; public static final String LOOK_UP_KEY_ID_AND_RETURN = "org.thialfihar.android.apg.intent.LOOK_UP_KEY_ID_AND_RETURN"; public static final String GENERATE_SIGNATURE = "org.thialfihar.android.apg.intent.GENERATE_SIGNATURE"; + public static final String EXPORT_KEY_TO_SERVER = "org.thialfihar.android.apg.intent.EXPORT_KEY_TO_SERVER"; + public static final String IMPORT_FROM_QR_CODE = "org.thialfihar.android.apg.intent.IMPORT_FROM_QR_CODE"; } public static final String EXTRA_TEXT = "text"; @@ -147,6 +151,7 @@ public class Apg { public static final String EXTRA_ASCII_ARMOUR = "asciiArmour"; public static final String EXTRA_BINARY = "binary"; public static final String EXTRA_KEY_SERVERS = "keyServers"; + public static final String EXTRA_EXPECTED_FINGERPRINT = "org.thialfihar.android.apg.EXPECTED_FINGERPRINT"; public static final String AUTHORITY = DataProvider.AUTHORITY; @@ -590,6 +595,75 @@ public class Apg { progress.setProgress(R.string.progress_done, 100, 100); } + + public static PGPKeyRing decodeKeyRing(InputStream is) throws IOException { + InputStream in = PGPUtil.getDecoderStream(is); + PGPObjectFactory objectFactory = new PGPObjectFactory(in); + Object obj = objectFactory.nextObject(); + + if (obj instanceof PGPKeyRing) { + return (PGPKeyRing) obj; + } + + return null; + } + + public static int storeKeyRingInCache(PGPKeyRing keyring) { + int status = Integer.MIN_VALUE; // out of bounds value (Id.retrun_value.*) + try { + if (keyring instanceof PGPSecretKeyRing) { + PGPSecretKeyRing secretKeyRing = (PGPSecretKeyRing) keyring; + boolean save = true; + try { + PGPPrivateKey testKey = secretKeyRing.getSecretKey().extractPrivateKey(new char[] {}, new BouncyCastleProvider()); + if (testKey == null) { + // this is bad, something is very wrong... likely a --export-secret-subkeys export + save = false; + status = Id.return_value.bad; + } + } catch (PGPException e) { + // all good if this fails, we likely didn't use the right password + } + + if (save) { + status = mDatabase.saveKeyRing(secretKeyRing); + } + } else if (keyring instanceof PGPPublicKeyRing) { + PGPPublicKeyRing publicKeyRing = (PGPPublicKeyRing) keyring; + status = mDatabase.saveKeyRing(publicKeyRing); + } + } catch (IOException e) { + status = Id.return_value.error; + } catch (Database.GeneralException e) { + status = Id.return_value.error; + } + + return status; + } + + public static boolean uploadKeyRingToServer(HkpKeyServer server, PGPPublicKeyRing keyring) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ArmoredOutputStream aos = new ArmoredOutputStream(bos); + try { + aos.write(keyring.getEncoded()); + aos.close(); + + String armouredKey = bos.toString("UTF-8"); + server.add(armouredKey); + + return true; + } catch (IOException e) { + return false; + } catch(AddKeyException e) { + // TODO: tell the user? + return false; + } finally { + try { + bos.close(); + } catch (IOException e) { + } + } + } public static Bundle importKeyRings(Activity context, int type, InputData data, @@ -616,64 +690,32 @@ public class Apg { int oldKeys = 0; int badKeys = 0; try { - while (true) { - InputStream in = PGPUtil.getDecoderStream(bufferedInput); - PGPObjectFactory objectFactory = new PGPObjectFactory(in); - Object obj = objectFactory.nextObject(); - // if the first is already a null object, then we can stop trying - if (obj == null) { - break; + PGPKeyRing keyring = decodeKeyRing(bufferedInput); + while (keyring != null) { + int status = Integer.MIN_VALUE; // out of bounds value + + // if this key is what we expect it to be, save it + if ((type == Id.type.secret_key && keyring instanceof PGPSecretKeyRing) || + (type == Id.type.public_key && keyring instanceof PGPPublicKeyRing)) { + status = storeKeyRingInCache(keyring); } - while (obj != null) { - PGPPublicKeyRing publicKeyRing; - PGPSecretKeyRing secretKeyRing; - // a return value that doesn't match any Id.return_value.* values, in case - // saveKeyRing is never called - int retValue = 2107; - try { - if (type == Id.type.secret_key && obj instanceof PGPSecretKeyRing) { - secretKeyRing = (PGPSecretKeyRing) obj; - boolean save = true; - try { - PGPPrivateKey testKey = secretKeyRing.getSecretKey() - .extractPrivateKey(new char[] {}, new BouncyCastleProvider()); - if (testKey == null) { - // this is bad, something is very wrong... likely a - // --export-secret-subkeys export - retValue = Id.return_value.bad; - save = false; - } - } catch (PGPException e) { - // all good if this fails, we likely didn't use the right password - } - if (save) { - retValue = mDatabase.saveKeyRing(secretKeyRing); - } - } else if (type == Id.type.public_key && obj instanceof PGPPublicKeyRing) { - publicKeyRing = (PGPPublicKeyRing) obj; - retValue = mDatabase.saveKeyRing(publicKeyRing); - } - } catch (IOException e) { - retValue = Id.return_value.error; - } catch (Database.GeneralException e) { - retValue = Id.return_value.error; - } - - if (retValue == Id.return_value.error) { - throw new GeneralException(context.getString(R.string.error_savingKeys)); - } - - if (retValue == Id.return_value.updated) { - ++oldKeys; - } else if (retValue == Id.return_value.ok) { - ++newKeys; - } else if (retValue == Id.return_value.bad) { - ++badKeys; - } - progress.setProgress((int)(100 * progressIn.position() / data.getSize()), 100); - obj = objectFactory.nextObject(); + if (status == Id.return_value.error) { + throw new GeneralException(context.getString(R.string.error_savingKeys)); } + + // update the counts to display to the user at the end + if (status == Id.return_value.updated) { + ++oldKeys; + } else if (status == Id.return_value.ok) { + ++newKeys; + } else if (status == Id.return_value.bad) { + ++badKeys; + } + + progress.setProgress((int)(100 * progressIn.position() / data.getSize()), 100); + + keyring = decodeKeyRing(bufferedInput); } } catch (EOFException e) { // nothing to do, we are done @@ -1038,18 +1080,8 @@ public class Apg { return algorithmStr + ", " + keySize + "bit"; } - public static String getFingerPrint(long keyId) { - PGPPublicKey key = Apg.getPublicKey(keyId); - if (key == null) { - PGPSecretKey secretKey = Apg.getSecretKey(keyId); - if (secretKey == null) { - return ""; - } - key = secretKey.getPublicKey(); - } - + public static String convertToHex(byte[] fp) { String fingerPrint = ""; - byte fp[] = key.getFingerprint(); for (int i = 0; i < fp.length; ++i) { if (i != 0 && i % 10 == 0) { fingerPrint += " "; @@ -1064,6 +1096,20 @@ public class Apg { } return fingerPrint; + + } + + public static String getFingerPrint(long keyId) { + PGPPublicKey key = Apg.getPublicKey(keyId); + if (key == null) { + PGPSecretKey secretKey = Apg.getSecretKey(keyId); + if (secretKey == null) { + return ""; + } + key = secretKey.getPublicKey(); + } + + return convertToHex(key.getFingerprint()); } public static String getSmallFingerPrint(long keyId) { @@ -1089,8 +1135,8 @@ public class Apg { mDatabase.deleteKeyRing(keyRingId); } - public static Object getKeyRing(int keyRingId) { - return mDatabase.getKeyRing(keyRingId); + public static PGPKeyRing getKeyRing(int keyRingId) { + return (PGPKeyRing) mDatabase.getKeyRing(keyRingId); } public static PGPSecretKeyRing getSecretKeyRing(long keyId) { @@ -1109,7 +1155,7 @@ public class Apg { } return null; } - + public static PGPPublicKeyRing getPublicKeyRing(long keyId) { byte[] data = mDatabase.getKeyRingDataFromKeyId(Id.database.type_public, keyId); if (data == null) { diff --git a/src/org/thialfihar/android/apg/BaseActivity.java b/src/org/thialfihar/android/apg/BaseActivity.java index 5226b90d6..73cfd039d 100644 --- a/src/org/thialfihar/android/apg/BaseActivity.java +++ b/src/org/thialfihar/android/apg/BaseActivity.java @@ -163,6 +163,13 @@ public class BaseActivity extends Activity mProgressDialog.setCancelable(false); return mProgressDialog; } + + case Id.dialog.signing: { + mProgressDialog.setMessage(this.getString(R.string.progress_signing)); + mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); + mProgressDialog.setCancelable(false); + return mProgressDialog; + } default: { break; diff --git a/src/org/thialfihar/android/apg/HkpKeyServer.java b/src/org/thialfihar/android/apg/HkpKeyServer.java index 9f363d2e0..ea0bfddfd 100644 --- a/src/org/thialfihar/android/apg/HkpKeyServer.java +++ b/src/org/thialfihar/android/apg/HkpKeyServer.java @@ -10,12 +10,25 @@ import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.net.UnknownHostException; +import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.List; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.NameValuePair; +import org.apache.http.client.HttpClient; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; + import android.text.Html; public class HkpKeyServer extends KeyServer { @@ -38,16 +51,14 @@ public class HkpKeyServer extends KeyServer { return mData; } } + private String mHost; private short mPort = 11371; // example: // pub 2048R/9F5C9090 2009-08-17 Jörg Runge <joerg@joergrunge.de> - public static Pattern PUB_KEY_LINE = - Pattern.compile("pub +([0-9]+)([a-z]+)/.*?0x([0-9a-z]+).*? +([0-9-]+) +(.+)[\n\r]+((?: +.+[\n\r]+)*)", - Pattern.CASE_INSENSITIVE); - public static Pattern USER_ID_LINE = - Pattern.compile("^ +(.+)$", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE); + public static Pattern PUB_KEY_LINE = Pattern.compile("pub +([0-9]+)([a-z]+)/.*?0x([0-9a-z]+).*? +([0-9-]+) +(.+)[\n\r]+((?: +.+[\n\r]+)*)", Pattern.CASE_INSENSITIVE); + public static Pattern USER_ID_LINE = Pattern.compile("^ +(.+)$", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE); public HkpKeyServer(String host) { mHost = host; @@ -58,8 +69,7 @@ public class HkpKeyServer extends KeyServer { mPort = port; } - static private String readAll(InputStream in, String encoding) - throws IOException { + static private String readAll(InputStream in, String encoding) throws IOException { ByteArrayOutputStream raw = new ByteArrayOutputStream(); byte buffer[] = new byte[1 << 16]; @@ -74,8 +84,8 @@ public class HkpKeyServer extends KeyServer { return raw.toString(encoding); } - private String query(String request) - throws QueryException, HttpError { + // TODO: replace this with httpclient + private String query(String request) throws QueryException, HttpError { InetAddress ips[]; try { ips = InetAddress.getAllByName(mHost); @@ -93,8 +103,7 @@ public class HkpKeyServer extends KeyServer { int response = conn.getResponseCode(); if (response >= 200 && response < 300) { return readAll(conn.getInputStream(), conn.getContentEncoding()); - } - else { + } else { String data = readAll(conn.getErrorStream(), conn.getContentEncoding()); throw new HttpError(response, data); } @@ -108,9 +117,9 @@ public class HkpKeyServer extends KeyServer { throw new QueryException("querying server(s) for '" + mHost + "' failed"); } + // TODO: replace this with httpclient @Override - List search(String query) - throws QueryException, TooManyResponses, InsufficientQuery { + List search(String query) throws QueryException, TooManyResponses, InsufficientQuery { Vector results = new Vector(); if (query.length() < 3) { @@ -151,9 +160,7 @@ public class HkpKeyServer extends KeyServer { info.keyId = Apg.keyFromHex(matcher.group(3)); info.fingerPrint = Apg.getSmallFingerPrint(info.keyId); String chunks[] = matcher.group(4).split("-"); - info.date = new GregorianCalendar(Integer.parseInt(chunks[0]), - Integer.parseInt(chunks[1]), - Integer.parseInt(chunks[2])).getTime(); + info.date = new GregorianCalendar(Integer.parseInt(chunks[0]), Integer.parseInt(chunks[1]), Integer.parseInt(chunks[2])).getTime(); info.userIds = new Vector(); if (matcher.group(5).startsWith("*** KEY")) { info.revoked = matcher.group(5); @@ -177,21 +184,50 @@ public class HkpKeyServer extends KeyServer { } @Override - String get(long keyId) - throws QueryException { - String request = "/pks/lookup?op=get&search=0x" + Apg.keyToHex(keyId); - - String data = null; + String get(long keyId) throws QueryException { + HttpClient client = new DefaultHttpClient(); try { - data = query(request); - } catch (HttpError e) { - throw new QueryException("not found"); + HttpGet get = new HttpGet("http://" + mHost + ":" + mPort + "/pks/lookup?op=get&search=0x" + Apg.keyToHex(keyId)); + + HttpResponse response = client.execute(get); + if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { + throw new QueryException("not found"); + } + + HttpEntity entity = response.getEntity(); + InputStream is = entity.getContent(); + String data = readAll(is, EntityUtils.getContentCharSet(entity)); + Matcher matcher = Apg.PGP_PUBLIC_KEY.matcher(data); + if (matcher.find()) { + return matcher.group(1); + } + } catch (IOException e) { + // nothing to do, better luck on the next keyserver + } finally { + client.getConnectionManager().shutdown(); } - Matcher matcher = Apg.PGP_PUBLIC_KEY.matcher(data); - if (matcher.find()) { - return matcher.group(1); - } - + return null; } + + @Override + void add(String armouredText) throws AddKeyException { + HttpClient client = new DefaultHttpClient(); + try { + HttpPost post = new HttpPost("http://" + mHost + ":" + mPort + "/pks/add"); + + List nameValuePairs = new ArrayList(2); + nameValuePairs.add(new BasicNameValuePair("keytext", armouredText)); + post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); + + HttpResponse response = client.execute(post); + if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { + throw new AddKeyException(); + } + } catch (IOException e) { + // nothing to do, better luck on the next keyserver + } finally { + client.getConnectionManager().shutdown(); + } + } } diff --git a/src/org/thialfihar/android/apg/Id.java b/src/org/thialfihar/android/apg/Id.java index 1ce53eabd..4bcbdba78 100644 --- a/src/org/thialfihar/android/apg/Id.java +++ b/src/org/thialfihar/android/apg/Id.java @@ -18,12 +18,16 @@ package org.thialfihar.android.apg; import org.spongycastle.bcpg.CompressionAlgorithmTags; + public final class Id { public static final class menu { public static final int export = 0x21070001; public static final int delete = 0x21070002; public static final int edit = 0x21070003; public static final int update = 0x21070004; + public static final int exportToServer = 0x21070005; + public static final int share = 0x21070006; + public static final int signKey = 0x21070007; public static final class option { public static final int new_pass_phrase = 0x21070001; @@ -37,6 +41,7 @@ public final class Id { public static final int search = 0x21070009; public static final int help = 0x21070010; public static final int key_server = 0x21070011; + public static final int scanQRCode = 0x21070012; } } @@ -61,6 +66,9 @@ public final class Id { public static final int output_filename = 0x21070004; public static final int key_server_preference = 0x21070005; public static final int look_up_key_id = 0x21070006; + public static final int export_to_server = 0x21070007; + public static final int import_from_qr_code = 0x21070008; + public static final int sign_key = 0x21070009; } public static final class dialog { @@ -86,6 +94,7 @@ public final class Id { public static final int help = 0x21070014; public static final int querying = 0x21070015; public static final int lookup_unknown_key = 0x21070016; + public static final int signing = 0x21070017; } public static final class task { @@ -166,8 +175,9 @@ public final class Id { public static final int keys = 2; } - public static final class query { + public static final class keyserver { public static final int search = 0x21070001; public static final int get = 0x21070002; + public static final int add = 0x21070003; } } diff --git a/src/org/thialfihar/android/apg/ImportFromQRCodeActivity.java b/src/org/thialfihar/android/apg/ImportFromQRCodeActivity.java new file mode 100644 index 000000000..b875f2eef --- /dev/null +++ b/src/org/thialfihar/android/apg/ImportFromQRCodeActivity.java @@ -0,0 +1,133 @@ +package org.thialfihar.android.apg; + +import java.io.ByteArrayInputStream; +import java.io.IOException; + +import org.spongycastle.openpgp.PGPKeyRing; +import org.spongycastle.openpgp.PGPPublicKeyRing; +import org.thialfihar.android.apg.KeyServer.QueryException; + +import android.content.Intent; +import android.os.Bundle; +import android.os.Message; +import android.util.Log; +import android.widget.Toast; + +import com.google.zxing.integration.android.IntentIntegrator; +import com.google.zxing.integration.android.IntentResult; + +public class ImportFromQRCodeActivity extends BaseActivity { + private static final String TAG = "ImportFromQRCodeActivity"; + + private final Bundle status = new Bundle(); + private final Message msg = new Message(); + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + IntentIntegrator.initiateScan(this); + } + + private void importAndSign(final long keyId, final String expectedFingerprint) { + if (expectedFingerprint != null && expectedFingerprint.length() > 0) { + + Thread t = new Thread() { + @Override + public void run() { + try { + // TODO: display some sort of spinner here while the user waits + + HkpKeyServer server = new HkpKeyServer(mPreferences.getKeyServers()[0]); // TODO: there should be only 1 + String encodedKey = server.get(keyId); + + PGPKeyRing keyring = Apg.decodeKeyRing(new ByteArrayInputStream(encodedKey.getBytes())); + if (keyring != null && keyring instanceof PGPPublicKeyRing) { + PGPPublicKeyRing publicKeyRing = (PGPPublicKeyRing) keyring; + + // make sure the fingerprints match before we cache this thing + String actualFingerprint = Apg.convertToHex(publicKeyRing.getPublicKey().getFingerprint()); + if (expectedFingerprint.equals(actualFingerprint)) { + // store the signed key in our local cache + int retval = Apg.storeKeyRingInCache(publicKeyRing); + if (retval != Id.return_value.ok && retval != Id.return_value.updated) { + status.putString(Apg.EXTRA_ERROR, "Failed to store signed key in local cache"); + } else { + Intent intent = new Intent(ImportFromQRCodeActivity.this, SignKeyActivity.class); + intent.putExtra(Apg.EXTRA_KEY_ID, keyId); + startActivityForResult(intent, Id.request.sign_key); + } + } else { + status.putString(Apg.EXTRA_ERROR, "Scanned fingerprint does NOT match the fingerprint of the received key. You shouldnt trust this key."); + } + } + } catch (QueryException e) { + Log.e(TAG, "Failed to query KeyServer", e); + status.putString(Apg.EXTRA_ERROR, "Failed to query KeyServer"); + status.putInt(Constants.extras.status, Id.message.done); + } catch (IOException e) { + Log.e(TAG, "Failed to query KeyServer", e); + status.putString(Apg.EXTRA_ERROR, "Failed to query KeyServer"); + status.putInt(Constants.extras.status, Id.message.done); + } + } + }; + + t.setName("KeyExchange Download Thread"); + t.setDaemon(true); + t.start(); + } + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + switch (requestCode) { + case IntentIntegrator.REQUEST_CODE: { + boolean debug = true; // TODO: remove this!!! + IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); + if (debug || (scanResult != null && scanResult.getFormatName() != null)) { + String[] bits = debug ? new String[] { "5993515643896327656", "0816 F68A 6816 68FB 01BF 2CA5 532D 3EB9 1E2F EDE8" } : scanResult.getContents().split(","); + if (bits.length != 2) { + return; // dont know how to handle this. Not a valid code + } + + long keyId = Long.parseLong(bits[0]); + String expectedFingerprint = bits[1]; + + importAndSign(keyId, expectedFingerprint); + + break; + } + } + + case Id.request.sign_key: { + // signals the end of processing. Signature was either applied, or it wasnt + status.putInt(Constants.extras.status, Id.message.done); + + msg.setData(status); + sendMessage(msg); + + break; + } + + default: { + super.onActivityResult(requestCode, resultCode, data); + } + } + } + + @Override + public void doneCallback(Message msg) { + super.doneCallback(msg); + + Bundle data = msg.getData(); + String error = data.getString(Apg.EXTRA_ERROR); + if (error != null) { + Toast.makeText(this, getString(R.string.errorMessage, error), Toast.LENGTH_SHORT).show(); + return; + } + + Toast.makeText(this, R.string.keySignSuccess, Toast.LENGTH_SHORT).show(); // TODO + finish(); + } +} diff --git a/src/org/thialfihar/android/apg/KeyListActivity.java b/src/org/thialfihar/android/apg/KeyListActivity.java index 585d0259b..e35061da7 100644 --- a/src/org/thialfihar/android/apg/KeyListActivity.java +++ b/src/org/thialfihar/android/apg/KeyListActivity.java @@ -33,6 +33,9 @@ import org.thialfihar.android.apg.provider.KeyRings; import org.thialfihar.android.apg.provider.Keys; import org.thialfihar.android.apg.provider.UserIds; +import com.google.zxing.integration.android.IntentIntegrator; +import com.google.zxing.integration.android.IntentResult; + import android.app.AlertDialog; import android.app.Dialog; import android.app.SearchManager; @@ -150,7 +153,7 @@ public class KeyListActivity extends BaseActivity { showDialog(Id.dialog.export_keys); return true; } - + default: { return super.onOptionsItemSelected(item); } @@ -792,7 +795,7 @@ public class KeyListActivity extends BaseActivity { } return; } - + default: { break; } diff --git a/src/org/thialfihar/android/apg/KeyServer.java b/src/org/thialfihar/android/apg/KeyServer.java index b31ace887..c6782632e 100644 --- a/src/org/thialfihar/android/apg/KeyServer.java +++ b/src/org/thialfihar/android/apg/KeyServer.java @@ -12,12 +12,19 @@ public abstract class KeyServer { super(message); } } + static public class TooManyResponses extends Exception { private static final long serialVersionUID = 2703768928624654513L; } + static public class InsufficientQuery extends Exception { private static final long serialVersionUID = 2703768928624654514L; } + + static public class AddKeyException extends Exception { + private static final long serialVersionUID = -507574859137295530L; + } + static public class KeyInfo implements Serializable { private static final long serialVersionUID = -7797972113284992662L; Vector userIds; @@ -28,6 +35,8 @@ public abstract class KeyServer { int size; String algorithm; } + abstract List search(String query) throws QueryException, TooManyResponses, InsufficientQuery; abstract String get(long keyId) throws QueryException; + abstract void add(String armouredText) throws AddKeyException; } diff --git a/src/org/thialfihar/android/apg/KeyServerQueryActivity.java b/src/org/thialfihar/android/apg/KeyServerQueryActivity.java index 01cfec0c0..2b04d7bac 100644 --- a/src/org/thialfihar/android/apg/KeyServerQueryActivity.java +++ b/src/org/thialfihar/android/apg/KeyServerQueryActivity.java @@ -99,7 +99,7 @@ public class KeyServerQueryActivity extends BaseActivity { private void search(String query) { showDialog(Id.dialog.querying); - mQueryType = Id.query.search; + mQueryType = Id.keyserver.search; mQueryString = query; mAdapter.setKeys(new Vector()); startThread(); @@ -107,11 +107,11 @@ public class KeyServerQueryActivity extends BaseActivity { private void get(long keyId) { showDialog(Id.dialog.querying); - mQueryType = Id.query.get; + mQueryType = Id.keyserver.get; mQueryId = keyId; startThread(); } - + protected Dialog onCreateDialog(int id) { ProgressDialog progress = (ProgressDialog) super.onCreateDialog(id); progress.setMessage(this.getString(R.string.progress_queryingServer, @@ -127,9 +127,9 @@ public class KeyServerQueryActivity extends BaseActivity { try { HkpKeyServer server = new HkpKeyServer((String)mKeyServer.getSelectedItem()); - if (mQueryType == Id.query.search) { + if (mQueryType == Id.keyserver.search) { mSearchResult = server.search(mQueryString); - } else if (mQueryType == Id.query.get) { + } else if (mQueryType == Id.keyserver.get) { mKeyData = server.get(mQueryId); } } catch (QueryException e) { @@ -163,12 +163,12 @@ public class KeyServerQueryActivity extends BaseActivity { return; } - if (mQueryType == Id.query.search) { + if (mQueryType == Id.keyserver.search) { if (mSearchResult != null) { Toast.makeText(this, getString(R.string.keysFound, mSearchResult.size()), Toast.LENGTH_SHORT).show(); mAdapter.setKeys(mSearchResult); } - } else if (mQueryType == Id.query.get) { + } else if (mQueryType == Id.keyserver.get) { Intent orgIntent = getIntent(); if (Apg.Intent.LOOK_UP_KEY_ID_AND_RETURN.equals(orgIntent.getAction())) { if (mKeyData != null) { diff --git a/src/org/thialfihar/android/apg/MainActivity.java b/src/org/thialfihar/android/apg/MainActivity.java index 5a07b0a42..1f0280407 100644 --- a/src/org/thialfihar/android/apg/MainActivity.java +++ b/src/org/thialfihar/android/apg/MainActivity.java @@ -16,9 +16,11 @@ package org.thialfihar.android.apg; +import java.security.Security; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.spongycastle.jce.provider.BouncyCastleProvider; import org.thialfihar.android.apg.provider.Accounts; import android.app.AlertDialog; @@ -51,6 +53,10 @@ import android.widget.TextView; import android.widget.Toast; public class MainActivity extends BaseActivity { + static { + Security.addProvider(new BouncyCastleProvider()); + } + private ListView mAccounts = null; private AccountListAdapter mListAdapter = null; private Cursor mAccountCursor; diff --git a/src/org/thialfihar/android/apg/PublicKeyListActivity.java b/src/org/thialfihar/android/apg/PublicKeyListActivity.java index 509a81374..1290c9df6 100644 --- a/src/org/thialfihar/android/apg/PublicKeyListActivity.java +++ b/src/org/thialfihar/android/apg/PublicKeyListActivity.java @@ -18,6 +18,9 @@ package org.thialfihar.android.apg; import org.spongycastle.openpgp.PGPPublicKeyRing; +import com.google.zxing.integration.android.IntentIntegrator; +import com.google.zxing.integration.android.IntentResult; + import android.content.Intent; import android.os.Bundle; import android.view.ContextMenu; @@ -48,6 +51,8 @@ public class PublicKeyListActivity extends KeyListActivity { .setIcon(android.R.drawable.ic_menu_preferences); menu.add(1, Id.menu.option.about, 4, R.string.menu_about) .setIcon(android.R.drawable.ic_menu_info_details); + menu.add(1, Id.menu.option.scanQRCode, 5, R.string.menu_scanQRCode) + .setIcon(android.R.drawable.ic_menu_add); return true; } @@ -63,6 +68,8 @@ public class PublicKeyListActivity extends KeyListActivity { menu.add(0, Id.menu.export, 0, R.string.menu_exportKey); menu.add(0, Id.menu.delete, 1, R.string.menu_deleteKey); menu.add(0, Id.menu.update, 1, R.string.menu_updateKey); + menu.add(0, Id.menu.exportToServer, 1, R.string.menu_exportKeyToServer); + menu.add(0, Id.menu.signKey, 1, R.string.menu_signKey); } } @@ -94,11 +101,62 @@ public class PublicKeyListActivity extends KeyListActivity { intent.setAction(Apg.Intent.LOOK_UP_KEY_ID_AND_RETURN); intent.putExtra(Apg.EXTRA_KEY_ID, keyId); startActivityForResult(intent, Id.request.look_up_key_id); + + return true; + } + + case Id.menu.exportToServer: { + mSelectedItem = groupPosition; + final int keyRingId = mListAdapter.getKeyRingId(groupPosition); + + Intent intent = new Intent(this, SendKeyActivity.class); + intent.setAction(Apg.Intent.EXPORT_KEY_TO_SERVER); + intent.putExtra(Apg.EXTRA_KEY_ID, keyRingId); + startActivityForResult(intent, Id.request.export_to_server); + + return true; + } + + case Id.menu.signKey: { + mSelectedItem = groupPosition; + final int keyRingId = mListAdapter.getKeyRingId(groupPosition); + long keyId = 0; + Object keyRing = Apg.getKeyRing(keyRingId); + if (keyRing != null && keyRing instanceof PGPPublicKeyRing) { + keyId = Apg.getMasterKey((PGPPublicKeyRing) keyRing).getKeyID(); + } + + if (keyId == 0) { + // this shouldn't happen + return true; + } + + Intent intent = new Intent(this, SignKeyActivity.class); + intent.putExtra(Apg.EXTRA_KEY_ID, keyId); + startActivity(intent); + + return true; + } + + default: { + return super.onContextItemSelected(menuItem); + } + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case Id.menu.option.scanQRCode: { + Intent intent = new Intent(this, ImportFromQRCodeActivity.class); + intent.setAction(Apg.Intent.IMPORT_FROM_QR_CODE); + startActivityForResult(intent, Id.request.import_from_qr_code); + return true; } default: { - return super.onContextItemSelected(menuItem); + return super.onOptionsItemSelected(item); } } } @@ -118,7 +176,7 @@ public class PublicKeyListActivity extends KeyListActivity { handleIntent(intent); break; } - + default: { super.onActivityResult(requestCode, resultCode, data); break; diff --git a/src/org/thialfihar/android/apg/SecretKeyListActivity.java b/src/org/thialfihar/android/apg/SecretKeyListActivity.java index d3c89ddc9..4689db982 100644 --- a/src/org/thialfihar/android/apg/SecretKeyListActivity.java +++ b/src/org/thialfihar/android/apg/SecretKeyListActivity.java @@ -28,6 +28,8 @@ import android.widget.ExpandableListView; import android.widget.ExpandableListView.ExpandableListContextMenuInfo; import android.widget.ExpandableListView.OnChildClickListener; +import com.google.zxing.integration.android.IntentIntegrator; + public class SecretKeyListActivity extends KeyListActivity implements OnChildClickListener { @Override public void onCreate(Bundle savedInstanceState) { @@ -80,6 +82,7 @@ public class SecretKeyListActivity extends KeyListActivity implements OnChildCli menu.add(0, Id.menu.edit, 0, R.string.menu_editKey); menu.add(0, Id.menu.export, 1, R.string.menu_exportKey); menu.add(0, Id.menu.delete, 2, R.string.menu_deleteKey); + menu.add(0, Id.menu.share, 2, R.string.menu_share); } } @@ -100,6 +103,14 @@ public class SecretKeyListActivity extends KeyListActivity implements OnChildCli return true; } + case Id.menu.share: { + mSelectedItem = groupPosition; + + long keyId = ((KeyListAdapter) mList.getExpandableListAdapter()).getGroupId(mSelectedItem); + String msg = keyId + "," + Apg.getFingerPrint(keyId);; + IntentIntegrator.shareText(this, msg); + } + default: { return super.onContextItemSelected(menuItem); } @@ -169,7 +180,7 @@ public class SecretKeyListActivity extends KeyListActivity implements OnChildCli } break; } - + default: { break; } diff --git a/src/org/thialfihar/android/apg/SendKeyActivity.java b/src/org/thialfihar/android/apg/SendKeyActivity.java new file mode 100644 index 000000000..9fe201a7a --- /dev/null +++ b/src/org/thialfihar/android/apg/SendKeyActivity.java @@ -0,0 +1,93 @@ +package org.thialfihar.android.apg; + +import org.spongycastle.openpgp.PGPKeyRing; +import org.spongycastle.openpgp.PGPPublicKeyRing; + +import android.os.Bundle; +import android.os.Message; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.Spinner; +import android.widget.Toast; + +/** + * gpg --send-key activity + * + * Sends the selected public key to a key server + */ +public class SendKeyActivity extends BaseActivity { + + private Button export; + private Spinner keyServer; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(R.layout.key_server_export_layout); + + export = (Button) findViewById(R.id.btn_export_to_server); + keyServer = (Spinner) findViewById(R.id.keyServer); + + ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, mPreferences.getKeyServers()); + adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + keyServer.setAdapter(adapter); + if (adapter.getCount() > 0) { + keyServer.setSelection(0); + } else { + export.setEnabled(false); + } + + export.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + startThread(); + } + }); + } + + @Override + public void run() { + String error = null; + Bundle data = new Bundle(); + Message msg = new Message(); + + HkpKeyServer server = new HkpKeyServer((String) keyServer.getSelectedItem()); + + int keyRingId = getIntent().getIntExtra(Apg.EXTRA_KEY_ID, -1); + + PGPKeyRing keyring = Apg.getKeyRing(keyRingId); + if (keyring != null && keyring instanceof PGPPublicKeyRing) { + boolean uploaded = Apg.uploadKeyRingToServer(server, (PGPPublicKeyRing) keyring); + if (!uploaded) { + error = "Unable to export key to selected server"; + } + } + + data.putInt(Constants.extras.status, Id.message.export_done); + + if (error != null) { + data.putString(Apg.EXTRA_ERROR, error); + } + + msg.setData(data); + sendMessage(msg); + } + + @Override + public void doneCallback(Message msg) { + super.doneCallback(msg); + + Bundle data = msg.getData(); + String error = data.getString(Apg.EXTRA_ERROR); + if (error != null) { + Toast.makeText(this, getString(R.string.errorMessage, error), Toast.LENGTH_SHORT).show(); + return; + } + + Toast.makeText(this, R.string.keySendSuccess, Toast.LENGTH_SHORT).show(); + finish(); + } +} diff --git a/src/org/thialfihar/android/apg/SignKeyActivity.java b/src/org/thialfihar/android/apg/SignKeyActivity.java new file mode 100644 index 000000000..0d8a473bd --- /dev/null +++ b/src/org/thialfihar/android/apg/SignKeyActivity.java @@ -0,0 +1,284 @@ +package org.thialfihar.android.apg; + +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.SignatureException; +import java.util.Iterator; + +import org.spongycastle.jce.provider.BouncyCastleProvider; +import org.spongycastle.openpgp.PGPException; +import org.spongycastle.openpgp.PGPPrivateKey; +import org.spongycastle.openpgp.PGPPublicKey; +import org.spongycastle.openpgp.PGPPublicKeyRing; +import org.spongycastle.openpgp.PGPSecretKey; +import org.spongycastle.openpgp.PGPSignature; +import org.spongycastle.openpgp.PGPSignatureGenerator; +import org.spongycastle.openpgp.PGPSignatureSubpacketGenerator; +import org.spongycastle.openpgp.PGPSignatureSubpacketVector; +import org.spongycastle.openpgp.PGPUtil; + +import android.content.Intent; +import android.os.Bundle; +import android.os.Message; +import android.util.Log; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.CompoundButton.OnCheckedChangeListener; +import android.widget.Spinner; +import android.widget.Toast; + +/** + * gpg --sign-key + * + * signs the specified public key with the specified secret master key + */ +public class SignKeyActivity extends BaseActivity { + private static final String TAG = "SignKeyActivity"; + + private long pubKeyId = 0; + private long masterKeyId = 0; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // check we havent already signed it + setContentView(R.layout.sign_key_layout); + + final Spinner keyServer = (Spinner) findViewById(R.id.keyServer); + ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, mPreferences.getKeyServers()); + adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + keyServer.setAdapter(adapter); + + final CheckBox sendKey = (CheckBox) findViewById(R.id.sendKey); + if (!sendKey.isChecked()) { + keyServer.setEnabled(false); + } else { + keyServer.setEnabled(true); + } + + sendKey.setOnCheckedChangeListener(new OnCheckedChangeListener() { + + @Override + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + if (!isChecked) { + keyServer.setEnabled(false); + } else { + keyServer.setEnabled(true); + } + } + }); + + Button sign = (Button) findViewById(R.id.sign); + sign.setEnabled(false); // disabled until the user selects a key to sign with + sign.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + if (pubKeyId != 0) { + initiateSigning(); + } + } + }); + + pubKeyId = getIntent().getLongExtra(Apg.EXTRA_KEY_ID, 0); + if (pubKeyId == 0) { + finish(); // nothing to do if we dont know what key to sign + } else { + // kick off the SecretKey selection activity so the user chooses which key to sign with first + Intent intent = new Intent(this, SelectSecretKeyListActivity.class); + startActivityForResult(intent, Id.request.secret_keys); + } + } + + /** + * handles the UI bits of the signing process on the UI thread + */ + private void initiateSigning() { + PGPPublicKeyRing pubring = Apg.getPublicKeyRing(pubKeyId); + if (pubring != null) { + // if we have already signed this key, dont bother doing it again + boolean alreadySigned = false; + + @SuppressWarnings("unchecked") + Iterator itr = pubring.getPublicKey(pubKeyId).getSignatures(); + while (itr.hasNext()) { + PGPSignature sig = itr.next(); + if (sig.getKeyID() == masterKeyId) { + alreadySigned = true; + break; + } + } + + if (!alreadySigned) { + /* + * get the user's passphrase for this key (if required) + */ + String passphrase = Apg.getCachedPassPhrase(masterKeyId); + if (passphrase == null) { + showDialog(Id.dialog.pass_phrase); + return; // bail out; need to wait until the user has entered the passphrase before trying again + } else { + startSigning(); + } + } else { + final Bundle status = new Bundle(); + Message msg = new Message(); + + status.putString(Apg.EXTRA_ERROR, "Key has already been signed"); + + status.putInt(Constants.extras.status, Id.message.done); + + msg.setData(status); + sendMessage(msg); + + setResult(Id.return_value.error); + finish(); + } + } + } + + @Override + public long getSecretKeyId() { + return masterKeyId; + } + + @Override + public void passPhraseCallback(long keyId, String passPhrase) { + super.passPhraseCallback(keyId, passPhrase); + startSigning(); + } + + /** + * kicks off the actual signing process on a background thread + */ + private void startSigning() { + showDialog(Id.dialog.signing); + startThread(); + } + + @Override + public void run() { + final Bundle status = new Bundle(); + Message msg = new Message(); + + try { + String passphrase = Apg.getCachedPassPhrase(masterKeyId); + if (passphrase == null || passphrase.length() <= 0) { + status.putString(Apg.EXTRA_ERROR, "Unable to obtain passphrase"); + } else { + PGPPublicKeyRing pubring = Apg.getPublicKeyRing(pubKeyId); + + /* + * sign the incoming key + */ + PGPSecretKey secretKey = Apg.getSecretKey(masterKeyId); + PGPPrivateKey signingKey = secretKey.extractPrivateKey(passphrase.toCharArray(), BouncyCastleProvider.PROVIDER_NAME); + PGPSignatureGenerator sGen = new PGPSignatureGenerator(secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA256, BouncyCastleProvider.PROVIDER_NAME); + sGen.initSign(PGPSignature.DIRECT_KEY, signingKey); + + PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); + + PGPSignatureSubpacketVector packetVector = spGen.generate(); + sGen.setHashedSubpackets(packetVector); + + PGPPublicKey signedKey = PGPPublicKey.addCertification(pubring.getPublicKey(pubKeyId), sGen.generate()); + pubring = PGPPublicKeyRing.insertPublicKey(pubring, signedKey); + + // check if we need to send the key to the server or not + CheckBox sendKey = (CheckBox) findViewById(R.id.sendKey); + if (sendKey.isChecked()) { + Spinner keyServer = (Spinner) findViewById(R.id.keyServer); + HkpKeyServer server = new HkpKeyServer((String) keyServer.getSelectedItem()); + + /* + * upload the newly signed key to the key server + */ + + Apg.uploadKeyRingToServer(server, pubring); + } + + // store the signed key in our local cache + int retval = Apg.storeKeyRingInCache(pubring); + if (retval != Id.return_value.ok && retval != Id.return_value.updated) { + status.putString(Apg.EXTRA_ERROR, "Failed to store signed key in local cache"); + } + } + } catch (PGPException e) { + Log.e(TAG, "Failed to sign key", e); + status.putString(Apg.EXTRA_ERROR, "Failed to sign key"); + status.putInt(Constants.extras.status, Id.message.done); + return; + } catch (NoSuchAlgorithmException e) { + Log.e(TAG, "Failed to sign key", e); + status.putString(Apg.EXTRA_ERROR, "Failed to sign key"); + status.putInt(Constants.extras.status, Id.message.done); + return; + } catch (NoSuchProviderException e) { + Log.e(TAG, "Failed to sign key", e); + status.putString(Apg.EXTRA_ERROR, "Failed to sign key"); + status.putInt(Constants.extras.status, Id.message.done); + return; + } catch (SignatureException e) { + Log.e(TAG, "Failed to sign key", e); + status.putString(Apg.EXTRA_ERROR, "Failed to sign key"); + status.putInt(Constants.extras.status, Id.message.done); + return; + } + + status.putInt(Constants.extras.status, Id.message.done); + + msg.setData(status); + sendMessage(msg); + + if (status.containsKey(Apg.EXTRA_ERROR)) { + setResult(Id.return_value.error); + } else { + setResult(Id.return_value.ok); + } + + finish(); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + switch (requestCode) { + case Id.request.secret_keys: { + if (resultCode == RESULT_OK) { + masterKeyId = data.getLongExtra(Apg.EXTRA_KEY_ID, 0); + + // re-enable the sign button so the user can initiate the sign process + Button sign = (Button) findViewById(R.id.sign); + sign.setEnabled(true); + } + + break; + } + + default: { + super.onActivityResult(requestCode, resultCode, data); + } + } + } + + @Override + public void doneCallback(Message msg) { + super.doneCallback(msg); + + removeDialog(Id.dialog.signing); + + Bundle data = msg.getData(); + String error = data.getString(Apg.EXTRA_ERROR); + if (error != null) { + Toast.makeText(this, getString(R.string.errorMessage, error), Toast.LENGTH_SHORT).show(); + return; + } + + Toast.makeText(this, R.string.keySignSuccess, Toast.LENGTH_SHORT).show(); + finish(); + } +}