Merge pull request #502 from thi/conform-to-style-guide

Conform to style guide, #466
This commit is contained in:
Dominik Schürmann 2014-04-02 11:26:46 +02:00
commit 64358bb3f8
68 changed files with 539 additions and 465 deletions

View File

@ -17,16 +17,17 @@
package org.sufficientlysecure.keychain;
import java.io.File;
import java.security.Provider;
import java.security.Security;
import android.app.Application;
import android.os.Environment;
import org.spongycastle.jce.provider.BouncyCastleProvider;
import org.sufficientlysecure.keychain.util.Log;
import org.sufficientlysecure.keychain.util.PRNGFixes;
import android.app.Application;
import android.os.Environment;
import java.io.File;
import java.security.Provider;
import java.security.Security;
public class KeychainApplication extends Application {
@ -40,14 +41,14 @@ public class KeychainApplication extends Application {
/*
* Sets Bouncy (Spongy) Castle as preferred security provider
*
*
* insertProviderAt() position starts from 1
*/
Security.insertProviderAt(new BouncyCastleProvider(), 1);
/*
* apply RNG fixes
*
*
* among other things, executes Security.insertProviderAt(new
* LinuxPRNGSecureRandomProvider(), 1) for Android <= SDK 17
*/

View File

@ -17,20 +17,20 @@
package org.sufficientlysecure.keychain.compatibility;
import java.lang.reflect.Method;
import android.content.Context;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.util.Log;
import java.lang.reflect.Method;
public class ClipboardReflection {
private static final String clipboardLabel = "Keychain";
/**
* Wrapper around ClipboardManager based on Android version using Reflection API
*
*
* @param context
* @param text
*/
@ -57,7 +57,7 @@ public class ClipboardReflection {
/**
* Wrapper around ClipboardManager based on Android version using Reflection API
*
*
* @param context
*/
public static CharSequence getClipboardText(Context context) {

View File

@ -30,18 +30,12 @@ import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.Id;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.compatibility.DialogFragmentWorkaround;
import org.sufficientlysecure.keychain.provider.KeychainContract;
import org.sufficientlysecure.keychain.provider.ProviderHelper;
import org.sufficientlysecure.keychain.service.KeychainIntentService;
import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler;
import org.sufficientlysecure.keychain.ui.dialog.DeleteKeyDialogFragment;
import org.sufficientlysecure.keychain.ui.dialog.FileDialogFragment;
import org.sufficientlysecure.keychain.util.Log;
import java.lang.reflect.Array;
import java.security.Provider;
import java.util.ArrayList;
public class ExportHelper {
protected FileDialogFragment mFileDialog;
protected String mExportFilename;
@ -81,7 +75,7 @@ public class ExportHelper {
int type = keyType;
mExportFilename = data.getString(FileDialogFragment.MESSAGE_DATA_FILENAME);
if( data.getBoolean(FileDialogFragment.MESSAGE_DATA_CHECKED) ) {
if (data.getBoolean(FileDialogFragment.MESSAGE_DATA_CHECKED)) {
type = Id.type.public_secret_key;
}

View File

@ -1,7 +1,7 @@
/*
* Copyright (C) 2012 Dominik Schürmann <dominik@dominikschuermann.de>
* Copyright (C) 2010 Thialfihar <thi@thialfihar.org>
*
*
* 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
@ -30,7 +30,7 @@ import java.util.Vector;
* Singleton Implementation of a Preference Helper
*/
public class Preferences {
private static Preferences mPreferences;
private static Preferences sPreferences;
private SharedPreferences mSharedPreferences;
public static synchronized Preferences getPreferences(Context context) {
@ -38,10 +38,10 @@ public class Preferences {
}
public static synchronized Preferences getPreferences(Context context, boolean forceNew) {
if (mPreferences == null || forceNew) {
mPreferences = new Preferences(context);
if (sPreferences == null || forceNew) {
sPreferences = new Preferences(context);
}
return mPreferences;
return sPreferences;
}
private Preferences(Context context) {

View File

@ -65,14 +65,16 @@ public class PgpConversionHelper {
try {
while ((obj = factory.nextObject()) != null) {
PGPSecretKey secKey = null;
if(obj instanceof PGPSecretKey) {
if ((secKey = (PGPSecretKey)obj ) == null) {
if (obj instanceof PGPSecretKey) {
secKey = (PGPSecretKey) obj;
if (secKey == null) {
Log.e(Constants.TAG, "No keys given!");
}
keys.add(secKey);
} else if(obj instanceof PGPSecretKeyRing) { //master keys are sent as keyrings
} else if (obj instanceof PGPSecretKeyRing) { //master keys are sent as keyrings
PGPSecretKeyRing keyRing = null;
if ((keyRing = (PGPSecretKeyRing)obj) == null) {
keyRing = (PGPSecretKeyRing) obj;
if (keyRing == null) {
Log.e(Constants.TAG, "No keys given!");
}
@SuppressWarnings("unchecked")

View File

@ -684,7 +684,8 @@ public class PgpDecryptVerify {
}
private static boolean verifyPrimaryKeyBinding(PGPSignatureSubpacketVector pkts,
PGPPublicKey masterPublicKey, PGPPublicKey signingPublicKey) {
PGPPublicKey masterPublicKey,
PGPPublicKey signingPublicKey) {
boolean validPrimaryKeyBinding = false;
JcaPGPContentVerifierBuilderProvider contentVerifierBuilderProvider =
new JcaPGPContentVerifierBuilderProvider()

View File

@ -51,9 +51,9 @@ public class PgpHelper {
".*?(-----BEGIN PGP MESSAGE-----.*?-----END PGP MESSAGE-----).*", Pattern.DOTALL);
public static final Pattern PGP_CLEARTEXT_SIGNATURE = Pattern
.compile(
".*?(-----BEGIN PGP SIGNED MESSAGE-----.*?-----BEGIN PGP SIGNATURE-----.*?-----END PGP SIGNATURE-----).*",
Pattern.DOTALL);
.compile(".*?(-----BEGIN PGP SIGNED MESSAGE-----.*?-----" +
"BEGIN PGP SIGNATURE-----.*?-----END PGP SIGNATURE-----).*",
Pattern.DOTALL);
public static final Pattern PGP_PUBLIC_KEY = Pattern.compile(
".*?(-----BEGIN PGP PUBLIC KEY BLOCK-----.*?-----END PGP PUBLIC KEY BLOCK-----).*",

View File

@ -168,7 +168,8 @@ public class PgpImportExport {
return returnData;
}
public Bundle exportKeyRings(ArrayList<Long> publicKeyRingMasterIds, ArrayList<Long> secretKeyRingMasterIds,
public Bundle exportKeyRings(ArrayList<Long> publicKeyRingMasterIds,
ArrayList<Long> secretKeyRingMasterIds,
OutputStream outStream) throws PgpGeneralException,
PGPException, IOException {
Bundle returnData = new Bundle();

View File

@ -300,8 +300,7 @@ public class PgpKeyHelper {
return userId;
}
public static int getKeyUsage(PGPSecretKey key)
{
public static int getKeyUsage(PGPSecretKey key) {
return getKeyUsage(key.getPublicKey());
}
@ -310,13 +309,19 @@ public class PgpKeyHelper {
int usage = 0;
if (key.getVersion() >= 4) {
for (PGPSignature sig : new IterableIterator<PGPSignature>(key.getSignatures())) {
if (key.isMasterKey() && sig.getKeyID() != key.getKeyID()) continue;
if (key.isMasterKey() && sig.getKeyID() != key.getKeyID()) {
continue;
}
PGPSignatureSubpacketVector hashed = sig.getHashedSubPackets();
if (hashed != null) usage |= hashed.getKeyFlags();
if (hashed != null) {
usage |= hashed.getKeyFlags();
}
PGPSignatureSubpacketVector unhashed = sig.getUnhashedSubPackets();
if (unhashed != null) usage |= unhashed.getKeyFlags();
if (unhashed != null) {
usage |= unhashed.getKeyFlags();
}
}
}
return usage;

View File

@ -17,6 +17,8 @@
package org.sufficientlysecure.keychain.pgp;
import android.util.Pair;
import org.spongycastle.bcpg.CompressionAlgorithmTags;
import org.spongycastle.bcpg.HashAlgorithmTags;
import org.spongycastle.bcpg.SymmetricKeyAlgorithmTags;
@ -45,6 +47,7 @@ import org.spongycastle.openpgp.operator.jcajce.JcaPGPDigestCalculatorProviderBu
import org.spongycastle.openpgp.operator.jcajce.JcaPGPKeyPair;
import org.spongycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilder;
import org.spongycastle.openpgp.operator.jcajce.JcePBESecretKeyEncryptorBuilder;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.Id;
import org.sufficientlysecure.keychain.R;
@ -193,8 +196,8 @@ public class PgpKeyOperation {
}
public PGPSecretKeyRing changeSecretKeyPassphrase(PGPSecretKeyRing keyRing, String oldPassPhrase,
String newPassPhrase) throws IOException, PGPException,
NoSuchProviderException {
String newPassPhrase)
throws IOException, PGPException, NoSuchProviderException {
updateProgress(R.string.progress_building_key, 0, 100);
if (oldPassPhrase == null) {
@ -216,7 +219,7 @@ public class PgpKeyOperation {
}
private Pair<PGPSecretKeyRing,PGPPublicKeyRing> buildNewSecretKey(
private Pair<PGPSecretKeyRing, PGPPublicKeyRing> buildNewSecretKey(
ArrayList<String> userIds, ArrayList<PGPSecretKey> keys,
ArrayList<GregorianCalendar> keysExpiryDates,
ArrayList<Integer> keysUsages,
@ -267,13 +270,16 @@ public class PgpKeyOperation {
GregorianCalendar expiryDate = keysExpiryDates.get(0);
//note that the below, (a/c) - (b/c) is *not* the same as (a - b) /c
//here we purposefully ignore partial days in each date - long type has no fractional part!
long numDays = (expiryDate.getTimeInMillis() / 86400000) - (creationDate.getTimeInMillis() / 86400000);
if (numDays <= 0)
long numDays = (expiryDate.getTimeInMillis() / 86400000) -
(creationDate.getTimeInMillis() / 86400000);
if (numDays <= 0) {
throw new PgpGeneralMsgIdException(R.string.error_expiry_must_come_after_creation);
}
hashedPacketsGen.setKeyExpirationTime(false, numDays * 86400);
} else {
hashedPacketsGen.setKeyExpirationTime(false, 0); //do this explicitly, although since we're rebuilding,
//this happens anyway
hashedPacketsGen.setKeyExpirationTime(false, 0);
// do this explicitly, although since we're rebuilding,
// this happens anyway
}
updateProgress(R.string.progress_building_master_key, 30, 100);
@ -339,15 +345,16 @@ public class PgpKeyOperation {
GregorianCalendar expiryDate = keysExpiryDates.get(i);
//note that the below, (a/c) - (b/c) is *not* the same as (a - b) /c
//here we purposefully ignore partial days in each date - long type has no fractional part!
long numDays =
(expiryDate.getTimeInMillis() / 86400000) - (creationDate.getTimeInMillis() / 86400000);
long numDays = (expiryDate.getTimeInMillis() / 86400000) -
(creationDate.getTimeInMillis() / 86400000);
if (numDays <= 0) {
throw new PgpGeneralMsgIdException(R.string.error_expiry_must_come_after_creation);
}
hashedPacketsGen.setKeyExpirationTime(false, numDays * 86400);
} else {
hashedPacketsGen.setKeyExpirationTime(false, 0); //do this explicitly, although since we're rebuilding,
//this happens anyway
hashedPacketsGen.setKeyExpirationTime(false, 0);
// do this explicitly, although since we're rebuilding,
// this happens anyway
}
keyGen.addSubKey(subKeyPair, hashedPacketsGen.generate(), unhashedPacketsGen.generate());
@ -356,11 +363,11 @@ public class PgpKeyOperation {
PGPSecretKeyRing secretKeyRing = keyGen.generateSecretKeyRing();
PGPPublicKeyRing publicKeyRing = keyGen.generatePublicKeyRing();
return new Pair<PGPSecretKeyRing,PGPPublicKeyRing>(secretKeyRing, publicKeyRing);
return new Pair<PGPSecretKeyRing, PGPPublicKeyRing>(secretKeyRing, publicKeyRing);
}
public Pair<PGPSecretKeyRing,PGPPublicKeyRing> buildSecretKey (PGPSecretKeyRing mKR,
public Pair<PGPSecretKeyRing, PGPPublicKeyRing> buildSecretKey(PGPSecretKeyRing mKR,
PGPPublicKeyRing pKR,
SaveKeyringParcel saveParcel)
throws PgpGeneralMsgIdException, PGPException, SignatureException, IOException {
@ -444,22 +451,28 @@ public class PgpKeyOperation {
GregorianCalendar expiryDate = saveParcel.keysExpiryDates.get(0);
//note that the below, (a/c) - (b/c) is *not* the same as (a - b) /c
//here we purposefully ignore partial days in each date - long type has no fractional part!
long numDays = (expiryDate.getTimeInMillis() / 86400000) - (creationDate.getTimeInMillis() / 86400000);
if (numDays <= 0)
long numDays = (expiryDate.getTimeInMillis() / 86400000) -
(creationDate.getTimeInMillis() / 86400000);
if (numDays <= 0) {
throw new PgpGeneralMsgIdException(R.string.error_expiry_must_come_after_creation);
}
hashedPacketsGen.setKeyExpirationTime(false, numDays * 86400);
} else {
hashedPacketsGen.setKeyExpirationTime(false, 0); //do this explicitly, although since we're rebuilding,
//this happens anyway
hashedPacketsGen.setKeyExpirationTime(false, 0);
// do this explicitly, although since we're rebuilding,
// this happens anyway
}
if (saveParcel.primaryIDChanged || !saveParcel.originalIDs.get(0).equals(saveParcel.userIDs.get(0))) {
if (saveParcel.primaryIDChanged ||
!saveParcel.originalIDs.get(0).equals(saveParcel.userIDs.get(0))) {
anyIDChanged = true;
ArrayList<Pair<String, PGPSignature>> sigList = new ArrayList<Pair<String, PGPSignature>>();
for (String userId : saveParcel.userIDs) {
String origID = saveParcel.originalIDs.get(userIDIndex);
if ((origID.equals(userId) && !saveParcel.newIDs[userIDIndex]) && !userId.equals(saveParcel.originalPrimaryID) && userIDIndex != 0) {
Iterator<PGPSignature> origSigs = masterPublicKey.getSignaturesForID(origID); //TODO: make sure this iterator only has signatures we are interested in
if (origID.equals(userId) && !saveParcel.newIDs[userIDIndex] &&
!userId.equals(saveParcel.originalPrimaryID) && userIDIndex != 0) {
Iterator<PGPSignature> origSigs = masterPublicKey.getSignaturesForID(origID);
// TODO: make sure this iterator only has signatures we are interested in
while (origSigs.hasNext()) {
PGPSignature origSig = origSigs.next();
sigList.add(new Pair<String, PGPSignature>(origID, origSig));
@ -484,7 +497,8 @@ public class PgpKeyOperation {
userIDIndex++;
}
for (Pair<String, PGPSignature> toAdd : sigList) {
masterPublicKey = PGPPublicKey.addCertification(masterPublicKey, toAdd.first, toAdd.second);
masterPublicKey =
PGPPublicKey.addCertification(masterPublicKey, toAdd.first, toAdd.second);
}
} else {
for (String userId : saveParcel.userIDs) {
@ -505,7 +519,8 @@ public class PgpKeyOperation {
if (!saveParcel.newIDs[userIDIndex]) {
masterPublicKey = PGPPublicKey.removeCertification(masterPublicKey, origID);
}
masterPublicKey = PGPPublicKey.addCertification(masterPublicKey, userId, certification);
masterPublicKey =
PGPPublicKey.addCertification(masterPublicKey, userId, certification);
}
userIDIndex++;
}
@ -517,7 +532,8 @@ public class PgpKeyOperation {
for (String userId : saveParcel.userIDs) {
String origID = saveParcel.originalIDs.get(userIDIndex);
if (!(origID.equals(saveParcel.originalPrimaryID) && !saveParcel.primaryIDChanged)) {
Iterator<PGPSignature> sigs = masterPublicKey.getSignaturesForID(userId); //TODO: make sure this iterator only has signatures we are interested in
Iterator<PGPSignature> sigs = masterPublicKey.getSignaturesForID(userId);
// TODO: make sure this iterator only has signatures we are interested in
while (sigs.hasNext()) {
PGPSignature sig = sigs.next();
sigList.add(new Pair<String, PGPSignature>(userId, sig));
@ -602,23 +618,27 @@ public class PgpKeyOperation {
GregorianCalendar creationDate = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
creationDate.setTime(subPublicKey.getCreationTime());
GregorianCalendar expiryDate = saveParcel.keysExpiryDates.get(i);
//note that the below, (a/c) - (b/c) is *not* the same as (a - b) /c
//here we purposefully ignore partial days in each date - long type has no fractional part!
long numDays = (expiryDate.getTimeInMillis() / 86400000) - (creationDate.getTimeInMillis() / 86400000);
if (numDays <= 0)
// note that the below, (a/c) - (b/c) is *not* the same as (a - b) /c
// here we purposefully ignore partial days in each date - long type has
// no fractional part!
long numDays = (expiryDate.getTimeInMillis() / 86400000) -
(creationDate.getTimeInMillis() / 86400000);
if (numDays <= 0) {
throw new PgpGeneralMsgIdException(R.string.error_expiry_must_come_after_creation);
}
hashedPacketsGen.setKeyExpirationTime(false, numDays * 86400);
} else {
hashedPacketsGen.setKeyExpirationTime(false, 0); //do this explicitly, although since we're rebuilding,
//this happens anyway
hashedPacketsGen.setKeyExpirationTime(false, 0);
// do this explicitly, although since we're rebuilding,
// this happens anyway
}
keyGen.addSubKey(subKeyPair, hashedPacketsGen.generate(), unhashedPacketsGen.generate());
//certifications will be discarded if the key is changed, because I think, for a start,
//they will be invalid. Binding certs are regenerated anyway, and other certs which
//need to be kept are on IDs and attributes
//TODO: don't let revoked keys be edited, other than removed - changing one would result in the
//revocation being wrong?
// certifications will be discarded if the key is changed, because I think, for a start,
// they will be invalid. Binding certs are regenerated anyway, and other certs which
// need to be kept are on IDs and attributes
// TODO: don't let revoked keys be edited, other than removed - changing one would
// result in the revocation being wrong?
}
}
@ -657,8 +677,10 @@ public class PgpKeyOperation {
Log.d(Constants.TAG, " ------- in private key -------");
for(String uid : new IterableIterator<String>(secretKeyRing.getPublicKey().getUserIDs())) {
for(PGPSignature sig : new IterableIterator<PGPSignature>(secretKeyRing.getPublicKey().getSignaturesForID(uid))) {
Log.d(Constants.TAG, "sig: " + PgpKeyHelper.convertKeyIdToHex(sig.getKeyID()) + " for " + uid);
for(PGPSignature sig : new IterableIterator<PGPSignature>(
secretKeyRing.getPublicKey().getSignaturesForID(uid))) {
Log.d(Constants.TAG, "sig: " +
PgpKeyHelper.convertKeyIdToHex(sig.getKeyID()) + " for " + uid);
}
}
@ -666,14 +688,16 @@ public class PgpKeyOperation {
Log.d(Constants.TAG, " ------- in public key -------");
for(String uid : new IterableIterator<String>(publicKeyRing.getPublicKey().getUserIDs())) {
for(PGPSignature sig : new IterableIterator<PGPSignature>(publicKeyRing.getPublicKey().getSignaturesForID(uid))) {
Log.d(Constants.TAG, "sig: " + PgpKeyHelper.convertKeyIdToHex(sig.getKeyID()) + " for " + uid);
for(PGPSignature sig : new IterableIterator<PGPSignature>(
publicKeyRing.getPublicKey().getSignaturesForID(uid))) {
Log.d(Constants.TAG, "sig: " +
PgpKeyHelper.convertKeyIdToHex(sig.getKeyID()) + " for " + uid);
}
}
*/
return new Pair<PGPSecretKeyRing,PGPPublicKeyRing>(mKR, pKR);
return new Pair<PGPSecretKeyRing, PGPPublicKeyRing>(mKR, pKR);
}
@ -686,9 +710,10 @@ public class PgpKeyOperation {
* @param passphrase Passphrase of the secret key
* @return A keyring with added certifications
*/
public PGPPublicKey certifyKey(PGPSecretKey certificationKey, PGPPublicKey publicKey, List<String> userIds, String passphrase)
public PGPPublicKey certifyKey(PGPSecretKey certificationKey, PGPPublicKey publicKey,
List<String> userIds, String passphrase)
throws PgpGeneralMsgIdException, NoSuchAlgorithmException, NoSuchProviderException,
PGPException, SignatureException {
PGPException, SignatureException {
// create a signatureGenerator from the supplied masterKeyId and passphrase
PGPSignatureGenerator signatureGenerator; {
@ -720,7 +745,7 @@ public class PgpKeyOperation {
}
// fetch public key ring, add the certification and return it
for(String userId : new IterableIterator<String>(userIds.iterator())) {
for (String userId : new IterableIterator<String>(userIds.iterator())) {
PGPSignature sig = signatureGenerator.generateCertification(userId, publicKey);
publicKey = PGPPublicKey.addCertification(publicKey, userId, sig);
}

View File

@ -83,9 +83,10 @@ public class PgpToX509 {
* @throws Exception
* @author Bruno Harbulot
*/
public static X509Certificate createSelfSignedCert(PublicKey pubKey, PrivateKey privKey,
X509Name subject, Date startDate, Date endDate, String subjAltNameURI)
throws InvalidKeyException, IllegalStateException, NoSuchAlgorithmException,
public static X509Certificate createSelfSignedCert(
PublicKey pubKey, PrivateKey privKey, X509Name subject, Date startDate, Date endDate,
String subjAltNameURI)
throws InvalidKeyException, IllegalStateException, NoSuchAlgorithmException,
SignatureException, CertificateException, NoSuchProviderException {
X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();
@ -182,10 +183,10 @@ public class PgpToX509 {
/**
* Creates a self-signed certificate from a PGP Secret Key.
*
* @param pgpSecKey PGP Secret Key (from which one can extract the public and private keys and other
* attributes).
* @param pgpPrivKey PGP Private Key corresponding to the Secret Key (password callbacks should be done
* before calling this method)
* @param pgpSecKey PGP Secret Key (from which one can extract the public and private
* keys and other attributes).
* @param pgpPrivKey PGP Private Key corresponding to the Secret Key (password callbacks
* should be done before calling this method)
* @param subjAltNameURI optional URI to embed in the subject alternative-name
* @return self-signed certificate
* @throws PGPException
@ -196,9 +197,9 @@ public class PgpToX509 {
* @throws CertificateException
* @author Bruno Harbulot
*/
public static X509Certificate createSelfSignedCert(PGPSecretKey pgpSecKey,
PGPPrivateKey pgpPrivKey, String subjAltNameURI) throws PGPException,
NoSuchProviderException, InvalidKeyException, NoSuchAlgorithmException,
public static X509Certificate createSelfSignedCert(
PGPSecretKey pgpSecKey, PGPPrivateKey pgpPrivKey, String subjAltNameURI)
throws PGPException, NoSuchProviderException, InvalidKeyException, NoSuchAlgorithmException,
SignatureException, CertificateException {
// get public key from secret key
PGPPublicKey pgpPubKey = pgpSecKey.getPublicKey();

View File

@ -22,14 +22,14 @@ import android.content.Context;
public class PgpGeneralMsgIdException extends Exception {
static final long serialVersionUID = 0xf812773343L;
private final int msgId;
private final int mMessageId;
public PgpGeneralMsgIdException(int msgId) {
super("msg[" + msgId + "]");
this.msgId = msgId;
public PgpGeneralMsgIdException(int messageId) {
super("msg[" + messageId + "]");
mMessageId = messageId;
}
public PgpGeneralException getContextualized(Context context) {
return new PgpGeneralException(context.getString(msgId), this);
return new PgpGeneralException(context.getString(mMessageId), this);
}
}

View File

@ -283,12 +283,14 @@ public class KeychainContract {
/**
* Use if multiple items get returned
*/
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.thialfihar.apg.api_app.accounts";
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.thialfihar.apg.api_app.accounts";
/**
* Use if a single item is returned
*/
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.thialfihar.apg.api_app.account";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.thialfihar.apg.api_app.account";
public static Uri buildBaseUri(String packageName) {
return CONTENT_URI.buildUpon().appendEncodedPath(packageName).appendPath(PATH_ACCOUNTS)

View File

@ -23,8 +23,8 @@ import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.provider.KeychainContract.ApiAppsColumns;
import org.sufficientlysecure.keychain.provider.KeychainContract.ApiAppsAccountsColumns;
import org.sufficientlysecure.keychain.provider.KeychainContract.ApiAppsColumns;
import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRingsColumns;
import org.sufficientlysecure.keychain.provider.KeychainContract.KeysColumns;
import org.sufficientlysecure.keychain.provider.KeychainContract.UserIdsColumns;

View File

@ -296,8 +296,8 @@ public class ProviderHelper {
/**
* Build ContentProviderOperation to add PGPPublicKey to database corresponding to a keyRing
*/
private static ContentProviderOperation buildPublicKeyOperations(Context context,
long keyRingRowId, PGPPublicKey key, int rank) throws IOException {
private static ContentProviderOperation buildPublicKeyOperations(
Context context, long keyRingRowId, PGPPublicKey key, int rank) throws IOException {
ContentValues values = new ContentValues();
values.put(Keys.KEY_ID, key.getKeyID());
values.put(Keys.IS_MASTER_KEY, key.isMasterKey());
@ -324,8 +324,8 @@ public class ProviderHelper {
/**
* Build ContentProviderOperation to add PublicUserIds to database corresponding to a keyRing
*/
private static ContentProviderOperation buildPublicUserIdOperations(Context context,
long keyRingRowId, String userId, int rank) {
private static ContentProviderOperation buildPublicUserIdOperations(
Context context, long keyRingRowId, String userId, int rank) {
ContentValues values = new ContentValues();
values.put(UserIds.KEY_RING_ROW_ID, keyRingRowId);
values.put(UserIds.USER_ID, userId);
@ -339,8 +339,8 @@ public class ProviderHelper {
/**
* Build ContentProviderOperation to add PGPSecretKey to database corresponding to a keyRing
*/
private static ContentProviderOperation buildSecretKeyOperations(Context context,
long keyRingRowId, PGPSecretKey key, int rank) throws IOException {
private static ContentProviderOperation buildSecretKeyOperations(
Context context, long keyRingRowId, PGPSecretKey key, int rank) throws IOException {
ContentValues values = new ContentValues();
boolean hasPrivate = true;
@ -376,8 +376,8 @@ public class ProviderHelper {
/**
* Build ContentProviderOperation to add SecretUserIds to database corresponding to a keyRing
*/
private static ContentProviderOperation buildSecretUserIdOperations(Context context,
long keyRingRowId, String userId, int rank) {
private static ContentProviderOperation buildSecretUserIdOperations(
Context context, long keyRingRowId, String userId, int rank) {
ContentValues values = new ContentValues();
values.put(UserIds.KEY_RING_ROW_ID, keyRingRowId);
values.put(UserIds.USER_ID, userId);
@ -508,13 +508,14 @@ public class ProviderHelper {
*/
public static boolean getMasterKeyCanCertify(Context context, Uri queryUri) {
String[] projection = new String[]{
String[] projection = new String[] {
KeyRings.MASTER_KEY_ID,
"(SELECT COUNT(sign_keys." + Keys._ID + ") FROM " + Tables.KEYS
+ " AS sign_keys WHERE sign_keys." + Keys.KEY_RING_ROW_ID + " = "
+ KeychainDatabase.Tables.KEY_RINGS + "." + KeyRings._ID
+ " AND sign_keys." + Keys.CAN_CERTIFY + " = '1' AND " + Keys.IS_MASTER_KEY
+ " = 1) AS sign",};
+ " = 1) AS sign",
};
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(queryUri, projection, null, null, null);

View File

@ -17,10 +17,6 @@
package org.sufficientlysecure.keychain.remote;
import org.spongycastle.bcpg.HashAlgorithmTags;
import org.spongycastle.openpgp.PGPEncryptedData;
import org.sufficientlysecure.keychain.Id;
public class AppSettings {
private String mPackageName;
private byte[] mPackageSignature;

View File

@ -188,7 +188,8 @@ public class OpenPgpService extends RemoteService {
}
private Intent encryptAndSignImpl(Intent data, ParcelFileDescriptor input,
ParcelFileDescriptor output, AccountSettings accSettings, boolean sign) {
ParcelFileDescriptor output, AccountSettings accSettings,
boolean sign) {
try {
boolean asciiArmor = data.getBooleanExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true);
@ -292,7 +293,8 @@ public class OpenPgpService extends RemoteService {
PgpDecryptVerify.Builder builder = new PgpDecryptVerify.Builder(this, inputData, os);
builder.allowSymmetricDecryption(false) // no support for symmetric encryption
.allowedKeyIds(allowedKeyIds) // allow only private keys associated with accounts of this app
.allowedKeyIds(allowedKeyIds) // allow only private keys associated with
// accounts of this app
.passphrase(passphrase);
// TODO: currently does not support binary signed-only content
@ -300,9 +302,11 @@ public class OpenPgpService extends RemoteService {
if (PgpDecryptVerifyResult.KEY_PASSHRASE_NEEDED == decryptVerifyResult.getStatus()) {
// get PendingIntent for passphrase input, add it to given params and return to client
Intent passphraseBundle = getPassphraseBundleIntent(data, decryptVerifyResult.getKeyIdPassphraseNeeded());
Intent passphraseBundle =
getPassphraseBundleIntent(data, decryptVerifyResult.getKeyIdPassphraseNeeded());
return passphraseBundle;
} else if (PgpDecryptVerifyResult.SYMMETRIC_PASSHRASE_NEEDED == decryptVerifyResult.getStatus()) {
} else if (PgpDecryptVerifyResult.SYMMETRIC_PASSHRASE_NEEDED ==
decryptVerifyResult.getStatus()) {
throw new PgpGeneralException("Decryption of symmetric content not supported by API!");
}
@ -455,7 +459,8 @@ public class OpenPgpService extends RemoteService {
} else if (OpenPgpApi.ACTION_DECRYPT_VERIFY.equals(action)) {
String currentPkg = getCurrentCallingPackage();
Set<Long> allowedKeyIds =
ProviderHelper.getAllKeyIdsForApp(mContext, KeychainContract.ApiAccounts.buildBaseUri(currentPkg));
ProviderHelper.getAllKeyIdsForApp(mContext,
KeychainContract.ApiAccounts.buildBaseUri(currentPkg));
return decryptAndVerifyImpl(data, input, output, allowedKeyIds);
} else if (OpenPgpApi.ACTION_GET_KEY.equals(action)) {
return getKeyImpl(data);

View File

@ -243,7 +243,8 @@ public abstract class RemoteService extends Service {
return true;
} else {
throw new WrongPackageSignatureException(
"PACKAGE NOT ALLOWED! Signature wrong! (Signature not equals signature from database)");
"PACKAGE NOT ALLOWED! Signature wrong! (Signature not " +
"equals signature from database)");
}
}

View File

@ -69,7 +69,8 @@ public class AccountSettingsFragment extends Fragment implements
this.mAccSettings = accountSettings;
mAccNameView.setText(accountSettings.getAccountName());
Uri keyUri = KeychainContract.KeyRings.buildSecretKeyRingsByMasterKeyIdUri(String.valueOf(accountSettings.getKeyId()));
Uri keyUri = KeychainContract.KeyRings.buildSecretKeyRingsByMasterKeyIdUri(
String.valueOf(accountSettings.getKeyId()));
mSelectKeyFragment.selectKey(keyUri);
mEncryptionAlgorithm.setSelection(mEncryptionAdapter.getPosition(accountSettings
.getEncryptionAlgorithm()));

View File

@ -32,12 +32,10 @@ import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.Id;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.provider.KeychainContract;
import org.sufficientlysecure.keychain.ui.widget.FixedListView;

View File

@ -37,11 +37,9 @@ import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.provider.KeychainContract;
import org.sufficientlysecure.keychain.provider.KeychainContract.ApiApps;
import org.sufficientlysecure.keychain.util.Log;
public class AppsListFragment extends ListFragment implements
LoaderManager.LoaderCallbacks<Cursor> {

View File

@ -95,7 +95,7 @@ public class RemoteServiceActivity extends ActionBarActivity {
if (ACTION_REGISTER.equals(action)) {
final String packageName = extras.getString(EXTRA_PACKAGE_NAME);
final byte[] packageSignature = extras.getByteArray(EXTRA_PACKAGE_SIGNATURE);
Log.d(Constants.TAG, "ACTION_REGISTER packageName: "+packageName);
Log.d(Constants.TAG, "ACTION_REGISTER packageName: " + packageName);
// Inflate a "Done"/"Cancel" custom action bar view
ActionBarHelper.setTwoButtonView(getSupportActionBar(),

View File

@ -36,8 +36,6 @@ import org.sufficientlysecure.keychain.helper.Preferences;
import org.sufficientlysecure.keychain.pgp.*;
import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException;
import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralMsgIdException;
import org.sufficientlysecure.keychain.provider.KeychainContract;
import org.sufficientlysecure.keychain.provider.KeychainContract.DataStream;
import org.sufficientlysecure.keychain.provider.ProviderHelper;
import org.sufficientlysecure.keychain.ui.adapter.ImportKeysListEntry;
import org.sufficientlysecure.keychain.util.*;
@ -487,10 +485,13 @@ public class KeychainIntentService extends IntentService
ProviderHelper.saveKeyRing(this, keyRing);
setProgress(R.string.progress_done, 100, 100);
} else {
PgpKeyOperation keyOperations = new PgpKeyOperation(new ProgressScaler(this, 0, 90, 100));
PGPSecretKeyRing privkey = ProviderHelper.getPGPSecretKeyRingByMasterKeyId(this, masterKeyId);
PGPPublicKeyRing pubkey = ProviderHelper.getPGPPublicKeyRingByMasterKeyId(this, masterKeyId);
PgpKeyOperation.Pair<PGPSecretKeyRing,PGPPublicKeyRing> pair =
PgpKeyOperation keyOperations =
new PgpKeyOperation(new ProgressScaler(this, 0, 90, 100));
PGPSecretKeyRing privkey =
ProviderHelper.getPGPSecretKeyRingByMasterKeyId(this, masterKeyId);
PGPPublicKeyRing pubkey =
ProviderHelper.getPGPPublicKeyRingByMasterKeyId(this, masterKeyId);
PgpKeyOperation.Pair<PGPSecretKeyRing, PGPPublicKeyRing> pair =
keyOperations.buildSecretKey(privkey, pubkey, saveParams);
setProgress(R.string.progress_saving_key_ring, 90, 100);
ProviderHelper.saveKeyRing(this, pair.first);
@ -747,11 +748,14 @@ public class KeychainIntentService extends IntentService
// verify downloaded key by comparing fingerprints
if (entry.getFingerPrintHex() != null) {
String downloadedKeyFp = PgpKeyHelper.convertFingerprintToHex(downloadedKey.getPublicKey().getFingerprint());
String downloadedKeyFp = PgpKeyHelper.convertFingerprintToHex(
downloadedKey.getPublicKey().getFingerprint());
if (downloadedKeyFp.equals(entry.getFingerPrintHex())) {
Log.d(Constants.TAG, "fingerprint of downloaded key is the same as the requested fingerprint!");
Log.d(Constants.TAG, "fingerprint of downloaded key is the same as " +
"the requested fingerprint!");
} else {
throw new PgpGeneralException("fingerprint of downloaded key is NOT the same as the requested fingerprint!");
throw new PgpGeneralException("fingerprint of downloaded key is " +
"NOT the same as the requested fingerprint!");
}
}
@ -820,7 +824,7 @@ public class KeychainIntentService extends IntentService
return;
}
// contextualize the exception, if necessary
if(e instanceof PgpGeneralMsgIdException) {
if (e instanceof PgpGeneralMsgIdException) {
e = ((PgpGeneralMsgIdException) e).getContextualized(this);
}
Log.e(Constants.TAG, "ApgService Exception: ", e);

View File

@ -25,14 +25,16 @@ import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.*;
import android.util.Log;
import android.support.v4.util.LongSparseArray;
import android.util.Log;
import org.spongycastle.openpgp.PGPException;
import org.spongycastle.openpgp.PGPPrivateKey;
import org.spongycastle.openpgp.PGPSecretKey;
import org.spongycastle.openpgp.PGPSecretKeyRing;
import org.spongycastle.openpgp.operator.PBESecretKeyDecryptor;
import org.spongycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilder;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.Id;
import org.sufficientlysecure.keychain.helper.Preferences;

View File

@ -46,20 +46,20 @@ public class SaveKeyringParcel implements Parcelable {
public SaveKeyringParcel() {}
private SaveKeyringParcel(Parcel source)
{
userIDs = (ArrayList<String>)source.readSerializable();
originalIDs = (ArrayList<String>)source.readSerializable();
deletedIDs = (ArrayList<String>)source.readSerializable();
private SaveKeyringParcel(Parcel source) {
userIDs = (ArrayList<String>) source.readSerializable();
originalIDs = (ArrayList<String>) source.readSerializable();
deletedIDs = (ArrayList<String>) source.readSerializable();
newIDs = source.createBooleanArray();
primaryIDChanged = source.readByte() != 0;
moddedKeys = source.createBooleanArray();
byte[] tmp = source.createByteArray();
if (tmp == null)
if (tmp == null) {
deletedKeys = null;
else
} else {
deletedKeys = PgpConversionHelper.BytesToPGPSecretKeyList(tmp);
keysExpiryDates = (ArrayList<GregorianCalendar>)source.readSerializable();
}
keysExpiryDates = (ArrayList<GregorianCalendar>) source.readSerializable();
keysUsages = source.readArrayList(Integer.class.getClassLoader());
newPassPhrase = source.readString();
oldPassPhrase = source.readString();
@ -69,8 +69,7 @@ public class SaveKeyringParcel implements Parcelable {
}
@Override
public void writeToParcel(Parcel destination, int flags)
{
public void writeToParcel(Parcel destination, int flags) {
destination.writeSerializable(userIDs); //might not be the best method to store.
destination.writeSerializable(originalIDs);
destination.writeSerializable(deletedIDs);
@ -78,8 +77,9 @@ public class SaveKeyringParcel implements Parcelable {
destination.writeByte((byte) (primaryIDChanged ? 1 : 0));
destination.writeBooleanArray(moddedKeys);
byte[] tmp = null;
if (deletedKeys.size() != 0)
if (deletedKeys.size() != 0) {
tmp = PgpConversionHelper.PGPSecretKeyArrayListToBytes(deletedKeys);
}
destination.writeByteArray(tmp);
destination.writeSerializable(keysExpiryDates);
destination.writeList(keysUsages);
@ -101,8 +101,7 @@ public class SaveKeyringParcel implements Parcelable {
};
@Override
public int describeContents()
{
public int describeContents() {
return 0;
}
}

View File

@ -1,7 +1,7 @@
/*
* Copyright (C) 2014 Dominik Schürmann <dominik@dominikschuermann.de>
* Copyright (C) 2011 Senecaso
*
*
* 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
@ -38,7 +38,6 @@ import com.beardedhen.androidbootstrap.BootstrapButton;
import org.spongycastle.openpgp.PGPPublicKeyRing;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.helper.OtherHelper;
import org.sufficientlysecure.keychain.helper.Preferences;
import org.sufficientlysecure.keychain.pgp.PgpKeyHelper;
import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException;
@ -213,7 +212,8 @@ public class CertifyKeyActivity extends ActionBarActivity implements
fingerprintBlob = ProviderHelper.getFingerprint(this, mDataUri);
}
String fingerprint = PgpKeyHelper.convertFingerprintToHex(fingerprintBlob);
((TextView) findViewById(R.id.fingerprint)).setText(PgpKeyHelper.colorizeFingerprint(fingerprint));
((TextView) findViewById(R.id.fingerprint))
.setText(PgpKeyHelper.colorizeFingerprint(fingerprint));
}
break;
case LOADER_ID_USER_IDS:
@ -307,7 +307,7 @@ public class CertifyKeyActivity extends ActionBarActivity implements
// Bail out if there is not at least one user id selected
ArrayList<String> userIds = mUserIdsAdapter.getSelectedUserIds();
if(userIds.isEmpty()) {
if (userIds.isEmpty()) {
Toast.makeText(CertifyKeyActivity.this, "No User IDs to sign selected!",
Toast.LENGTH_SHORT).show();
return;

View File

@ -77,8 +77,10 @@ public class DecryptActivity extends DrawerActivity {
// Handle intent actions, maybe changes the bundles
handleActions(getIntent());
mTabsAdapter.addTab(DecryptMessageFragment.class, mMessageFragmentBundle, getString(R.string.label_message));
mTabsAdapter.addTab(DecryptFileFragment.class, mFileFragmentBundle, getString(R.string.label_file));
mTabsAdapter.addTab(DecryptMessageFragment.class,
mMessageFragmentBundle, getString(R.string.label_message));
mTabsAdapter.addTab(DecryptFileFragment.class,
mFileFragmentBundle, getString(R.string.label_file));
mViewPager.setCurrentItem(mSwitchToTab);
}
@ -164,7 +166,8 @@ public class DecryptActivity extends DrawerActivity {
mSwitchToTab = PAGER_TAB_FILE;
} else {
Log.e(Constants.TAG,
"Direct binary data without actual file in filesystem is not supported. Please use the Remote Service API!");
"Direct binary data without actual file in filesystem is not supported. " +
"Please use the Remote Service API!");
Toast.makeText(this, R.string.error_only_files_are_supported, Toast.LENGTH_LONG)
.show();
// end activity

View File

@ -200,12 +200,13 @@ public class DecryptFileFragment extends DecryptFragment {
if (PgpDecryptVerifyResult.KEY_PASSHRASE_NEEDED == decryptVerifyResult.getStatus()) {
showPassphraseDialog(decryptVerifyResult.getKeyIdPassphraseNeeded());
} else if (PgpDecryptVerifyResult.SYMMETRIC_PASSHRASE_NEEDED == decryptVerifyResult.getStatus()) {
} else if (PgpDecryptVerifyResult.SYMMETRIC_PASSHRASE_NEEDED ==
decryptVerifyResult.getStatus()) {
showPassphraseDialog(Id.key.symmetric);
} else {
AppMsg.makeText(getActivity(), R.string.decryption_successful,
AppMsg.STYLE_INFO).show();
if (mDeleteAfter.isChecked()) {
// Create and show dialog to delete original file
DeleteFileDialogFragment deleteFileDialog = DeleteFileDialogFragment

View File

@ -154,7 +154,8 @@ public class DecryptMessageFragment extends DecryptFragment {
if (PgpDecryptVerifyResult.KEY_PASSHRASE_NEEDED == decryptVerifyResult.getStatus()) {
showPassphraseDialog(decryptVerifyResult.getKeyIdPassphraseNeeded());
} else if (PgpDecryptVerifyResult.SYMMETRIC_PASSHRASE_NEEDED == decryptVerifyResult.getStatus()) {
} else if (PgpDecryptVerifyResult.SYMMETRIC_PASSHRASE_NEEDED ==
decryptVerifyResult.getStatus()) {
showPassphraseDialog(Id.key.symmetric);
} else {
AppMsg.makeText(getActivity(), R.string.decryption_successful,

View File

@ -58,7 +58,7 @@ public class DrawerActivity extends ActionBarActivity {
// if the left margin of the loaded layout is close to the
// one used in tablets then set drawer as open and locked
if( Math.abs(leftMarginLoaded - leftMarginInTablets) < errorInMarginAllowed) {
if (Math.abs(leftMarginLoaded - leftMarginInTablets) < errorInMarginAllowed) {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN, mDrawerList);
mDrawerLayout.setScrimColor(Color.TRANSPARENT);
mIsDrawerLocked = true;
@ -82,7 +82,7 @@ public class DrawerActivity extends ActionBarActivity {
// enable ActionBar app icon to behave as action to toggle nav drawer
// if the drawer is not locked
if ( !mIsDrawerLocked ) {
if (!mIsDrawerLocked) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
@ -109,7 +109,7 @@ public class DrawerActivity extends ActionBarActivity {
}
};
if ( !mIsDrawerLocked ) {
if (!mIsDrawerLocked) {
mDrawerLayout.setDrawerListener(mDrawerToggle);
} else {
// If the drawer is locked open make it un-focusable
@ -218,9 +218,9 @@ public class DrawerActivity extends ActionBarActivity {
// setTitle(mDrawerTitles[position]);
// If drawer isn't locked just close the drawer and
// it will move to the selected item by itself (via drawer toggle listener)
if ( !mIsDrawerLocked ) {
if (!mIsDrawerLocked) {
mDrawerLayout.closeDrawer(mDrawerList);
// else move to the selected item yourself
// else move to the selected item yourself
} else {
callIntentForDrawerItem(mSelectedItem);
}

View File

@ -47,6 +47,7 @@ import com.devspark.appmsg.AppMsg;
import org.spongycastle.openpgp.PGPSecretKey;
import org.spongycastle.openpgp.PGPSecretKeyRing;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.Id;
import org.sufficientlysecure.keychain.R;
@ -124,7 +125,6 @@ public class EditKeyActivity extends ActionBarActivity implements EditorListener
public void somethingChanged() {
ActivityCompat.invalidateOptionsMenu(this);
//Toast.makeText(this, "Needs saving: " + Boolean.toString(mNeedsSaving) + "(" + Boolean.toString(mUserIdsView.needsSaving()) + ", " + Boolean.toString(mKeysView.needsSaving()) + ")", Toast.LENGTH_LONG).show();
}
public void onDeleted(Editor e, boolean wasNewItem) {
@ -328,7 +328,9 @@ public class EditKeyActivity extends ActionBarActivity implements EditorListener
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
cancelClicked(); //TODO: why isn't this triggered on my tablet - one of many ui problems I've had with this device. A code compatibility issue or a Samsung fail?
cancelClicked();
// TODO: why isn't this triggered on my tablet - one of many ui problems
// I've had with this device. A code compatibility issue or a Samsung fail?
return true;
case R.id.menu_key_edit_cancel:
cancelClicked();
@ -338,9 +340,9 @@ public class EditKeyActivity extends ActionBarActivity implements EditorListener
Toast.makeText(this, R.string.error_save_first, Toast.LENGTH_LONG).show();
} else {
long masterKeyId = ProviderHelper.getMasterKeyId(this, mDataUri);
long[] ids = new long[]{masterKeyId};
mExportHelper.showExportKeysDialog(ids, Id.type.secret_key, Constants.Path.APP_DIR_FILE_SEC,
null);
long[] ids = new long[] {masterKeyId};
mExportHelper.showExportKeysDialog(
ids, Id.type.secret_key, Constants.Path.APP_DIR_FILE_SEC, null);
return true;
}
return true;
@ -389,8 +391,9 @@ public class EditKeyActivity extends ActionBarActivity implements EditorListener
if (!isSet) {
isSet = true;
String[] parts = PgpKeyHelper.splitUserId(userId);
if (parts[0] != null)
if (parts[0] != null) {
setTitle(parts[0]);
}
}
mUserIds.add(userId);
}
@ -545,10 +548,11 @@ public class EditKeyActivity extends ActionBarActivity implements EditorListener
}
String passphrase;
if (mIsPassPhraseSet)
if (mIsPassPhraseSet) {
passphrase = PassphraseCacheService.getCachedPassphrase(this, masterKeyId);
else
} else {
passphrase = "";
}
if (passphrase == null) {
showPassphraseDialog(masterKeyId);
} else {

View File

@ -155,12 +155,16 @@ public class EncryptActivity extends DrawerActivity implements
// Handle intent actions
handleActions(getIntent());
mTabsAdapterMode.addTab(EncryptAsymmetricFragment.class, mAsymmetricFragmentBundle, getString(R.string.label_asymmetric));
mTabsAdapterMode.addTab(EncryptSymmetricFragment.class, mSymmetricFragmentBundle, getString(R.string.label_symmetric));
mTabsAdapterMode.addTab(EncryptAsymmetricFragment.class,
mAsymmetricFragmentBundle, getString(R.string.label_asymmetric));
mTabsAdapterMode.addTab(EncryptSymmetricFragment.class,
mSymmetricFragmentBundle, getString(R.string.label_symmetric));
mViewPagerMode.setCurrentItem(mSwitchToMode);
mTabsAdapterContent.addTab(EncryptMessageFragment.class, mMessageFragmentBundle, getString(R.string.label_message));
mTabsAdapterContent.addTab(EncryptFileFragment.class, mFileFragmentBundle, getString(R.string.label_file));
mTabsAdapterContent.addTab(EncryptMessageFragment.class,
mMessageFragmentBundle, getString(R.string.label_message));
mTabsAdapterContent.addTab(EncryptFileFragment.class,
mFileFragmentBundle, getString(R.string.label_file));
mViewPagerContent.setCurrentItem(mSwitchToContent);
}
@ -212,8 +216,10 @@ public class EncryptActivity extends DrawerActivity implements
long[] encryptionKeyIds = extras.getLongArray(EXTRA_ENCRYPTION_KEY_IDS);
// preselect keys given by intent
mAsymmetricFragmentBundle.putLongArray(EncryptAsymmetricFragment.ARG_ENCRYPTION_KEY_IDS, encryptionKeyIds);
mAsymmetricFragmentBundle.putLong(EncryptAsymmetricFragment.ARG_SIGNATURE_KEY_ID, signatureKeyId);
mAsymmetricFragmentBundle.putLongArray(EncryptAsymmetricFragment.ARG_ENCRYPTION_KEY_IDS,
encryptionKeyIds);
mAsymmetricFragmentBundle.putLong(EncryptAsymmetricFragment.ARG_SIGNATURE_KEY_ID,
signatureKeyId);
mSwitchToMode = PAGER_MODE_ASYMMETRIC;
/**
@ -234,7 +240,8 @@ public class EncryptActivity extends DrawerActivity implements
mSwitchToContent = PAGER_CONTENT_FILE;
} else {
Log.e(Constants.TAG,
"Direct binary data without actual file in filesystem is not supported by Intents. Please use the Remote Service API!");
"Direct binary data without actual file in filesystem is not supported " +
"by Intents. Please use the Remote Service API!");
Toast.makeText(this, R.string.error_only_files_are_supported, Toast.LENGTH_LONG)
.show();
// end activity

View File

@ -264,8 +264,8 @@ public class EncryptAsymmetricFragment extends Fragment {
case RESULT_CODE_SECRET_KEYS: {
if (resultCode == Activity.RESULT_OK) {
Uri uri_master_key = data.getData();
setSignatureKeyId(Long.valueOf(uri_master_key.getLastPathSegment()));
Uri uriMasterKey = data.getData();
setSignatureKeyId(Long.valueOf(uriMasterKey.getLastPathSegment()));
} else {
setSignatureKeyId(Id.key.none);
}

View File

@ -112,7 +112,7 @@ public class EncryptFileFragment extends Fragment {
});
mFileCompression = (Spinner) view.findViewById(R.id.fileCompression);
Choice[] choices = new Choice[]{
Choice[] choices = new Choice[] {
new Choice(Id.choice.compression.none, getString(R.string.choice_none) + " ("
+ getString(R.string.compression_fast) + ")"),
new Choice(Id.choice.compression.zip, "ZIP ("
@ -120,7 +120,8 @@ public class EncryptFileFragment extends Fragment {
new Choice(Id.choice.compression.zlib, "ZLIB ("
+ getString(R.string.compression_fast) + ")"),
new Choice(Id.choice.compression.bzip2, "BZIP2 ("
+ getString(R.string.compression_very_slow) + ")"),};
+ getString(R.string.compression_very_slow) + ")"),
};
ArrayAdapter<Choice> adapter = new ArrayAdapter<Choice>(getActivity(),
android.R.layout.simple_spinner_item, choices);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
@ -252,8 +253,9 @@ public class EncryptFileFragment extends Fragment {
return;
}
if (mEncryptInterface.getSignatureKey() != 0
&& PassphraseCacheService.getCachedPassphrase(getActivity(), mEncryptInterface.getSignatureKey()) == null) {
if (mEncryptInterface.getSignatureKey() != 0 &&
PassphraseCacheService.getCachedPassphrase(getActivity(),
mEncryptInterface.getSignatureKey()) == null) {
showPassphraseDialog();
return;
@ -282,8 +284,10 @@ public class EncryptFileFragment extends Fragment {
}
data.putString(KeychainIntentService.ENCRYPT_SYMMETRIC_PASSPHRASE, passphrase);
} else {
data.putLong(KeychainIntentService.ENCRYPT_SIGNATURE_KEY_ID, mEncryptInterface.getSignatureKey());
data.putLongArray(KeychainIntentService.ENCRYPT_ENCRYPTION_KEYS_IDS, mEncryptInterface.getEncryptionKeys());
data.putLong(KeychainIntentService.ENCRYPT_SIGNATURE_KEY_ID,
mEncryptInterface.getSignatureKey());
data.putLongArray(KeychainIntentService.ENCRYPT_ENCRYPTION_KEYS_IDS,
mEncryptInterface.getEncryptionKeys());
}
Log.d(Constants.TAG, "mInputFilename=" + mInputFilename + ", mOutputFilename="

View File

@ -150,8 +150,9 @@ public class EncryptMessageFragment extends Fragment {
return;
}
if (mEncryptInterface.getSignatureKey() != 0
&& PassphraseCacheService.getCachedPassphrase(getActivity(), mEncryptInterface.getSignatureKey()) == null) {
if (mEncryptInterface.getSignatureKey() != 0 &&
PassphraseCacheService.getCachedPassphrase(getActivity(),
mEncryptInterface.getSignatureKey()) == null) {
showPassphraseDialog(toClipboard);
return;
@ -182,8 +183,10 @@ public class EncryptMessageFragment extends Fragment {
}
data.putString(KeychainIntentService.ENCRYPT_SYMMETRIC_PASSPHRASE, passphrase);
} else {
data.putLong(KeychainIntentService.ENCRYPT_SIGNATURE_KEY_ID, mEncryptInterface.getSignatureKey());
data.putLongArray(KeychainIntentService.ENCRYPT_ENCRYPTION_KEYS_IDS, mEncryptInterface.getEncryptionKeys());
data.putLong(KeychainIntentService.ENCRYPT_SIGNATURE_KEY_ID,
mEncryptInterface.getSignatureKey());
data.putLongArray(KeychainIntentService.ENCRYPT_ENCRYPTION_KEYS_IDS,
mEncryptInterface.getEncryptionKeys());
boolean signOnly = (mEncryptInterface.getEncryptionKeys() == null
|| mEncryptInterface.getEncryptionKeys().length == 0);

View File

@ -1,7 +1,7 @@
/*
* Copyright (C) 2012-2014 Dominik Schürmann <dominik@dominikschuermann.de>
* Copyright (C) 2011 Senecaso
*
*
* 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
@ -168,7 +168,8 @@ public class ImportKeysActivity extends DrawerActivity implements ActionBar.OnNa
}
} else {
Log.e(Constants.TAG,
"IMPORT_KEY_FROM_KEYSERVER action needs to contain the 'query', 'key_id', or 'fingerprint' extra!");
"IMPORT_KEY_FROM_KEYSERVER action needs to contain the 'query', 'key_id', or " +
"'fingerprint' extra!");
return;
}
@ -233,7 +234,7 @@ public class ImportKeysActivity extends DrawerActivity implements ActionBar.OnNa
* onNavigationItemSelected() should check whether the Fragment is already in existence
* inside your Activity."
* <p/>
* from http://stackoverflow.com/questions/10983396/fragment-oncreateview-and-onactivitycreated-called-twice/14295474#14295474
* from http://bit.ly/1dBYThO
* <p/>
* In our case, if we start ImportKeysActivity with parameters to directly search using a fingerprint,
* the fragment would be loaded twice resulting in the query being empty after the second load.
@ -337,7 +338,8 @@ public class ImportKeysActivity extends DrawerActivity implements ActionBar.OnNa
// } else {
// status.putString(
// EXTRA_ERROR,
// "Scanned fingerprint does NOT match the fingerprint of the received key. You shouldnt trust this key.");
// "Scanned fingerprint does NOT match the fingerprint of the received key. " +
// "You shouldnt trust this key.");
// }
// }
// } catch (QueryException e) {

View File

@ -65,7 +65,7 @@ public class ImportKeysClipboardFragment extends Fragment {
String sendText = "";
if (clipboardText != null) {
sendText = clipboardText.toString();
if(sendText.toLowerCase(Locale.ENGLISH).startsWith(Constants.FINGERPRINT_SCHEME)) {
if (sendText.toLowerCase(Locale.ENGLISH).startsWith(Constants.FINGERPRINT_SCHEME)) {
mImportActivity.loadFromFingerprintUri(null, Uri.parse(sendText));
return;
}

View File

@ -17,6 +17,8 @@
package org.sufficientlysecure.keychain.ui;
import com.google.zxing.integration.android.IntentResult;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
@ -28,8 +30,9 @@ import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.beardedhen.androidbootstrap.BootstrapButton;
import com.google.zxing.integration.android.IntentResult;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.util.IntentIntegratorSupportV4;

View File

@ -66,11 +66,13 @@ public class KeyListActivity extends DrawerActivity {
return true;
case R.id.menu_key_list_export_public:
mExportHelper.showExportKeysDialog(null, Id.type.public_key, Constants.Path.APP_DIR_FILE_PUB, null);
mExportHelper.showExportKeysDialog(null,
Id.type.public_key, Constants.Path.APP_DIR_FILE_PUB, null);
return true;
case R.id.menu_key_list_secret_export:
mExportHelper.showExportKeysDialog(null, Id.type.secret_key, Constants.Path.APP_DIR_FILE_SEC, null);
mExportHelper.showExportKeysDialog(null, Id.type.secret_key,
Constants.Path.APP_DIR_FILE_SEC, null);
return true;
default:

View File

@ -185,17 +185,20 @@ public class KeyListFragment extends Fragment
}
case R.id.menu_key_list_multi_export: {
ids = mStickyList.getWrappedList().getCheckedItemIds();
long[] masterKeyIds = new long[2*ids.length];
long[] masterKeyIds = new long[2 * ids.length];
ArrayList<Long> allPubRowIds =
ProviderHelper.getPublicKeyRingsRowIds(getActivity());
for (int i = 0; i < ids.length; i++) {
if (allPubRowIds.contains(ids[i])) {
masterKeyIds[i] = ProviderHelper.getPublicMasterKeyId(getActivity(), ids[i]);
masterKeyIds[i] =
ProviderHelper.getPublicMasterKeyId(getActivity(), ids[i]);
} else {
masterKeyIds[i] = ProviderHelper.getSecretMasterKeyId(getActivity(), ids[i]);
masterKeyIds[i] =
ProviderHelper.getSecretMasterKeyId(getActivity(), ids[i]);
}
}
ExportHelper mExportHelper = new ExportHelper((ActionBarActivity) getActivity());
ExportHelper mExportHelper =
new ExportHelper((ActionBarActivity) getActivity());
mExportHelper
.showExportKeysDialog(masterKeyIds, Id.type.public_key,
Constants.Path.APP_DIR_FILE_PUB,

View File

@ -38,11 +38,11 @@ public class PreferencesActivity extends PreferenceActivity {
public static final String ACTION_PREFS_ADV = "org.sufficientlysecure.keychain.ui.PREFS_ADV";
private PreferenceScreen mKeyServerPreference = null;
private static Preferences mPreferences;
private static Preferences sPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
mPreferences = Preferences.getPreferences(this);
sPreferences = Preferences.getPreferences(this);
super.onCreate(savedInstanceState);
// final ActionBar actionBar = getSupportActionBar();
@ -59,7 +59,7 @@ public class PreferencesActivity extends PreferenceActivity {
(IntegerListPreference) findPreference(Constants.Pref.PASS_PHRASE_CACHE_TTL));
mKeyServerPreference = (PreferenceScreen) findPreference(Constants.Pref.KEY_SERVERS);
String servers[] = mPreferences.getKeyServers();
String servers[] = sPreferences.getKeyServers();
mKeyServerPreference.setSummary(getResources().getQuantityString(R.plurals.n_key_servers,
servers.length, servers.length));
mKeyServerPreference
@ -68,7 +68,7 @@ public class PreferencesActivity extends PreferenceActivity {
Intent intent = new Intent(PreferencesActivity.this,
PreferencesKeyServerActivity.class);
intent.putExtra(PreferencesKeyServerActivity.EXTRA_KEY_SERVERS,
mPreferences.getKeyServers());
sPreferences.getKeyServers());
startActivityForResult(intent, Id.request.key_server_preference);
return false;
}
@ -125,7 +125,7 @@ public class PreferencesActivity extends PreferenceActivity {
}
String servers[] = data
.getStringArrayExtra(PreferencesKeyServerActivity.EXTRA_KEY_SERVERS);
mPreferences.setKeyServers(servers);
sPreferences.setKeyServers(servers);
mKeyServerPreference.setSummary(getResources().getQuantityString(
R.plurals.n_key_servers, servers.length, servers.length));
break;
@ -163,7 +163,7 @@ public class PreferencesActivity extends PreferenceActivity {
(IntegerListPreference) findPreference(Constants.Pref.PASS_PHRASE_CACHE_TTL));
mKeyServerPreference = (PreferenceScreen) findPreference(Constants.Pref.KEY_SERVERS);
String servers[] = mPreferences.getKeyServers();
String servers[] = sPreferences.getKeyServers();
mKeyServerPreference.setSummary(getResources().getQuantityString(R.plurals.n_key_servers,
servers.length, servers.length));
mKeyServerPreference
@ -172,7 +172,7 @@ public class PreferencesActivity extends PreferenceActivity {
Intent intent = new Intent(getActivity(),
PreferencesKeyServerActivity.class);
intent.putExtra(PreferencesKeyServerActivity.EXTRA_KEY_SERVERS,
mPreferences.getKeyServers());
sPreferences.getKeyServers());
startActivityForResult(intent, Id.request.key_server_preference);
return false;
}
@ -188,7 +188,7 @@ public class PreferencesActivity extends PreferenceActivity {
}
String servers[] = data
.getStringArrayExtra(PreferencesKeyServerActivity.EXTRA_KEY_SERVERS);
mPreferences.setKeyServers(servers);
sPreferences.setKeyServers(servers);
mKeyServerPreference.setSummary(getResources().getQuantityString(
R.plurals.n_key_servers, servers.length, servers.length));
break;
@ -256,14 +256,14 @@ public class PreferencesActivity extends PreferenceActivity {
}
private static void initializePassPassPhraceCacheTtl(final IntegerListPreference mPassphraseCacheTtl) {
mPassphraseCacheTtl.setValue("" + mPreferences.getPassPhraseCacheTtl());
mPassphraseCacheTtl.setValue("" + sPreferences.getPassPhraseCacheTtl());
mPassphraseCacheTtl.setSummary(mPassphraseCacheTtl.getEntry());
mPassphraseCacheTtl
.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
mPassphraseCacheTtl.setValue(newValue.toString());
mPassphraseCacheTtl.setSummary(mPassphraseCacheTtl.getEntry());
mPreferences.setPassPhraseCacheTtl(Integer.parseInt(newValue.toString()));
sPreferences.setPassPhraseCacheTtl(Integer.parseInt(newValue.toString()));
return false;
}
});
@ -282,14 +282,14 @@ public class PreferencesActivity extends PreferenceActivity {
}
mEncryptionAlgorithm.setEntries(entries);
mEncryptionAlgorithm.setEntryValues(values);
mEncryptionAlgorithm.setValue("" + mPreferences.getDefaultEncryptionAlgorithm());
mEncryptionAlgorithm.setValue("" + sPreferences.getDefaultEncryptionAlgorithm());
mEncryptionAlgorithm.setSummary(mEncryptionAlgorithm.getEntry());
mEncryptionAlgorithm
.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
mEncryptionAlgorithm.setValue(newValue.toString());
mEncryptionAlgorithm.setSummary(mEncryptionAlgorithm.getEntry());
mPreferences.setDefaultEncryptionAlgorithm(Integer.parseInt(newValue
sPreferences.setDefaultEncryptionAlgorithm(Integer.parseInt(newValue
.toString()));
return false;
}
@ -309,13 +309,13 @@ public class PreferencesActivity extends PreferenceActivity {
}
mHashAlgorithm.setEntries(entries);
mHashAlgorithm.setEntryValues(values);
mHashAlgorithm.setValue("" + mPreferences.getDefaultHashAlgorithm());
mHashAlgorithm.setValue("" + sPreferences.getDefaultHashAlgorithm());
mHashAlgorithm.setSummary(mHashAlgorithm.getEntry());
mHashAlgorithm.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
mHashAlgorithm.setValue(newValue.toString());
mHashAlgorithm.setSummary(mHashAlgorithm.getEntry());
mPreferences.setDefaultHashAlgorithm(Integer.parseInt(newValue.toString()));
sPreferences.setDefaultHashAlgorithm(Integer.parseInt(newValue.toString()));
return false;
}
});
@ -326,14 +326,14 @@ public class PreferencesActivity extends PreferenceActivity {
int[] valueIds, String[] entries, String[] values) {
mMessageCompression.setEntries(entries);
mMessageCompression.setEntryValues(values);
mMessageCompression.setValue("" + mPreferences.getDefaultMessageCompression());
mMessageCompression.setValue("" + sPreferences.getDefaultMessageCompression());
mMessageCompression.setSummary(mMessageCompression.getEntry());
mMessageCompression
.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
mMessageCompression.setValue(newValue.toString());
mMessageCompression.setSummary(mMessageCompression.getEntry());
mPreferences.setDefaultMessageCompression(Integer.parseInt(newValue
sPreferences.setDefaultMessageCompression(Integer.parseInt(newValue
.toString()));
return false;
}
@ -344,36 +344,36 @@ public class PreferencesActivity extends PreferenceActivity {
(final IntegerListPreference mFileCompression, String[] entries, String[] values) {
mFileCompression.setEntries(entries);
mFileCompression.setEntryValues(values);
mFileCompression.setValue("" + mPreferences.getDefaultFileCompression());
mFileCompression.setValue("" + sPreferences.getDefaultFileCompression());
mFileCompression.setSummary(mFileCompression.getEntry());
mFileCompression.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
mFileCompression.setValue(newValue.toString());
mFileCompression.setSummary(mFileCompression.getEntry());
mPreferences.setDefaultFileCompression(Integer.parseInt(newValue.toString()));
sPreferences.setDefaultFileCompression(Integer.parseInt(newValue.toString()));
return false;
}
});
}
private static void initializeAsciiArmour(final CheckBoxPreference mAsciiArmour) {
mAsciiArmour.setChecked(mPreferences.getDefaultAsciiArmour());
mAsciiArmour.setChecked(sPreferences.getDefaultAsciiArmour());
mAsciiArmour.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
mAsciiArmour.setChecked((Boolean) newValue);
mPreferences.setDefaultAsciiArmour((Boolean) newValue);
sPreferences.setDefaultAsciiArmour((Boolean) newValue);
return false;
}
});
}
private static void initializeForceV3Signatures(final CheckBoxPreference mForceV3Signatures) {
mForceV3Signatures.setChecked(mPreferences.getForceV3Signatures());
mForceV3Signatures.setChecked(sPreferences.getForceV3Signatures());
mForceV3Signatures
.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
mForceV3Signatures.setChecked((Boolean) newValue);
mPreferences.setForceV3Signatures((Boolean) newValue);
sPreferences.setForceV3Signatures((Boolean) newValue);
return false;
}
});

View File

@ -141,7 +141,8 @@ public class SelectSecretKeyFragment extends ListFragment implements
+ Keys.IS_REVOKED + " = '0' AND valid_keys." + Keys.CAN_SIGN
+ " = '1' AND valid_keys." + Keys.CREATION + " <= '" + now + "' AND "
+ "(valid_keys." + Keys.EXPIRY + " IS NULL OR valid_keys." + Keys.EXPIRY
+ " >= '" + now + "')) AS " + SelectKeyCursorAdapter.PROJECTION_ROW_VALID,};
+ " >= '" + now + "')) AS " + SelectKeyCursorAdapter.PROJECTION_ROW_VALID,
};
String orderBy = UserIds.USER_ID + " ASC";

View File

@ -53,12 +53,12 @@ public class SelectSecretKeyLayoutFragment extends Fragment implements LoaderMan
private SelectSecretKeyCallback mCallback;
final String[] PROJECTION = new String[]{
KeychainContract.UserIds.USER_ID,
KeychainContract.KeyRings.MASTER_KEY_ID
private static final String[] PROJECTION = new String[] {
KeychainContract.UserIds.USER_ID,
KeychainContract.KeyRings.MASTER_KEY_ID,
};
final int INDEX_USER_ID = 0;
final int INDEX_MASTER_KEY_ID = 1;
private static final int INDEX_USER_ID = 0;
private static final int INDEX_MASTER_KEY_ID = 1;
public interface SelectSecretKeyCallback {
void onKeySelected(long secretKeyId);

View File

@ -38,7 +38,6 @@ import org.sufficientlysecure.keychain.pgp.PgpKeyHelper;
import org.sufficientlysecure.keychain.provider.KeychainContract;
import org.sufficientlysecure.keychain.provider.ProviderHelper;
import org.sufficientlysecure.keychain.ui.adapter.TabsAdapter;
import org.sufficientlysecure.keychain.ui.dialog.DeleteKeyDialogFragment;
import org.sufficientlysecure.keychain.ui.dialog.ShareNfcDialogFragment;
import org.sufficientlysecure.keychain.ui.dialog.ShareQrCodeDialogFragment;
import org.sufficientlysecure.keychain.util.Log;
@ -125,8 +124,9 @@ public class ViewKeyActivity extends ActionBarActivity {
return true;
case R.id.menu_key_view_export_file:
long masterKeyId =
ProviderHelper.getPublicMasterKeyId(this, Long.valueOf(mDataUri.getLastPathSegment()));
long[] ids = new long[]{masterKeyId};
ProviderHelper.getPublicMasterKeyId(this,
Long.valueOf(mDataUri.getLastPathSegment()));
long[] ids = new long[] {masterKeyId};
mExportHelper.showExportKeysDialog(ids, Id.type.public_key,
Constants.Path.APP_DIR_FILE_PUB, null);
return true;

View File

@ -37,7 +37,6 @@ import com.beardedhen.androidbootstrap.BootstrapButton;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.helper.OtherHelper;
import org.sufficientlysecure.keychain.pgp.PgpKeyHelper;
import org.sufficientlysecure.keychain.provider.KeychainContract;
import org.sufficientlysecure.keychain.provider.ProviderHelper;

View File

@ -32,7 +32,6 @@ import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.helper.OtherHelper;
import org.sufficientlysecure.keychain.pgp.PgpKeyHelper;
import java.util.ArrayList;
@ -45,12 +44,12 @@ public class ImportKeysAdapter extends ArrayAdapter<ImportKeysListEntry> {
protected List<ImportKeysListEntry> mData;
static class ViewHolder {
private TextView mainUserId;
private TextView mainUserIdRest;
private TextView keyId;
private TextView fingerprint;
private TextView algorithm;
private TextView status;
public TextView mainUserId;
public TextView mainUserIdRest;
public TextView keyId;
public TextView fingerprint;
public TextView algorithm;
public TextView status;
}
public ImportKeysAdapter(Activity activity) {

View File

@ -249,7 +249,7 @@ public class ImportKeysListEntry implements Serializable, Parcelable {
/**
* Based on <a href="http://tools.ietf.org/html/rfc2440#section-9.1">OpenPGP Message Format</a>
*/
private final static SparseArray<String> ALGORITHM_IDS = new SparseArray<String>() {{
private static final SparseArray<String> ALGORITHM_IDS = new SparseArray<String>() {{
put(-1, "unknown"); // TODO: with resources
put(0, "unencrypted");
put(PGPPublicKey.RSA_GENERAL, "RSA");
@ -267,6 +267,8 @@ public class ImportKeysListEntry implements Serializable, Parcelable {
* Based on <a href="http://tools.ietf.org/html/rfc2440#section-9.1">OpenPGP Message Format</a>
*/
public static String getAlgorithmFromId(int algorithmId) {
return (ALGORITHM_IDS.get(algorithmId) != null ? ALGORITHM_IDS.get(algorithmId) : ALGORITHM_IDS.get(-1));
return (ALGORITHM_IDS.get(algorithmId) != null ?
ALGORITHM_IDS.get(algorithmId) :
ALGORITHM_IDS.get(-1));
}
}

View File

@ -21,10 +21,6 @@ import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import java.util.ArrayList;
@ -34,9 +30,9 @@ public class PagerTabStripAdapter extends FragmentPagerAdapter {
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
private final String title;
public final Class<?> clss;
public final Bundle args;
public final String title;
TabInfo(Class<?> clss, Bundle args, String title) {
this.clss = clss;

View File

@ -36,8 +36,8 @@ public class TabsAdapter extends FragmentStatePagerAdapter implements ActionBar.
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
public final Class<?> clss;
public final Bundle args;
TabInfo(Class<?> clss, Bundle args) {
this.clss = clss;

View File

@ -20,7 +20,6 @@ package org.sufficientlysecure.keychain.ui.adapter;
import android.content.Context;
import android.content.res.ColorStateList;
import android.database.Cursor;
import android.graphics.Color;
import android.support.v4.widget.CursorAdapter;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
@ -149,8 +148,7 @@ public class ViewKeyKeysAdapter extends CursorAdapter {
DateFormat.getDateFormat(context).format(expiryDate) + ")");
keyExpiry.setVisibility(View.VISIBLE);
}
else {
} else {
keyExpiry.setVisibility(View.GONE);
}
// if key is expired or revoked, strike through text

View File

@ -37,7 +37,7 @@ public class ViewKeyUserIdsAdapter extends CursorAdapter {
private int mIndexUserId, mIndexRank;
final private ArrayList<Boolean> mCheckStates;
private final ArrayList<Boolean> mCheckStates;
public ViewKeyUserIdsAdapter(Context context, Cursor c, int flags, boolean showCheckBoxes) {
super(context, c, flags);
@ -55,14 +55,15 @@ public class ViewKeyUserIdsAdapter extends CursorAdapter {
@Override
public Cursor swapCursor(Cursor newCursor) {
initIndex(newCursor);
if(mCheckStates != null) {
if (mCheckStates != null) {
mCheckStates.clear();
if(newCursor != null) {
if (newCursor != null) {
int count = newCursor.getCount();
mCheckStates.ensureCapacity(count);
// initialize to true (use case knowledge: we usually want to sign all uids)
for(int i = 0; i < count; i++)
for (int i = 0; i < count; i++) {
mCheckStates.add(true);
}
}
}
@ -100,8 +101,9 @@ public class ViewKeyUserIdsAdapter extends CursorAdapter {
vAddress.setText(userId[1]);
// don't care further if checkboxes aren't shown
if(mCheckStates == null)
if (mCheckStates == null) {
return;
}
final CheckBox vCheckBox = (CheckBox) view.findViewById(R.id.checkBox);
final int position = cursor.getPosition();
@ -124,8 +126,8 @@ public class ViewKeyUserIdsAdapter extends CursorAdapter {
public ArrayList<String> getSelectedUserIds() {
ArrayList<String> result = new ArrayList<String>();
for(int i = 0; i < mCheckStates.size(); i++) {
if(mCheckStates.get(i)) {
for (int i = 0; i < mCheckStates.size(); i++) {
if (mCheckStates.get(i)) {
mCursor.moveToPosition(i);
result.add(mCursor.getString(mIndexUserId));
}

View File

@ -138,9 +138,10 @@ public class CreateKeyDialogFragment extends DialogFragment {
final AdapterView.OnItemSelectedListener weakRsaListener = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
final Choice selectedAlgorithm = (Choice)algorithm.getSelectedItem();
final int selectedKeySize = Integer.parseInt((String)keySize.getSelectedItem());
final boolean isWeakRsa = (selectedAlgorithm.getId() == Id.choice.algorithm.rsa && selectedKeySize <= 1024);
final Choice selectedAlgorithm = (Choice) algorithm.getSelectedItem();
final int selectedKeySize = Integer.parseInt((String) keySize.getSelectedItem());
final boolean isWeakRsa = (selectedAlgorithm.getId() == Id.choice.algorithm.rsa &&
selectedKeySize <= 1024);
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(!isWeakRsa);
}

View File

@ -51,12 +51,12 @@ public class DeleteKeyDialogFragment extends DialogFragment {
public static final int MESSAGE_OKAY = 1;
public static final int MESSAGE_ERROR = 0;
private boolean isSingleSelection = false;
private boolean mIsSingleSelection = false;
private TextView mainMessage;
private CheckBox checkDeleteSecret;
private LinearLayout deleteSecretKeyView;
private View inflateView;
private TextView mMainMessage;
private CheckBox mCheckDeleteSecret;
private LinearLayout mDeleteSecretKeyView;
private View mInflateView;
private Messenger mMessenger;
@ -90,12 +90,12 @@ public class DeleteKeyDialogFragment extends DialogFragment {
//Setup custom View to display in AlertDialog
LayoutInflater inflater = activity.getLayoutInflater();
inflateView = inflater.inflate(R.layout.view_key_delete_fragment, null);
builder.setView(inflateView);
mInflateView = inflater.inflate(R.layout.view_key_delete_fragment, null);
builder.setView(mInflateView);
deleteSecretKeyView = (LinearLayout) inflateView.findViewById(R.id.deleteSecretKeyView);
mainMessage = (TextView) inflateView.findViewById(R.id.mainMessage);
checkDeleteSecret = (CheckBox) inflateView.findViewById(R.id.checkDeleteSecret);
mDeleteSecretKeyView = (LinearLayout) mInflateView.findViewById(R.id.deleteSecretKeyView);
mMainMessage = (TextView) mInflateView.findViewById(R.id.mainMessage);
mCheckDeleteSecret = (CheckBox) mInflateView.findViewById(R.id.checkDeleteSecret);
builder.setTitle(R.string.warning);
@ -103,7 +103,7 @@ public class DeleteKeyDialogFragment extends DialogFragment {
if (keyRingRowIds.length == 1) {
Uri dataUri;
ArrayList<Long> publicKeyRings; //Any one will do
isSingleSelection = true;
mIsSingleSelection = true;
long selectedRow = keyRingRowIds[0];
long keyType;
@ -119,16 +119,16 @@ public class DeleteKeyDialogFragment extends DialogFragment {
}
String userId = ProviderHelper.getUserId(activity, dataUri);
//Hide the Checkbox and TextView since this is a single selection,user will be notified thru message
deleteSecretKeyView.setVisibility(View.GONE);
//Set message depending on which key it is.
mainMessage.setText(getString(keyType == Id.type.secret_key ? R.string.secret_key_deletion_confirmation
: R.string.public_key_deletetion_confirmation, userId));
// Hide the Checkbox and TextView since this is a single selection,
// user will be notified thru message
mDeleteSecretKeyView.setVisibility(View.GONE);
// Set message depending on which key it is.
mMainMessage.setText(getString(keyType == Id.type.secret_key ?
R.string.secret_key_deletion_confirmation :
R.string.public_key_deletetion_confirmation, userId));
} else {
deleteSecretKeyView.setVisibility(View.VISIBLE);
mainMessage.setText(R.string.key_deletion_confirmation_multi);
mDeleteSecretKeyView.setVisibility(View.VISIBLE);
mMainMessage.setText(R.string.key_deletion_confirmation_multi);
}
@ -148,8 +148,9 @@ public class DeleteKeyDialogFragment extends DialogFragment {
String selectionIDs = "";
for (int i = 0; i < keyRingRowIds.length; i++) {
selectionIDs += "'" + String.valueOf(keyRingRowIds[i]) + "'";
if (i + 1 < keyRingRowIds.length)
if (i + 1 < keyRingRowIds.length) {
selectionIDs += ",";
}
}
selection += selectionIDs + ")";
@ -166,30 +167,33 @@ public class DeleteKeyDialogFragment extends DialogFragment {
masterKeyId = cursor.getLong(0);
keyType = cursor.getLong(1);
Log.d(Constants.TAG, "masterKeyId: " + masterKeyId
+ ", keyType:" + (keyType == KeychainContract.KeyTypes.PUBLIC ? "Public" : "Private"));
Log.d(Constants.TAG, "masterKeyId: " + masterKeyId +
", keyType:" +
(keyType == KeychainContract.KeyTypes.PUBLIC ?
"Public" : "Private"));
if (keyType == KeychainContract.KeyTypes.SECRET) {
if (checkDeleteSecret.isChecked() || isSingleSelection) {
ProviderHelper.deleteUnifiedKeyRing(activity, String.valueOf(masterKeyId), true);
if (mCheckDeleteSecret.isChecked() || mIsSingleSelection) {
ProviderHelper.deleteUnifiedKeyRing(activity,
String.valueOf(masterKeyId), true);
}
} else {
ProviderHelper.deleteUnifiedKeyRing(activity, String.valueOf(masterKeyId), false);
ProviderHelper.deleteUnifiedKeyRing(activity,
String.valueOf(masterKeyId), false);
}
}
//Check if the selected rows have actually been deleted
cursor = activity.getContentResolver().query(queryUri, projection, selection, null, null);
if (cursor == null || cursor.getCount() == 0 || !checkDeleteSecret.isChecked()) {
cursor = activity.getContentResolver().query(
queryUri, projection, selection, null, null);
if (cursor == null || cursor.getCount() == 0 ||
!mCheckDeleteSecret.isChecked()) {
isSuccessfullyDeleted = true;
}
} finally {
if (cursor != null) {
cursor.close();
}
}
dismiss();
@ -200,9 +204,7 @@ public class DeleteKeyDialogFragment extends DialogFragment {
sendMessageToHandler(MESSAGE_ERROR, null);
}
}
}
);
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
@ -232,5 +234,4 @@ public class DeleteKeyDialogFragment extends DialogFragment {
Log.w(Constants.TAG, "Messenger is null!", e);
}
}
}
}

View File

@ -111,7 +111,7 @@ public class ShareQrCodeDialogFragment extends DialogFragment {
content = keyringArmored.get(0);
// OnClickListener are set in onResume to prevent automatic dismissing of Dialogs
// http://stackoverflow.com/questions/2620444/how-to-prevent-a-dialog-from-closing-when-a-button-is-clicked
// http://bit.ly/O5vfaR
alert.setPositiveButton(R.string.btn_next, null);
alert.setNegativeButton(android.R.string.cancel, null);

View File

@ -82,7 +82,7 @@ public class FoldableLinearLayout extends LinearLayout {
* @param attrs
*/
private void processAttributes(Context context, AttributeSet attrs) {
if(attrs != null) {
if (attrs != null) {
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.FoldableLinearLayout, 0, 0);
mFoldedIconName = a.getString(R.styleable.FoldableLinearLayout_foldedIcon);
@ -102,7 +102,7 @@ public class FoldableLinearLayout extends LinearLayout {
protected void onFinishInflate() {
// if the migration has already happened
// there is no need to move any children
if(!mHasMigrated) {
if (!mHasMigrated) {
migrateChildrenToContainer();
mHasMigrated = true;
}
@ -120,10 +120,10 @@ public class FoldableLinearLayout extends LinearLayout {
int childNum = getChildCount();
View[] children = new View[childNum];
for(int i = 0; i < childNum; i++) {
for (int i = 0; i < childNum; i++) {
children[i] = getChildAt(i);
}
if(children[0].getId() == R.id.foldableControl) {
if (children[0].getId() == R.id.foldableControl) {
}
@ -131,14 +131,14 @@ public class FoldableLinearLayout extends LinearLayout {
detachAllViewsFromParent();
// Inflate the inner foldable_linearlayout.xml
LayoutInflater inflator = (LayoutInflater)getContext().getSystemService(
LayoutInflater inflator = (LayoutInflater) getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
mFoldableLayout = inflator.inflate(R.layout.foldable_linearlayout, this, true);
mFoldableContainer = (LinearLayout) mFoldableLayout.findViewById(R.id.foldableContainer);
// Push previously collected children into foldableContainer.
for(int i = 0; i < childNum; i++) {
for (int i = 0; i < childNum; i++) {
addView(children[i]);
}
}
@ -196,7 +196,7 @@ public class FoldableLinearLayout extends LinearLayout {
*/
@Override
public void addView(View child) {
if(mFoldableContainer != null) {
if (mFoldableContainer != null) {
mFoldableContainer.addView(child);
}
}

View File

@ -16,20 +16,6 @@
package org.sufficientlysecure.keychain.ui.widget;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.Vector;
import org.spongycastle.bcpg.sig.KeyFlags;
import org.spongycastle.openpgp.PGPKeyFlags;
import org.spongycastle.openpgp.PGPPublicKey;
import org.spongycastle.openpgp.PGPSecretKey;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.pgp.PgpKeyHelper;
import org.sufficientlysecure.keychain.util.Choice;
import android.annotation.TargetApi;
import android.app.DatePickerDialog;
import android.app.Dialog;
@ -47,16 +33,23 @@ import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.beardedhen.androidbootstrap.BootstrapButton;
import org.spongycastle.bcpg.sig.KeyFlags;
import org.spongycastle.openpgp.PGPPublicKey;
import org.spongycastle.openpgp.PGPSecretKey;
import org.sufficientlysecure.keychain.Id;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.pgp.PgpKeyHelper;
import org.sufficientlysecure.keychain.util.Choice;
import java.text.DateFormat;
import java.util.*;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.Vector;
public class KeyEditor extends LinearLayout implements Editor, OnClickListener {
private PGPSecretKey mKey;
@ -101,11 +94,13 @@ public class KeyEditor extends LinearLayout implements Editor, OnClickListener {
GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
date.set(year, monthOfYear, dayOfMonth);
if (mOriginalExpiryDate != null) {
long numDays = (date.getTimeInMillis() / 86400000) - (mOriginalExpiryDate.getTimeInMillis() / 86400000);
if (numDays == 0)
long numDays = (date.getTimeInMillis() / 86400000) -
(mOriginalExpiryDate.getTimeInMillis() / 86400000);
if (numDays == 0) {
setExpiryDate(mOriginalExpiryDate);
else
} else {
setExpiryDate(date);
}
} else {
setExpiryDate(date);
}
@ -155,7 +150,7 @@ public class KeyEditor extends LinearLayout implements Editor, OnClickListener {
date = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
}
/*
* Using custom DatePickerDialog which overrides the setTitle because
* Using custom DatePickerDialog which overrides the setTitle because
* the DatePickerDialog title is buggy (unix warparound bug).
* See: https://code.google.com/p/android/issues/detail?id=49066
*/
@ -228,23 +223,23 @@ public class KeyEditor extends LinearLayout implements Editor, OnClickListener {
boolean isDSAKey = (key.getPublicKey().getAlgorithm() == PGPPublicKey.DSA);
if (isElGamalKey) {
mChkSign.setVisibility(View.INVISIBLE);
TableLayout table = (TableLayout)findViewById(R.id.table_keylayout);
TableRow row = (TableRow)findViewById(R.id.row_sign);
TableLayout table = (TableLayout) findViewById(R.id.table_keylayout);
TableRow row = (TableRow) findViewById(R.id.row_sign);
table.removeView(row);
}
if (isDSAKey) {
mChkEncrypt.setVisibility(View.INVISIBLE);
TableLayout table = (TableLayout)findViewById(R.id.table_keylayout);
TableRow row = (TableRow)findViewById(R.id.row_encrypt);
TableLayout table = (TableLayout) findViewById(R.id.table_keylayout);
TableRow row = (TableRow) findViewById(R.id.row_encrypt);
table.removeView(row);
}
if (!mIsMasterKey) {
mChkCertify.setVisibility(View.INVISIBLE);
TableLayout table = (TableLayout)findViewById(R.id.table_keylayout);
TableRow row = (TableRow)findViewById(R.id.row_certify);
TableLayout table = (TableLayout) findViewById(R.id.table_keylayout);
TableRow row = (TableRow) findViewById(R.id.row_certify);
table.removeView(row);
} else {
TextView mLabelUsage2= (TextView) findViewById(R.id.label_usage2);
TextView mLabelUsage2 = (TextView) findViewById(R.id.label_usage2);
mLabelUsage2.setVisibility(View.INVISIBLE);
}
@ -260,8 +255,9 @@ public class KeyEditor extends LinearLayout implements Editor, OnClickListener {
} else {
mUsage = PgpKeyHelper.getKeyUsage(key);
mOriginalUsage = mUsage;
if (key.isMasterKey())
if (key.isMasterKey()) {
mChkCertify.setChecked(PgpKeyHelper.isCertificationKey(key));
}
mChkSign.setChecked(PgpKeyHelper.isSigningKey(key));
mChkEncrypt.setChecked(PgpKeyHelper.isEncryptionKey(key));
mChkAuthenticate.setChecked(PgpKeyHelper.isAuthenticationKey(key));
@ -323,19 +319,24 @@ public class KeyEditor extends LinearLayout implements Editor, OnClickListener {
}
public int getUsage() {
mUsage = (mUsage & ~KeyFlags.CERTIFY_OTHER) | (mChkCertify.isChecked() ? KeyFlags.CERTIFY_OTHER : 0);
mUsage = (mUsage & ~KeyFlags.SIGN_DATA) | (mChkSign.isChecked() ? KeyFlags.SIGN_DATA : 0);
mUsage = (mUsage & ~KeyFlags.ENCRYPT_COMMS) | (mChkEncrypt.isChecked() ? KeyFlags.ENCRYPT_COMMS : 0);
mUsage = (mUsage & ~KeyFlags.ENCRYPT_STORAGE) | (mChkEncrypt.isChecked() ? KeyFlags.ENCRYPT_STORAGE : 0);
mUsage = (mUsage & ~KeyFlags.AUTHENTICATION) | (mChkAuthenticate.isChecked() ? KeyFlags.AUTHENTICATION : 0);
mUsage = (mUsage & ~KeyFlags.CERTIFY_OTHER) |
(mChkCertify.isChecked() ? KeyFlags.CERTIFY_OTHER : 0);
mUsage = (mUsage & ~KeyFlags.SIGN_DATA) |
(mChkSign.isChecked() ? KeyFlags.SIGN_DATA : 0);
mUsage = (mUsage & ~KeyFlags.ENCRYPT_COMMS) |
(mChkEncrypt.isChecked() ? KeyFlags.ENCRYPT_COMMS : 0);
mUsage = (mUsage & ~KeyFlags.ENCRYPT_STORAGE) |
(mChkEncrypt.isChecked() ? KeyFlags.ENCRYPT_STORAGE : 0);
mUsage = (mUsage & ~KeyFlags.AUTHENTICATION) |
(mChkAuthenticate.isChecked() ? KeyFlags.AUTHENTICATION : 0);
return mUsage;
}
public boolean needsSaving()
{
if (mIsNewKey)
public boolean needsSaving() {
if (mIsNewKey) {
return true;
}
boolean retval = (getUsage() != mOriginalUsage);
@ -345,21 +346,21 @@ public class KeyEditor extends LinearLayout implements Editor, OnClickListener {
if (mOEDNull != mEDNull) {
dateChanged = true;
} else {
if(mOEDNull) //both null, no change
if (mOEDNull) {
//both null, no change
dateChanged = false;
else
} else {
dateChanged = ((mExpiryDate.compareTo(mOriginalExpiryDate)) != 0);
}
}
retval |= dateChanged;
return retval;
}
public boolean getIsNewKey()
{
public boolean getIsNewKey() {
return mIsNewKey;
}
}
class ExpiryDatePickerDialog extends DatePickerDialog {

View File

@ -16,23 +16,6 @@
package org.sufficientlysecure.keychain.ui.widget;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import org.spongycastle.openpgp.PGPKeyFlags;
import org.spongycastle.openpgp.PGPSecretKey;
import org.sufficientlysecure.keychain.Id;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.pgp.PgpConversionHelper;
import org.sufficientlysecure.keychain.service.KeychainIntentService;
import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler;
import org.sufficientlysecure.keychain.service.PassphraseCacheService;
import org.sufficientlysecure.keychain.ui.dialog.ProgressDialogFragment;
import org.sufficientlysecure.keychain.ui.widget.Editor.EditorListener;
import org.sufficientlysecure.keychain.util.Choice;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
@ -49,7 +32,10 @@ import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.beardedhen.androidbootstrap.BootstrapButton;
import org.spongycastle.openpgp.PGPKeyFlags;
import org.spongycastle.openpgp.PGPSecretKey;
import org.sufficientlysecure.keychain.Id;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.pgp.PgpConversionHelper;
@ -61,7 +47,9 @@ import org.sufficientlysecure.keychain.ui.dialog.ProgressDialogFragment;
import org.sufficientlysecure.keychain.ui.widget.Editor.EditorListener;
import org.sufficientlysecure.keychain.util.Choice;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
public class SectionView extends LinearLayout implements OnClickListener, EditorListener, Editor {
private LayoutInflater mInflater;
@ -73,7 +61,7 @@ public class SectionView extends LinearLayout implements OnClickListener, Editor
private Choice mNewKeyAlgorithmChoice;
private int mNewKeySize;
private boolean oldItemDeleted = false;
private boolean mOldItemDeleted = false;
private ArrayList<String> mDeletedIDs = new ArrayList<String>();
private ArrayList<PGPSecretKey> mDeletedKeys = new ArrayList<PGPSecretKey>();
private boolean mCanEdit = true;
@ -150,13 +138,13 @@ public class SectionView extends LinearLayout implements OnClickListener, Editor
* {@inheritDoc}
*/
public void onDeleted(Editor editor, boolean wasNewItem) {
oldItemDeleted |= !wasNewItem;
if (oldItemDeleted) {
if (mType == Id.type.user_id)
mDeletedIDs.add(((UserIdEditor)editor).getOriginalID());
else if (mType == Id.type.key)
mDeletedKeys.add(((KeyEditor)editor).getValue());
mOldItemDeleted |= !wasNewItem;
if (mOldItemDeleted) {
if (mType == Id.type.user_id) {
mDeletedIDs.add(((UserIdEditor) editor).getOriginalID());
} else if (mType == Id.type.key) {
mDeletedKeys.add(((KeyEditor) editor).getValue());
}
}
this.updateEditorsVisible();
if (mEditorListener != null) {
@ -176,55 +164,55 @@ public class SectionView extends LinearLayout implements OnClickListener, Editor
mEditors.setVisibility(hasChildren ? View.VISIBLE : View.GONE);
}
public boolean needsSaving()
{
public boolean needsSaving() {
//check each view for needs saving, take account of deleted items
boolean ret = oldItemDeleted;
boolean ret = mOldItemDeleted;
for (int i = 0; i < mEditors.getChildCount(); ++i) {
Editor editor = (Editor) mEditors.getChildAt(i);
ret |= editor.needsSaving();
if (mType == Id.type.user_id)
ret |= ((UserIdEditor)editor).primarySwapped();
if (mType == Id.type.user_id) {
ret |= ((UserIdEditor) editor).primarySwapped();
}
}
return ret;
}
public boolean primaryChanged()
{
public boolean primaryChanged() {
boolean ret = false;
for (int i = 0; i < mEditors.getChildCount(); ++i) {
Editor editor = (Editor) mEditors.getChildAt(i);
if (mType == Id.type.user_id)
ret |= ((UserIdEditor)editor).primarySwapped();
if (mType == Id.type.user_id) {
ret |= ((UserIdEditor) editor).primarySwapped();
}
}
return ret;
}
public String getOriginalPrimaryID()
{ //NB: this will have to change when we change how Primary IDs are chosen, and so we need to be
// careful about where Master key capabilities are stored... multiple primaries and
// revoked ones make this harder than the simple case we are continuing to assume here
public String getOriginalPrimaryID() {
//NB: this will have to change when we change how Primary IDs are chosen, and so we need to be
// careful about where Master key capabilities are stored... multiple primaries and
// revoked ones make this harder than the simple case we are continuing to assume here
for (int i = 0; i < mEditors.getChildCount(); ++i) {
Editor editor = (Editor) mEditors.getChildAt(i);
if (mType == Id.type.user_id) {
if(((UserIdEditor)editor).getIsOriginallyMainUserID()) {
return ((UserIdEditor)editor).getOriginalID();
if (((UserIdEditor) editor).getIsOriginallyMainUserID()) {
return ((UserIdEditor) editor).getOriginalID();
}
}
}
return null;
}
public ArrayList<String> getOriginalIDs()
{
public ArrayList<String> getOriginalIDs() {
ArrayList<String> orig = new ArrayList<String>();
if (mType == Id.type.user_id) {
for (int i = 0; i < mEditors.getChildCount(); ++i) {
UserIdEditor editor = (UserIdEditor) mEditors.getChildAt(i);
if (editor.isMainUserId())
if (editor.isMainUserId()) {
orig.add(0, editor.getOriginalID());
else
} else {
orig.add(editor.getOriginalID());
}
}
return orig;
} else {
@ -232,18 +220,15 @@ public class SectionView extends LinearLayout implements OnClickListener, Editor
}
}
public ArrayList<String> getDeletedIDs()
{
public ArrayList<String> getDeletedIDs() {
return mDeletedIDs;
}
public ArrayList<PGPSecretKey> getDeletedKeys()
{
public ArrayList<PGPSecretKey> getDeletedKeys() {
return mDeletedKeys;
}
public List<Boolean> getNeedsSavingArray()
{
public List<Boolean> getNeedsSavingArray() {
ArrayList<Boolean> mList = new ArrayList<Boolean>();
for (int i = 0; i < mEditors.getChildCount(); ++i) {
Editor editor = (Editor) mEditors.getChildAt(i);
@ -252,21 +237,20 @@ public class SectionView extends LinearLayout implements OnClickListener, Editor
return mList;
}
public List<Boolean> getNewIDFlags()
{
public List<Boolean> getNewIDFlags() {
ArrayList<Boolean> mList = new ArrayList<Boolean>();
for (int i = 0; i < mEditors.getChildCount(); ++i) {
UserIdEditor editor = (UserIdEditor) mEditors.getChildAt(i);
if (editor.isMainUserId())
if (editor.isMainUserId()) {
mList.add(0, editor.getIsNewID());
else
} else {
mList.add(editor.getIsNewID());
}
}
return mList;
}
public List<Boolean> getNewKeysArray()
{
public List<Boolean> getNewKeysArray() {
ArrayList<Boolean> mList = new ArrayList<Boolean>();
if (mType == Id.type.key) {
for (int i = 0; i < mEditors.getChildCount(); ++i) {
@ -432,8 +416,9 @@ public class SectionView extends LinearLayout implements OnClickListener, Editor
mEditors, false);
view.setEditorListener(SectionView.this);
int usage = 0;
if (mEditors.getChildCount() == 0)
if (mEditors.getChildCount() == 0) {
usage = PGPKeyFlags.CAN_CERTIFY;
}
view.setValue(newKey, newKey.isMasterKey(), usage, true);
mEditors.addView(view);
SectionView.this.updateEditorsVisible();

View File

@ -16,11 +16,6 @@
package org.sufficientlysecure.keychain.ui.widget;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.pgp.PgpKeyHelper;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
@ -31,8 +26,12 @@ import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.*;
import com.beardedhen.androidbootstrap.BootstrapButton;
import org.sufficientlysecure.keychain.helper.ContactHelper;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.helper.ContactHelper;
import org.sufficientlysecure.keychain.pgp.PgpKeyHelper;
import java.util.regex.Matcher;
public class UserIdEditor extends LinearLayout implements Editor, OnClickListener {
private EditorListener mEditorListener = null;
@ -85,8 +84,7 @@ public class UserIdEditor extends LinearLayout implements Editor, OnClickListene
}
@Override
public void afterTextChanged(Editable s)
{
public void afterTextChanged(Editable s) {
if (mEditorListener != null) {
mEditorListener.onEdited();
}
@ -240,25 +238,22 @@ public class UserIdEditor extends LinearLayout implements Editor, OnClickListene
@Override
public boolean needsSaving() {
boolean retval = false; //(mOriginallyMainUserID != isMainUserId());
retval |= !(mOriginalName.equals( ("" + mName.getText()).trim() ) );
retval |= !(mOriginalEmail.equals( ("" + mEmail.getText()).trim() ) );
retval |= !(mOriginalComment.equals( ("" + mComment.getText()).trim() ) );
retval |= !(mOriginalName.equals(("" + mName.getText()).trim()));
retval |= !(mOriginalEmail.equals(("" + mEmail.getText()).trim()));
retval |= !(mOriginalComment.equals(("" + mComment.getText()).trim()));
retval |= mIsNewId;
return retval;
}
public boolean getIsOriginallyMainUserID()
{
public boolean getIsOriginallyMainUserID() {
return mOriginallyMainUserID;
}
public boolean primarySwapped()
{
public boolean primarySwapped() {
return (mOriginallyMainUserID != isMainUserId());
}
public String getOriginalID()
{
public String getOriginalID() {
return mOriginalID;
}

View File

@ -31,7 +31,6 @@ import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.pgp.PgpHelper;
import org.sufficientlysecure.keychain.pgp.PgpKeyHelper;
import org.sufficientlysecure.keychain.ui.adapter.ImportKeysListEntry;
import java.io.ByteArrayOutputStream;
@ -43,8 +42,6 @@ import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.sufficientlysecure.keychain.ui.adapter.ImportKeysListEntry.getAlgorithmFromId;
public class HkpKeyServer extends KeyServer {
private static class HttpError extends Exception {
private static final long serialVersionUID = 1718783705229428893L;
@ -72,20 +69,22 @@ public class HkpKeyServer extends KeyServer {
/**
* pub:%keyid%:%algo%:%keylen%:%creationdate%:%expirationdate%:%flags%
* <ul>
* <li>%<b>keyid</b>% = this is either the fingerprint or the key ID of the key. Either the 16-digit or 8-digit
* key IDs are acceptable, but obviously the fingerprint is best.</li>
* <li>%<b>keyid</b>% = this is either the fingerprint or the key ID of the key.
* Either the 16-digit or 8-digit key IDs are acceptable, but obviously the fingerprint is best.
* </li>
* <li>%<b>algo</b>% = the algorithm number, (i.e. 1==RSA, 17==DSA, etc).
* See <a href="http://tools.ietf.org/html/rfc2440#section-9.1">RFC-2440</a></li>
* <li>%<b>keylen</b>% = the key length (i.e. 1024, 2048, 4096, etc.)</li>
* <li>%<b>creationdate</b>% = creation date of the key in standard
* <a href="http://tools.ietf.org/html/rfc2440#section-9.1">RFC-2440</a> form (i.e. number of seconds since
* 1/1/1970 UTC time)</li>
* <a href="http://tools.ietf.org/html/rfc2440#section-9.1">RFC-2440</a> form (i.e. number of
* seconds since 1/1/1970 UTC time)</li>
* <li>%<b>expirationdate</b>% = expiration date of the key in standard
* <a href="http://tools.ietf.org/html/rfc2440#section-9.1">RFC-2440</a> form (i.e. number of seconds since
* 1/1/1970 UTC time)</li>
* <li>%<b>flags</b>% = letter codes to indicate details of the key, if any. Flags may be in any order. The
* meaning of "disabled" is implementation-specific. Note that individual flags may be unimplemented, so
* the absence of a given flag does not necessarily mean the absence of the detail.
* <a href="http://tools.ietf.org/html/rfc2440#section-9.1">RFC-2440</a> form (i.e. number of
* seconds since 1/1/1970 UTC time)</li>
* <li>%<b>flags</b>% = letter codes to indicate details of the key, if any. Flags may be in any
* order. The meaning of "disabled" is implementation-specific. Note that individual flags may
* be unimplemented, so the absence of a given flag does not necessarily mean the absence of the
* detail.
* <ul>
* <li>r == revoked</li>
* <li>d == disabled</li>
@ -94,7 +93,8 @@ public class HkpKeyServer extends KeyServer {
* </li>
* </ul>
*
* @see <a href="http://tools.ietf.org/html/draft-shaw-openpgp-hkp-00#section-5.2">5.2. Machine Readable Indexes</a>
* @see <a href="http://tools.ietf.org/html/draft-shaw-openpgp-hkp-00#section-5.2">
* 5.2. Machine Readable Indexes</a>
* in Internet-Draft OpenPGP HTTP Keyserver Protocol Document
*/
public static final Pattern PUB_KEY_LINE = Pattern
@ -105,17 +105,19 @@ public class HkpKeyServer extends KeyServer {
/**
* uid:%escaped uid string%:%creationdate%:%expirationdate%:%flags%
* <ul>
* <li>%<b>escaped uid string</b>% = the user ID string, with HTTP %-escaping for anything that isn't 7-bit
* safe as well as for the ":" character. Any other characters may be escaped, as desired.</li>
* <li>%<b>escaped uid string</b>% = the user ID string, with HTTP %-escaping for anything that
* isn't 7-bit safe as well as for the ":" character. Any other characters may be escaped, as
* desired.</li>
* <li>%<b>creationdate</b>% = creation date of the key in standard
* <a href="http://tools.ietf.org/html/rfc2440#section-9.1">RFC-2440</a> form (i.e. number of seconds since
* 1/1/1970 UTC time)</li>
* <a href="http://tools.ietf.org/html/rfc2440#section-9.1">RFC-2440</a> form (i.e. number of
* seconds since 1/1/1970 UTC time)</li>
* <li>%<b>expirationdate</b>% = expiration date of the key in standard
* <a href="http://tools.ietf.org/html/rfc2440#section-9.1">RFC-2440</a> form (i.e. number of seconds since
* 1/1/1970 UTC time)</li>
* <li>%<b>flags</b>% = letter codes to indicate details of the key, if any. Flags may be in any order. The
* meaning of "disabled" is implementation-specific. Note that individual flags may be unimplemented, so
* the absence of a given flag does not necessarily mean the absence of the detail.
* <a href="http://tools.ietf.org/html/rfc2440#section-9.1">RFC-2440</a> form (i.e. number of
* seconds since 1/1/1970 UTC time)</li>
* <li>%<b>flags</b>% = letter codes to indicate details of the key, if any. Flags may be in any
* order. The meaning of "disabled" is implementation-specific. Note that individual flags may
* be unimplemented, so the absence of a given flag does not necessarily mean the absence of
* the detail.
* <ul>
* <li>r == revoked</li>
* <li>d == disabled</li>
@ -244,11 +246,10 @@ public class HkpKeyServer extends KeyServer {
entry.setBitStrength(Integer.parseInt(matcher.group(3)));
final int algorithmId = Integer.decode(matcher.group(2));
entry.setAlgorithm(getAlgorithmFromId(algorithmId));
entry.setAlgorithm(ImportKeysListEntry.getAlgorithmFromId(algorithmId));
// group 1 contains the full fingerprint (v4) or the long key id if available
// see https://bitbucket.org/skskeyserver/sks-keyserver/pull-request/12/fixes-for-machine-readable-indexes/diff
// and https://github.com/openpgp-keychain/openpgp-keychain/issues/259#issuecomment-38168176
// see http://bit.ly/1d4bxbk and http://bit.ly/1gD1wwr
String fingerprintOrKeyId = matcher.group(1);
if (fingerprintOrKeyId.length() > 16) {
entry.setFingerPrintHex(fingerprintOrKeyId.toLowerCase(Locale.US));

View File

@ -1,4 +1,6 @@
/*
* Copyright (C) 2010-2014 Thialfihar <thi@thialfihar.org>
*
* 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

View File

@ -16,9 +16,10 @@
package org.sufficientlysecure.keychain.util;
import com.google.zxing.integration.android.IntentIntegrator;
import android.content.Intent;
import android.support.v4.app.Fragment;
import com.google.zxing.integration.android.IntentIntegrator;
/**
* IntentIntegrator for the V4 Android compatibility package.

View File

@ -24,7 +24,7 @@ public class IterableIterator<T> implements Iterable<T> {
public IterableIterator(Iterator<T> iter, boolean failsafe) {
mIter = iter;
if(failsafe && mIter == null) {
if (failsafe && mIter == null) {
// is there a better way?
mIter = new ArrayList<T>().iterator();
}

View File

@ -1,16 +1,20 @@
/*
* 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
* Copyright (C) 2014 Dominik Schürmann <dominik@dominikschuermann.de>
*
* http://www.apache.org/licenses/LICENSE-2.0
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sufficientlysecure.keychain.util;
public interface KeychainServiceListener {

View File

@ -1,4 +1,6 @@
/*
* Copyright (C) 2010-2014 Thialfihar <thi@thialfihar.org>
*
* 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

View File

@ -36,7 +36,7 @@ public class ProgressScaler implements ProgressDialogUpdater {
* Set progressDialogUpdater of ProgressDialog by sending message to handler on UI thread
*/
public void setProgress(String message, int progress, int max) {
mWrapped.setProgress(message, mFrom+ progress*(mTo-mFrom)/max, mMax);
mWrapped.setProgress(message, mFrom + progress * (mTo - mFrom) / max, mMax);
}
public void setProgress(int resourceId, int progress, int max) {

View File

@ -18,14 +18,16 @@
package org.sufficientlysecure.keychain.util;
import android.graphics.Bitmap;
import android.graphics.Color;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import android.graphics.Bitmap;
import android.graphics.Color;
import org.sufficientlysecure.keychain.Constants;
import java.util.Hashtable;

View File

@ -9,9 +9,9 @@ page at http://checkstyle.sourceforge.net/config.html -->
<module name="OpenPgpChecker">
<!--<module name="SuppressionFilter">
<module name="SuppressionFilter">
<property name="file" value="tools/suppressions.xml"/>
</module>-->
</module>
<module name="RegexpSingleline">
<!-- Requires a copyright notice in each file.

12
tools/suppressions.xml Normal file
View File

@ -0,0 +1,12 @@
<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
"-//Puppy Crawl//DTD Suppressions 1.1//EN"
"http://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
<suppressions>
<suppress files="(Constants|Id|R|PgpConversionHelper)\.java" checks=".*NameCheck"/>
<suppress files="Apg.java" checks="LineLength"/>
<suppress files="FileDialog.java" checks="StaticVariableNameCheck"/>
<suppress files="PRNGFixes.java" checks=".*"/>
</suppressions>