From 95e35a4ffa1f4c54078009ec6846450240a0884c Mon Sep 17 00:00:00 2001 From: Dominik Date: Thu, 20 Sep 2012 17:13:45 +0200 Subject: more Provider Helper methods --- .../org/thialfihar/android/apg/ApgApplication.java | 5 - .../android/apg/deprecated/ApgService2.java | 1346 ++++++++++---------- .../apg/deprecated/ApgServiceBlobDatabase.java | 142 +-- .../apg/deprecated/ApgServiceBlobProvider.java | 302 ++--- .../android/apg/deprecated/Database.java | 1160 ++++++++--------- .../thialfihar/android/apg/helper/PGPHelper.java | 22 +- .../org/thialfihar/android/apg/helper/PGPMain.java | 210 ++- .../android/apg/provider/ApgContract.java | 16 +- .../android/apg/provider/ApgDatabase.java | 13 +- .../android/apg/provider/ApgProvider.java | 105 +- .../android/apg/provider/ProviderHelper.java | 230 +++- .../thialfihar/android/apg/service/ApgService.java | 19 +- .../apg/service/PassphraseCacheService.java | 4 +- .../thialfihar/android/apg/ui/DecryptActivity.java | 7 +- .../thialfihar/android/apg/ui/EditKeyActivity.java | 18 +- .../thialfihar/android/apg/ui/EncryptActivity.java | 8 +- .../thialfihar/android/apg/ui/KeyListActivity.java | 2 +- .../android/apg/ui/PublicKeyListActivity.java | 9 +- .../thialfihar/android/apg/ui/SignKeyActivity.java | 3 +- .../apg/ui/dialog/DeleteKeyDialogFragment.java | 8 +- 20 files changed, 1873 insertions(+), 1756 deletions(-) (limited to 'org_apg/src/org') diff --git a/org_apg/src/org/thialfihar/android/apg/ApgApplication.java b/org_apg/src/org/thialfihar/android/apg/ApgApplication.java index b46db2060..f89375079 100644 --- a/org_apg/src/org/thialfihar/android/apg/ApgApplication.java +++ b/org_apg/src/org/thialfihar/android/apg/ApgApplication.java @@ -20,7 +20,6 @@ import java.io.File; import java.security.Security; import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.thialfihar.android.apg.helper.PGPMain; import android.app.Application; import android.os.Environment; @@ -36,10 +35,6 @@ public class ApgApplication extends Application { public void onCreate() { super.onCreate(); - // TODO: Do it better than this! - // this initializes the database to be used in PGPMain - PGPMain.initialize(this); - // Create APG directory on sdcard if not existing if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { File dir = new File(Constants.path.APP_DIR); diff --git a/org_apg/src/org/thialfihar/android/apg/deprecated/ApgService2.java b/org_apg/src/org/thialfihar/android/apg/deprecated/ApgService2.java index 571c61b27..cbb033bed 100644 --- a/org_apg/src/org/thialfihar/android/apg/deprecated/ApgService2.java +++ b/org_apg/src/org/thialfihar/android/apg/deprecated/ApgService2.java @@ -1,673 +1,673 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.thialfihar.android.apg.deprecated; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; - -import org.thialfihar.android.apg.deprecated.IApgService2; -import org.thialfihar.android.apg.Id; -import org.thialfihar.android.apg.R; -import org.thialfihar.android.apg.deprecated.IApgService2.Stub; -import org.thialfihar.android.apg.Id.database; -import org.thialfihar.android.apg.R.string; -import org.thialfihar.android.apg.helper.PGPHelper; -import org.thialfihar.android.apg.helper.PGPMain; -import org.thialfihar.android.apg.helper.Preferences; -import org.thialfihar.android.apg.provider.KeyRings; -import org.thialfihar.android.apg.provider.Keys; -import org.thialfihar.android.apg.provider.UserIds; -import org.thialfihar.android.apg.service.PassphraseCacheService; -import org.thialfihar.android.apg.util.InputData; - -import android.content.ContentResolver; -import android.content.Intent; -import android.database.Cursor; -import android.database.sqlite.SQLiteQueryBuilder; -import android.net.Uri; -import android.os.Bundle; -import android.os.IBinder; -import org.thialfihar.android.apg.util.Log; - -/** - * ATTENTION: - * - * This is the old ApgService used as remote service over aidl interface. It will be reworked! - * - */ -public class ApgService2 extends PassphraseCacheService { - private final static String TAG = "ApgService"; - public static final boolean LOCAL_LOGV = true; - public static final boolean LOCAL_LOGD = true; - - @Override - public IBinder onBind(Intent intent) { - if (LOCAL_LOGD) - Log.d(TAG, "bound"); - return mBinder; - } - - /** error status */ - private static enum error { - ARGUMENTS_MISSING, APG_FAILURE, NO_MATCHING_SECRET_KEY, PRIVATE_KEY_PASSPHRASE_WRONG, PRIVATE_KEY_PASSPHRASE_MISSING; - - public int shiftedOrdinal() { - return ordinal() + 100; - } - } - - private static enum call { - encrypt_with_passphrase, encrypt_with_public_key, decrypt, get_keys - } - - /** all arguments that can be passed by calling application */ - public static enum arg { - MESSAGE, // message to encrypt or to decrypt - SYMMETRIC_PASSPHRASE, // key for symmetric en/decryption - PUBLIC_KEYS, // public keys for encryption - ENCRYPTION_ALGORYTHM, // encryption algorithm - HASH_ALGORYTHM, // hash algorithm - ARMORED_OUTPUT, // whether to armor output - FORCE_V3_SIGNATURE, // whether to force v3 signature - COMPRESSION, // what compression to use for encrypted output - SIGNATURE_KEY, // key for signing - PRIVATE_KEY_PASSPHRASE, // passphrase for encrypted private key - KEY_TYPE, // type of key (private or public) - BLOB, // blob passed - } - - /** all things that might be returned */ - private static enum ret { - ERRORS, // string array list with errors - WARNINGS, // string array list with warnings - ERROR, // numeric error - RESULT, // en-/decrypted - FINGERPRINTS, // fingerprints of keys - USER_IDS, // user ids - } - - /** required arguments for each AIDL function */ - private static final HashMap> FUNCTIONS_REQUIRED_ARGS = new HashMap>(); - static { - HashSet args = new HashSet(); - args.add(arg.SYMMETRIC_PASSPHRASE); - FUNCTIONS_REQUIRED_ARGS.put(call.encrypt_with_passphrase.name(), args); - - args = new HashSet(); - args.add(arg.PUBLIC_KEYS); - FUNCTIONS_REQUIRED_ARGS.put(call.encrypt_with_public_key.name(), args); - - args = new HashSet(); - FUNCTIONS_REQUIRED_ARGS.put(call.decrypt.name(), args); - - args = new HashSet(); - args.add(arg.KEY_TYPE); - FUNCTIONS_REQUIRED_ARGS.put(call.get_keys.name(), args); - } - - /** optional arguments for each AIDL function */ - private static final HashMap> FUNCTIONS_OPTIONAL_ARGS = new HashMap>(); - static { - HashSet args = new HashSet(); - args.add(arg.ENCRYPTION_ALGORYTHM); - args.add(arg.HASH_ALGORYTHM); - args.add(arg.ARMORED_OUTPUT); - args.add(arg.FORCE_V3_SIGNATURE); - args.add(arg.COMPRESSION); - args.add(arg.PRIVATE_KEY_PASSPHRASE); - args.add(arg.SIGNATURE_KEY); - args.add(arg.BLOB); - args.add(arg.MESSAGE); - FUNCTIONS_OPTIONAL_ARGS.put(call.encrypt_with_passphrase.name(), args); - FUNCTIONS_OPTIONAL_ARGS.put(call.encrypt_with_public_key.name(), args); - - args = new HashSet(); - args.add(arg.SYMMETRIC_PASSPHRASE); - args.add(arg.PUBLIC_KEYS); - args.add(arg.PRIVATE_KEY_PASSPHRASE); - args.add(arg.MESSAGE); - args.add(arg.BLOB); - FUNCTIONS_OPTIONAL_ARGS.put(call.decrypt.name(), args); - } - - /** a map from ApgService parameters to function calls to get the default */ - private static final HashMap FUNCTIONS_DEFAULTS = new HashMap(); - static { - FUNCTIONS_DEFAULTS.put(arg.ENCRYPTION_ALGORYTHM, "getDefaultEncryptionAlgorithm"); - FUNCTIONS_DEFAULTS.put(arg.HASH_ALGORYTHM, "getDefaultHashAlgorithm"); - FUNCTIONS_DEFAULTS.put(arg.ARMORED_OUTPUT, "getDefaultAsciiArmour"); - FUNCTIONS_DEFAULTS.put(arg.FORCE_V3_SIGNATURE, "getForceV3Signatures"); - FUNCTIONS_DEFAULTS.put(arg.COMPRESSION, "getDefaultMessageCompression"); - } - - /** a map of the default function names to their method */ - private static final HashMap FUNCTIONS_DEFAULTS_METHODS = new HashMap(); - static { - try { - FUNCTIONS_DEFAULTS_METHODS.put("getDefaultEncryptionAlgorithm", - Preferences.class.getMethod("getDefaultEncryptionAlgorithm")); - FUNCTIONS_DEFAULTS_METHODS.put("getDefaultHashAlgorithm", - Preferences.class.getMethod("getDefaultHashAlgorithm")); - FUNCTIONS_DEFAULTS_METHODS.put("getDefaultAsciiArmour", - Preferences.class.getMethod("getDefaultAsciiArmour")); - FUNCTIONS_DEFAULTS_METHODS.put("getForceV3Signatures", - Preferences.class.getMethod("getForceV3Signatures")); - FUNCTIONS_DEFAULTS_METHODS.put("getDefaultMessageCompression", - Preferences.class.getMethod("getDefaultMessageCompression")); - } catch (Exception e) { - Log.e(TAG, "Function method exception: " + e.getMessage()); - } - } - - private static void writeToOutputStream(InputStream is, OutputStream os) throws IOException { - byte[] buffer = new byte[8]; - int len = 0; - while ((len = is.read(buffer)) != -1) { - os.write(buffer, 0, len); - } - } - - private static Cursor getKeyEntries(HashMap pParams) { - SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); - qb.setTables(KeyRings.TABLE_NAME + " INNER JOIN " + Keys.TABLE_NAME + " ON " + "(" - + KeyRings.TABLE_NAME + "." + KeyRings._ID + " = " + Keys.TABLE_NAME + "." - + Keys.KEY_RING_ID + " AND " + Keys.TABLE_NAME + "." + Keys.IS_MASTER_KEY - + " = '1'" + ") " + " INNER JOIN " + UserIds.TABLE_NAME + " ON " + "(" - + Keys.TABLE_NAME + "." + Keys._ID + " = " + UserIds.TABLE_NAME + "." - + UserIds.KEY_ID + " AND " + UserIds.TABLE_NAME + "." + UserIds.RANK + " = '0') "); - - String orderBy = pParams.containsKey("order_by") ? (String) pParams.get("order_by") - : UserIds.TABLE_NAME + "." + UserIds.USER_ID + " ASC"; - - String typeVal[] = null; - String typeWhere = null; - if (pParams.containsKey("key_type")) { - typeWhere = KeyRings.TABLE_NAME + "." + KeyRings.TYPE + " = ?"; - typeVal = new String[] { "" + pParams.get("key_type") }; - } - return qb.query(PGPMain.getDatabase().db(), (String[]) pParams.get("columns"), typeWhere, - typeVal, null, null, orderBy); - } - - /** - * maps a fingerprint or user id of a key to a master key in database - * - * @param search_key - * fingerprint or user id to search for - * @return master key if found, or 0 - */ - private static long getMasterKey(String pSearchKey, Bundle pReturn) { - if (pSearchKey == null || pSearchKey.length() != 8) { - return 0; - } - ArrayList keyList = new ArrayList(); - keyList.add(pSearchKey); - long[] keys = getMasterKey(keyList, pReturn); - if (keys.length > 0) { - return keys[0]; - } else { - return 0; - } - } - - /** - * maps fingerprints or user ids of keys to master keys in database - * - * @param search_keys - * a list of keys (fingerprints or user ids) to look for in database - * @return an array of master keys - */ - private static long[] getMasterKey(ArrayList pSearchKeys, Bundle pReturn) { - - HashMap qParams = new HashMap(); - qParams.put("columns", new String[] { KeyRings.TABLE_NAME + "." + KeyRings.MASTER_KEY_ID, // 0 - UserIds.TABLE_NAME + "." + UserIds.USER_ID, // 1 - }); - qParams.put("key_type", Id.database.type_public); - - Cursor mCursor = getKeyEntries(qParams); - - if (LOCAL_LOGV) - Log.v(TAG, "going through installed user keys"); - ArrayList masterKeys = new ArrayList(); - while (mCursor.moveToNext()) { - long curMkey = mCursor.getLong(0); - String curUser = mCursor.getString(1); - - String curFprint = PGPHelper.getSmallFingerPrint(curMkey); - if (LOCAL_LOGV) - Log.v(TAG, "current user: " + curUser + " (" + curFprint + ")"); - if (pSearchKeys.contains(curFprint) || pSearchKeys.contains(curUser)) { - if (LOCAL_LOGV) - Log.v(TAG, "master key found for: " + curFprint); - masterKeys.add(curMkey); - pSearchKeys.remove(curFprint); - } else { - if (LOCAL_LOGV) - Log.v(TAG, "Installed key " + curFprint - + " is not in the list of public keys to encrypt with"); - } - } - mCursor.close(); - - long[] masterKeyLongs = new long[masterKeys.size()]; - int i = 0; - for (Long key : masterKeys) { - masterKeyLongs[i++] = key; - } - - if (i == 0) { - Log.w(TAG, "Found not one public key"); - pReturn.getStringArrayList(ret.WARNINGS.name()).add( - "Searched for public key(s) but found not one"); - } - - for (String key : pSearchKeys) { - Log.w(TAG, "Searched for key " + key + " but cannot find it in APG"); - pReturn.getStringArrayList(ret.WARNINGS.name()).add( - "Searched for key " + key + " but cannot find it in APG"); - } - - return masterKeyLongs; - } - - /** - * Add default arguments if missing - * - * @param args - * the bundle to add default parameters to if missing - */ - private void addDefaultArguments(String pCall, Bundle pArgs) { - // check whether there are optional elements defined for that call - if (FUNCTIONS_OPTIONAL_ARGS.containsKey(pCall)) { - Preferences preferences = Preferences.getPreferences(getBaseContext(), true); - - Iterator iter = FUNCTIONS_DEFAULTS.keySet().iterator(); - while (iter.hasNext()) { - arg currentArg = iter.next(); - String currentKey = currentArg.name(); - if (!pArgs.containsKey(currentKey) - && FUNCTIONS_OPTIONAL_ARGS.get(pCall).contains(currentArg)) { - String currentFunctionName = FUNCTIONS_DEFAULTS.get(currentArg); - try { - Class returnType = FUNCTIONS_DEFAULTS_METHODS.get(currentFunctionName) - .getReturnType(); - if (returnType == String.class) { - pArgs.putString(currentKey, - (String) FUNCTIONS_DEFAULTS_METHODS.get(currentFunctionName) - .invoke(preferences)); - } else if (returnType == boolean.class) { - pArgs.putBoolean(currentKey, - (Boolean) FUNCTIONS_DEFAULTS_METHODS.get(currentFunctionName) - .invoke(preferences)); - } else if (returnType == int.class) { - pArgs.putInt(currentKey, - (Integer) FUNCTIONS_DEFAULTS_METHODS.get(currentFunctionName) - .invoke(preferences)); - } else { - Log.e(TAG, "Unknown return type " + returnType.toString() - + " for default option"); - } - } catch (Exception e) { - Log.e(TAG, "Exception in add_default_arguments " + e.getMessage()); - } - } - } - } - } - - /** - * updates a Bundle with default return values - * - * @param pReturn - * the Bundle to update - */ - private void addDefaultReturns(Bundle pReturn) { - ArrayList errors = new ArrayList(); - ArrayList warnings = new ArrayList(); - - pReturn.putStringArrayList(ret.ERRORS.name(), errors); - pReturn.putStringArrayList(ret.WARNINGS.name(), warnings); - } - - /** - * checks for required arguments and adds them to the error if missing - * - * @param function - * the functions required arguments to check for - * @param pArgs - * the Bundle of arguments to check - * @param pReturn - * the bundle to write errors to - */ - private void checkForRequiredArgs(String pFunction, Bundle pArgs, Bundle pReturn) { - if (FUNCTIONS_REQUIRED_ARGS.containsKey(pFunction)) { - Iterator iter = FUNCTIONS_REQUIRED_ARGS.get(pFunction).iterator(); - while (iter.hasNext()) { - String curArg = iter.next().name(); - if (!pArgs.containsKey(curArg)) { - pReturn.getStringArrayList(ret.ERRORS.name()) - .add("Argument missing: " + curArg); - } - } - } - - if (pFunction.equals(call.encrypt_with_passphrase.name()) - || pFunction.equals(call.encrypt_with_public_key.name()) - || pFunction.equals(call.decrypt.name())) { - // check that either MESSAGE or BLOB are there - if (!pArgs.containsKey(arg.MESSAGE.name()) && !pArgs.containsKey(arg.BLOB.name())) { - pReturn.getStringArrayList(ret.ERRORS.name()).add( - "Arguments missing: Neither MESSAGE nor BLOG found"); - } - - } - } - - /** - * checks for unknown arguments and add them to warning if found - * - * @param function - * the functions name to check against - * @param pArgs - * the Bundle of arguments to check - * @param pReturn - * the bundle to write warnings to - */ - private void checkForUnknownArgs(String pFunction, Bundle pArgs, Bundle pReturn) { - - HashSet allArgs = new HashSet(); - if (FUNCTIONS_REQUIRED_ARGS.containsKey(pFunction)) { - allArgs.addAll(FUNCTIONS_REQUIRED_ARGS.get(pFunction)); - } - if (FUNCTIONS_OPTIONAL_ARGS.containsKey(pFunction)) { - allArgs.addAll(FUNCTIONS_OPTIONAL_ARGS.get(pFunction)); - } - - ArrayList unknownArgs = new ArrayList(); - Iterator iter = pArgs.keySet().iterator(); - while (iter.hasNext()) { - String curKey = iter.next(); - try { - arg curArg = arg.valueOf(curKey); - if (!allArgs.contains(curArg)) { - pReturn.getStringArrayList(ret.WARNINGS.name()).add( - "Unknown argument: " + curKey); - unknownArgs.add(curKey); - } - } catch (Exception e) { - pReturn.getStringArrayList(ret.WARNINGS.name()).add("Unknown argument: " + curKey); - unknownArgs.add(curKey); - } - } - - // remove unknown arguments so our bundle has just what we need - for (String arg : unknownArgs) { - pArgs.remove(arg); - } - } - - private boolean prepareArgs(String pCall, Bundle pArgs, Bundle pReturn) { - // PGPMain.initialize(getBaseContext()); - - /* add default return values for all functions */ - addDefaultReturns(pReturn); - - /* add default arguments if missing */ - addDefaultArguments(pCall, pArgs); - if (LOCAL_LOGV) - Log.v(TAG, "add_default_arguments"); - - /* check for required arguments */ - checkForRequiredArgs(pCall, pArgs, pReturn); - if (LOCAL_LOGV) - Log.v(TAG, "check_required_args"); - - /* check for unknown arguments and add to warning if found */ - checkForUnknownArgs(pCall, pArgs, pReturn); - if (LOCAL_LOGV) - Log.v(TAG, "check_unknown_args"); - - /* return if errors happened */ - if (pReturn.getStringArrayList(ret.ERRORS.name()).size() != 0) { - if (LOCAL_LOGV) - Log.v(TAG, "Errors after preparing, not executing " + pCall); - pReturn.putInt(ret.ERROR.name(), error.ARGUMENTS_MISSING.shiftedOrdinal()); - return false; - } - if (LOCAL_LOGV) - Log.v(TAG, "error return"); - - return true; - } - - private boolean encrypt(Bundle pArgs, Bundle pReturn) { - boolean isBlob = pArgs.containsKey(arg.BLOB.name()); - - long pubMasterKeys[] = {}; - if (pArgs.containsKey(arg.PUBLIC_KEYS.name())) { - ArrayList list = pArgs.getStringArrayList(arg.PUBLIC_KEYS.name()); - ArrayList pubKeys = new ArrayList(); - if (LOCAL_LOGV) - Log.v(TAG, "Long size: " + list.size()); - Iterator iter = list.iterator(); - while (iter.hasNext()) { - pubKeys.add(iter.next()); - } - pubMasterKeys = getMasterKey(pubKeys, pReturn); - } - - InputStream inStream = null; - if (isBlob) { - ContentResolver cr = getContentResolver(); - try { - inStream = cr.openInputStream(Uri.parse(pArgs.getString(arg.BLOB.name()))); - } catch (Exception e) { - Log.e(TAG, "... exception on opening blob", e); - } - } else { - inStream = new ByteArrayInputStream(pArgs.getString(arg.MESSAGE.name()).getBytes()); - } - InputData in = new InputData(inStream, 0); // XXX Size second param? - - OutputStream out = new ByteArrayOutputStream(); - if (LOCAL_LOGV) - Log.v(TAG, "About to encrypt"); - try { - PGPMain.encrypt(getBaseContext(), // context - in, // input stream - out, // output stream - pArgs.getBoolean(arg.ARMORED_OUTPUT.name()), // ARMORED_OUTPUT - pubMasterKeys, // encryption keys - getMasterKey(pArgs.getString(arg.SIGNATURE_KEY.name()), pReturn), // signature - // key - pArgs.getString(arg.PRIVATE_KEY_PASSPHRASE.name()), // signature passphrase - null, // progress - pArgs.getInt(arg.ENCRYPTION_ALGORYTHM.name()), // encryption - pArgs.getInt(arg.HASH_ALGORYTHM.name()), // hash - pArgs.getInt(arg.COMPRESSION.name()), // compression - pArgs.getBoolean(arg.FORCE_V3_SIGNATURE.name()), // mPreferences.getForceV3Signatures(), - pArgs.getString(arg.SYMMETRIC_PASSPHRASE.name()) // passPhrase - ); - } catch (Exception e) { - Log.e(TAG, "Exception in encrypt"); - String msg = e.getMessage(); - if (msg.equals(getBaseContext().getString(R.string.error_noSignaturePassPhrase))) { - pReturn.getStringArrayList(ret.ERRORS.name()).add( - "Cannot encrypt (" + arg.PRIVATE_KEY_PASSPHRASE.name() + " missing): " - + msg); - pReturn.putInt(ret.ERROR.name(), - error.PRIVATE_KEY_PASSPHRASE_MISSING.shiftedOrdinal()); - } else if (msg.equals(getBaseContext().getString( - R.string.error_couldNotExtractPrivateKey))) { - pReturn.getStringArrayList(ret.ERRORS.name()).add( - "Cannot encrypt (" + arg.PRIVATE_KEY_PASSPHRASE.name() - + " probably wrong): " + msg); - pReturn.putInt(ret.ERROR.name(), - error.PRIVATE_KEY_PASSPHRASE_WRONG.shiftedOrdinal()); - } else { - pReturn.getStringArrayList(ret.ERRORS.name()).add( - "Internal failure (" + e.getClass() + ") in APG when encrypting: " - + e.getMessage()); - pReturn.putInt(ret.ERROR.name(), error.APG_FAILURE.shiftedOrdinal()); - } - return false; - } - if (LOCAL_LOGV) - Log.v(TAG, "Encrypted"); - if (isBlob) { - ContentResolver cr = getContentResolver(); - try { - OutputStream outStream = cr.openOutputStream(Uri.parse(pArgs.getString(arg.BLOB - .name()))); - writeToOutputStream(new ByteArrayInputStream(out.toString().getBytes()), outStream); - outStream.close(); - } catch (Exception e) { - Log.e(TAG, "... exception on writing blob", e); - } - } else { - pReturn.putString(ret.RESULT.name(), out.toString()); - } - return true; - } - - private final IApgService2.Stub mBinder = new IApgService2.Stub() { - - public boolean getKeys(Bundle pArgs, Bundle pReturn) { - - prepareArgs("get_keys", pArgs, pReturn); - - HashMap qParams = new HashMap(); - qParams.put("columns", new String[] { - KeyRings.TABLE_NAME + "." + KeyRings.MASTER_KEY_ID, // 0 - UserIds.TABLE_NAME + "." + UserIds.USER_ID, // 1 - }); - - qParams.put("key_type", pArgs.getInt(arg.KEY_TYPE.name())); - - Cursor cursor = getKeyEntries(qParams); - ArrayList fPrints = new ArrayList(); - ArrayList ids = new ArrayList(); - while (cursor.moveToNext()) { - if (LOCAL_LOGV) - Log.v(TAG, "adding key " + PGPHelper.getSmallFingerPrint(cursor.getLong(0))); - fPrints.add(PGPHelper.getSmallFingerPrint(cursor.getLong(0))); - ids.add(cursor.getString(1)); - } - cursor.close(); - - pReturn.putStringArrayList(ret.FINGERPRINTS.name(), fPrints); - pReturn.putStringArrayList(ret.USER_IDS.name(), ids); - return true; - } - - public boolean encryptWithPublicKey(Bundle pArgs, Bundle pReturn) { - if (!prepareArgs("encrypt_with_public_key", pArgs, pReturn)) { - return false; - } - - return encrypt(pArgs, pReturn); - } - - public boolean encryptWithPassphrase(Bundle pArgs, Bundle pReturn) { - if (!prepareArgs("encrypt_with_passphrase", pArgs, pReturn)) { - return false; - } - - return encrypt(pArgs, pReturn); - - } - - public boolean decrypt(Bundle pArgs, Bundle pReturn) { - if (!prepareArgs("decrypt", pArgs, pReturn)) { - return false; - } - - boolean isBlob = pArgs.containsKey(arg.BLOB.name()); - - String passphrase = pArgs.getString(arg.SYMMETRIC_PASSPHRASE.name()) != null ? pArgs - .getString(arg.SYMMETRIC_PASSPHRASE.name()) : pArgs - .getString(arg.PRIVATE_KEY_PASSPHRASE.name()); - - InputStream inStream = null; - if (isBlob) { - ContentResolver cr = getContentResolver(); - try { - inStream = cr.openInputStream(Uri.parse(pArgs.getString(arg.BLOB.name()))); - } catch (Exception e) { - Log.e(TAG, "... exception on opening blob", e); - } - } else { - inStream = new ByteArrayInputStream(pArgs.getString(arg.MESSAGE.name()).getBytes()); - } - - InputData in = new InputData(inStream, 0); // XXX what size in second parameter? - OutputStream out = new ByteArrayOutputStream(); - if (LOCAL_LOGV) - Log.v(TAG, "About to decrypt"); - try { - PGPMain.decrypt(getBaseContext(), in, out, passphrase, null, // progress - pArgs.getString(arg.SYMMETRIC_PASSPHRASE.name()) != null // symmetric - ); - } catch (Exception e) { - Log.e(TAG, "Exception in decrypt"); - String msg = e.getMessage(); - if (msg.equals(getBaseContext().getString(R.string.error_noSecretKeyFound))) { - pReturn.getStringArrayList(ret.ERRORS.name()).add("Cannot decrypt: " + msg); - pReturn.putInt(ret.ERROR.name(), error.NO_MATCHING_SECRET_KEY.shiftedOrdinal()); - } else if (msg.equals(getBaseContext().getString(R.string.error_wrongPassPhrase))) { - pReturn.getStringArrayList(ret.ERRORS.name()).add( - "Cannot decrypt (" + arg.PRIVATE_KEY_PASSPHRASE.name() - + " wrong/missing): " + msg); - pReturn.putInt(ret.ERROR.name(), - error.PRIVATE_KEY_PASSPHRASE_WRONG.shiftedOrdinal()); - } else { - pReturn.getStringArrayList(ret.ERRORS.name()).add( - "Internal failure (" + e.getClass() + ") in APG when decrypting: " - + msg); - pReturn.putInt(ret.ERROR.name(), error.APG_FAILURE.shiftedOrdinal()); - } - return false; - } - if (LOCAL_LOGV) - Log.v(TAG, "... decrypted"); - - if (isBlob) { - ContentResolver cr = getContentResolver(); - try { - OutputStream outStream = cr.openOutputStream(Uri.parse(pArgs.getString(arg.BLOB - .name()))); - writeToOutputStream(new ByteArrayInputStream(out.toString().getBytes()), - outStream); - outStream.close(); - } catch (Exception e) { - Log.e(TAG, "... exception on writing blob", e); - } - } else { - pReturn.putString(ret.RESULT.name(), out.toString()); - } - return true; - } - - }; -} +///* +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +// +//package org.thialfihar.android.apg.deprecated; +// +//import java.io.ByteArrayInputStream; +//import java.io.ByteArrayOutputStream; +//import java.io.IOException; +//import java.io.InputStream; +//import java.io.OutputStream; +//import java.lang.reflect.Method; +//import java.util.ArrayList; +//import java.util.HashMap; +//import java.util.HashSet; +//import java.util.Iterator; +// +//import org.thialfihar.android.apg.deprecated.IApgService2; +//import org.thialfihar.android.apg.Id; +//import org.thialfihar.android.apg.R; +//import org.thialfihar.android.apg.deprecated.IApgService2.Stub; +//import org.thialfihar.android.apg.Id.database; +//import org.thialfihar.android.apg.R.string; +//import org.thialfihar.android.apg.helper.PGPHelper; +//import org.thialfihar.android.apg.helper.PGPMain; +//import org.thialfihar.android.apg.helper.Preferences; +//import org.thialfihar.android.apg.provider.KeyRings; +//import org.thialfihar.android.apg.provider.Keys; +//import org.thialfihar.android.apg.provider.UserIds; +//import org.thialfihar.android.apg.service.PassphraseCacheService; +//import org.thialfihar.android.apg.util.InputData; +// +//import android.content.ContentResolver; +//import android.content.Intent; +//import android.database.Cursor; +//import android.database.sqlite.SQLiteQueryBuilder; +//import android.net.Uri; +//import android.os.Bundle; +//import android.os.IBinder; +//import org.thialfihar.android.apg.util.Log; +// +///** +// * ATTENTION: +// * +// * This is the old ApgService used as remote service over aidl interface. It will be reworked! +// * +// */ +//public class ApgService2 extends PassphraseCacheService { +// private final static String TAG = "ApgService"; +// public static final boolean LOCAL_LOGV = true; +// public static final boolean LOCAL_LOGD = true; +// +// @Override +// public IBinder onBind(Intent intent) { +// if (LOCAL_LOGD) +// Log.d(TAG, "bound"); +// return mBinder; +// } +// +// /** error status */ +// private static enum error { +// ARGUMENTS_MISSING, APG_FAILURE, NO_MATCHING_SECRET_KEY, PRIVATE_KEY_PASSPHRASE_WRONG, PRIVATE_KEY_PASSPHRASE_MISSING; +// +// public int shiftedOrdinal() { +// return ordinal() + 100; +// } +// } +// +// private static enum call { +// encrypt_with_passphrase, encrypt_with_public_key, decrypt, get_keys +// } +// +// /** all arguments that can be passed by calling application */ +// public static enum arg { +// MESSAGE, // message to encrypt or to decrypt +// SYMMETRIC_PASSPHRASE, // key for symmetric en/decryption +// PUBLIC_KEYS, // public keys for encryption +// ENCRYPTION_ALGORYTHM, // encryption algorithm +// HASH_ALGORYTHM, // hash algorithm +// ARMORED_OUTPUT, // whether to armor output +// FORCE_V3_SIGNATURE, // whether to force v3 signature +// COMPRESSION, // what compression to use for encrypted output +// SIGNATURE_KEY, // key for signing +// PRIVATE_KEY_PASSPHRASE, // passphrase for encrypted private key +// KEY_TYPE, // type of key (private or public) +// BLOB, // blob passed +// } +// +// /** all things that might be returned */ +// private static enum ret { +// ERRORS, // string array list with errors +// WARNINGS, // string array list with warnings +// ERROR, // numeric error +// RESULT, // en-/decrypted +// FINGERPRINTS, // fingerprints of keys +// USER_IDS, // user ids +// } +// +// /** required arguments for each AIDL function */ +// private static final HashMap> FUNCTIONS_REQUIRED_ARGS = new HashMap>(); +// static { +// HashSet args = new HashSet(); +// args.add(arg.SYMMETRIC_PASSPHRASE); +// FUNCTIONS_REQUIRED_ARGS.put(call.encrypt_with_passphrase.name(), args); +// +// args = new HashSet(); +// args.add(arg.PUBLIC_KEYS); +// FUNCTIONS_REQUIRED_ARGS.put(call.encrypt_with_public_key.name(), args); +// +// args = new HashSet(); +// FUNCTIONS_REQUIRED_ARGS.put(call.decrypt.name(), args); +// +// args = new HashSet(); +// args.add(arg.KEY_TYPE); +// FUNCTIONS_REQUIRED_ARGS.put(call.get_keys.name(), args); +// } +// +// /** optional arguments for each AIDL function */ +// private static final HashMap> FUNCTIONS_OPTIONAL_ARGS = new HashMap>(); +// static { +// HashSet args = new HashSet(); +// args.add(arg.ENCRYPTION_ALGORYTHM); +// args.add(arg.HASH_ALGORYTHM); +// args.add(arg.ARMORED_OUTPUT); +// args.add(arg.FORCE_V3_SIGNATURE); +// args.add(arg.COMPRESSION); +// args.add(arg.PRIVATE_KEY_PASSPHRASE); +// args.add(arg.SIGNATURE_KEY); +// args.add(arg.BLOB); +// args.add(arg.MESSAGE); +// FUNCTIONS_OPTIONAL_ARGS.put(call.encrypt_with_passphrase.name(), args); +// FUNCTIONS_OPTIONAL_ARGS.put(call.encrypt_with_public_key.name(), args); +// +// args = new HashSet(); +// args.add(arg.SYMMETRIC_PASSPHRASE); +// args.add(arg.PUBLIC_KEYS); +// args.add(arg.PRIVATE_KEY_PASSPHRASE); +// args.add(arg.MESSAGE); +// args.add(arg.BLOB); +// FUNCTIONS_OPTIONAL_ARGS.put(call.decrypt.name(), args); +// } +// +// /** a map from ApgService parameters to function calls to get the default */ +// private static final HashMap FUNCTIONS_DEFAULTS = new HashMap(); +// static { +// FUNCTIONS_DEFAULTS.put(arg.ENCRYPTION_ALGORYTHM, "getDefaultEncryptionAlgorithm"); +// FUNCTIONS_DEFAULTS.put(arg.HASH_ALGORYTHM, "getDefaultHashAlgorithm"); +// FUNCTIONS_DEFAULTS.put(arg.ARMORED_OUTPUT, "getDefaultAsciiArmour"); +// FUNCTIONS_DEFAULTS.put(arg.FORCE_V3_SIGNATURE, "getForceV3Signatures"); +// FUNCTIONS_DEFAULTS.put(arg.COMPRESSION, "getDefaultMessageCompression"); +// } +// +// /** a map of the default function names to their method */ +// private static final HashMap FUNCTIONS_DEFAULTS_METHODS = new HashMap(); +// static { +// try { +// FUNCTIONS_DEFAULTS_METHODS.put("getDefaultEncryptionAlgorithm", +// Preferences.class.getMethod("getDefaultEncryptionAlgorithm")); +// FUNCTIONS_DEFAULTS_METHODS.put("getDefaultHashAlgorithm", +// Preferences.class.getMethod("getDefaultHashAlgorithm")); +// FUNCTIONS_DEFAULTS_METHODS.put("getDefaultAsciiArmour", +// Preferences.class.getMethod("getDefaultAsciiArmour")); +// FUNCTIONS_DEFAULTS_METHODS.put("getForceV3Signatures", +// Preferences.class.getMethod("getForceV3Signatures")); +// FUNCTIONS_DEFAULTS_METHODS.put("getDefaultMessageCompression", +// Preferences.class.getMethod("getDefaultMessageCompression")); +// } catch (Exception e) { +// Log.e(TAG, "Function method exception: " + e.getMessage()); +// } +// } +// +// private static void writeToOutputStream(InputStream is, OutputStream os) throws IOException { +// byte[] buffer = new byte[8]; +// int len = 0; +// while ((len = is.read(buffer)) != -1) { +// os.write(buffer, 0, len); +// } +// } +// +// private static Cursor getKeyEntries(HashMap pParams) { +// SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); +// qb.setTables(KeyRings.TABLE_NAME + " INNER JOIN " + Keys.TABLE_NAME + " ON " + "(" +// + KeyRings.TABLE_NAME + "." + KeyRings._ID + " = " + Keys.TABLE_NAME + "." +// + Keys.KEY_RING_ID + " AND " + Keys.TABLE_NAME + "." + Keys.IS_MASTER_KEY +// + " = '1'" + ") " + " INNER JOIN " + UserIds.TABLE_NAME + " ON " + "(" +// + Keys.TABLE_NAME + "." + Keys._ID + " = " + UserIds.TABLE_NAME + "." +// + UserIds.KEY_ID + " AND " + UserIds.TABLE_NAME + "." + UserIds.RANK + " = '0') "); +// +// String orderBy = pParams.containsKey("order_by") ? (String) pParams.get("order_by") +// : UserIds.TABLE_NAME + "." + UserIds.USER_ID + " ASC"; +// +// String typeVal[] = null; +// String typeWhere = null; +// if (pParams.containsKey("key_type")) { +// typeWhere = KeyRings.TABLE_NAME + "." + KeyRings.TYPE + " = ?"; +// typeVal = new String[] { "" + pParams.get("key_type") }; +// } +// return qb.query(PGPMain.getDatabase().db(), (String[]) pParams.get("columns"), typeWhere, +// typeVal, null, null, orderBy); +// } +// +// /** +// * maps a fingerprint or user id of a key to a master key in database +// * +// * @param search_key +// * fingerprint or user id to search for +// * @return master key if found, or 0 +// */ +// private static long getMasterKey(String pSearchKey, Bundle pReturn) { +// if (pSearchKey == null || pSearchKey.length() != 8) { +// return 0; +// } +// ArrayList keyList = new ArrayList(); +// keyList.add(pSearchKey); +// long[] keys = getMasterKey(keyList, pReturn); +// if (keys.length > 0) { +// return keys[0]; +// } else { +// return 0; +// } +// } +// +// /** +// * maps fingerprints or user ids of keys to master keys in database +// * +// * @param search_keys +// * a list of keys (fingerprints or user ids) to look for in database +// * @return an array of master keys +// */ +// private static long[] getMasterKey(ArrayList pSearchKeys, Bundle pReturn) { +// +// HashMap qParams = new HashMap(); +// qParams.put("columns", new String[] { KeyRings.TABLE_NAME + "." + KeyRings.MASTER_KEY_ID, // 0 +// UserIds.TABLE_NAME + "." + UserIds.USER_ID, // 1 +// }); +// qParams.put("key_type", Id.database.type_public); +// +// Cursor mCursor = getKeyEntries(qParams); +// +// if (LOCAL_LOGV) +// Log.v(TAG, "going through installed user keys"); +// ArrayList masterKeys = new ArrayList(); +// while (mCursor.moveToNext()) { +// long curMkey = mCursor.getLong(0); +// String curUser = mCursor.getString(1); +// +// String curFprint = PGPHelper.getSmallFingerPrint(curMkey); +// if (LOCAL_LOGV) +// Log.v(TAG, "current user: " + curUser + " (" + curFprint + ")"); +// if (pSearchKeys.contains(curFprint) || pSearchKeys.contains(curUser)) { +// if (LOCAL_LOGV) +// Log.v(TAG, "master key found for: " + curFprint); +// masterKeys.add(curMkey); +// pSearchKeys.remove(curFprint); +// } else { +// if (LOCAL_LOGV) +// Log.v(TAG, "Installed key " + curFprint +// + " is not in the list of public keys to encrypt with"); +// } +// } +// mCursor.close(); +// +// long[] masterKeyLongs = new long[masterKeys.size()]; +// int i = 0; +// for (Long key : masterKeys) { +// masterKeyLongs[i++] = key; +// } +// +// if (i == 0) { +// Log.w(TAG, "Found not one public key"); +// pReturn.getStringArrayList(ret.WARNINGS.name()).add( +// "Searched for public key(s) but found not one"); +// } +// +// for (String key : pSearchKeys) { +// Log.w(TAG, "Searched for key " + key + " but cannot find it in APG"); +// pReturn.getStringArrayList(ret.WARNINGS.name()).add( +// "Searched for key " + key + " but cannot find it in APG"); +// } +// +// return masterKeyLongs; +// } +// +// /** +// * Add default arguments if missing +// * +// * @param args +// * the bundle to add default parameters to if missing +// */ +// private void addDefaultArguments(String pCall, Bundle pArgs) { +// // check whether there are optional elements defined for that call +// if (FUNCTIONS_OPTIONAL_ARGS.containsKey(pCall)) { +// Preferences preferences = Preferences.getPreferences(getBaseContext(), true); +// +// Iterator iter = FUNCTIONS_DEFAULTS.keySet().iterator(); +// while (iter.hasNext()) { +// arg currentArg = iter.next(); +// String currentKey = currentArg.name(); +// if (!pArgs.containsKey(currentKey) +// && FUNCTIONS_OPTIONAL_ARGS.get(pCall).contains(currentArg)) { +// String currentFunctionName = FUNCTIONS_DEFAULTS.get(currentArg); +// try { +// Class returnType = FUNCTIONS_DEFAULTS_METHODS.get(currentFunctionName) +// .getReturnType(); +// if (returnType == String.class) { +// pArgs.putString(currentKey, +// (String) FUNCTIONS_DEFAULTS_METHODS.get(currentFunctionName) +// .invoke(preferences)); +// } else if (returnType == boolean.class) { +// pArgs.putBoolean(currentKey, +// (Boolean) FUNCTIONS_DEFAULTS_METHODS.get(currentFunctionName) +// .invoke(preferences)); +// } else if (returnType == int.class) { +// pArgs.putInt(currentKey, +// (Integer) FUNCTIONS_DEFAULTS_METHODS.get(currentFunctionName) +// .invoke(preferences)); +// } else { +// Log.e(TAG, "Unknown return type " + returnType.toString() +// + " for default option"); +// } +// } catch (Exception e) { +// Log.e(TAG, "Exception in add_default_arguments " + e.getMessage()); +// } +// } +// } +// } +// } +// +// /** +// * updates a Bundle with default return values +// * +// * @param pReturn +// * the Bundle to update +// */ +// private void addDefaultReturns(Bundle pReturn) { +// ArrayList errors = new ArrayList(); +// ArrayList warnings = new ArrayList(); +// +// pReturn.putStringArrayList(ret.ERRORS.name(), errors); +// pReturn.putStringArrayList(ret.WARNINGS.name(), warnings); +// } +// +// /** +// * checks for required arguments and adds them to the error if missing +// * +// * @param function +// * the functions required arguments to check for +// * @param pArgs +// * the Bundle of arguments to check +// * @param pReturn +// * the bundle to write errors to +// */ +// private void checkForRequiredArgs(String pFunction, Bundle pArgs, Bundle pReturn) { +// if (FUNCTIONS_REQUIRED_ARGS.containsKey(pFunction)) { +// Iterator iter = FUNCTIONS_REQUIRED_ARGS.get(pFunction).iterator(); +// while (iter.hasNext()) { +// String curArg = iter.next().name(); +// if (!pArgs.containsKey(curArg)) { +// pReturn.getStringArrayList(ret.ERRORS.name()) +// .add("Argument missing: " + curArg); +// } +// } +// } +// +// if (pFunction.equals(call.encrypt_with_passphrase.name()) +// || pFunction.equals(call.encrypt_with_public_key.name()) +// || pFunction.equals(call.decrypt.name())) { +// // check that either MESSAGE or BLOB are there +// if (!pArgs.containsKey(arg.MESSAGE.name()) && !pArgs.containsKey(arg.BLOB.name())) { +// pReturn.getStringArrayList(ret.ERRORS.name()).add( +// "Arguments missing: Neither MESSAGE nor BLOG found"); +// } +// +// } +// } +// +// /** +// * checks for unknown arguments and add them to warning if found +// * +// * @param function +// * the functions name to check against +// * @param pArgs +// * the Bundle of arguments to check +// * @param pReturn +// * the bundle to write warnings to +// */ +// private void checkForUnknownArgs(String pFunction, Bundle pArgs, Bundle pReturn) { +// +// HashSet allArgs = new HashSet(); +// if (FUNCTIONS_REQUIRED_ARGS.containsKey(pFunction)) { +// allArgs.addAll(FUNCTIONS_REQUIRED_ARGS.get(pFunction)); +// } +// if (FUNCTIONS_OPTIONAL_ARGS.containsKey(pFunction)) { +// allArgs.addAll(FUNCTIONS_OPTIONAL_ARGS.get(pFunction)); +// } +// +// ArrayList unknownArgs = new ArrayList(); +// Iterator iter = pArgs.keySet().iterator(); +// while (iter.hasNext()) { +// String curKey = iter.next(); +// try { +// arg curArg = arg.valueOf(curKey); +// if (!allArgs.contains(curArg)) { +// pReturn.getStringArrayList(ret.WARNINGS.name()).add( +// "Unknown argument: " + curKey); +// unknownArgs.add(curKey); +// } +// } catch (Exception e) { +// pReturn.getStringArrayList(ret.WARNINGS.name()).add("Unknown argument: " + curKey); +// unknownArgs.add(curKey); +// } +// } +// +// // remove unknown arguments so our bundle has just what we need +// for (String arg : unknownArgs) { +// pArgs.remove(arg); +// } +// } +// +// private boolean prepareArgs(String pCall, Bundle pArgs, Bundle pReturn) { +// // PGPMain.initialize(getBaseContext()); +// +// /* add default return values for all functions */ +// addDefaultReturns(pReturn); +// +// /* add default arguments if missing */ +// addDefaultArguments(pCall, pArgs); +// if (LOCAL_LOGV) +// Log.v(TAG, "add_default_arguments"); +// +// /* check for required arguments */ +// checkForRequiredArgs(pCall, pArgs, pReturn); +// if (LOCAL_LOGV) +// Log.v(TAG, "check_required_args"); +// +// /* check for unknown arguments and add to warning if found */ +// checkForUnknownArgs(pCall, pArgs, pReturn); +// if (LOCAL_LOGV) +// Log.v(TAG, "check_unknown_args"); +// +// /* return if errors happened */ +// if (pReturn.getStringArrayList(ret.ERRORS.name()).size() != 0) { +// if (LOCAL_LOGV) +// Log.v(TAG, "Errors after preparing, not executing " + pCall); +// pReturn.putInt(ret.ERROR.name(), error.ARGUMENTS_MISSING.shiftedOrdinal()); +// return false; +// } +// if (LOCAL_LOGV) +// Log.v(TAG, "error return"); +// +// return true; +// } +// +// private boolean encrypt(Bundle pArgs, Bundle pReturn) { +// boolean isBlob = pArgs.containsKey(arg.BLOB.name()); +// +// long pubMasterKeys[] = {}; +// if (pArgs.containsKey(arg.PUBLIC_KEYS.name())) { +// ArrayList list = pArgs.getStringArrayList(arg.PUBLIC_KEYS.name()); +// ArrayList pubKeys = new ArrayList(); +// if (LOCAL_LOGV) +// Log.v(TAG, "Long size: " + list.size()); +// Iterator iter = list.iterator(); +// while (iter.hasNext()) { +// pubKeys.add(iter.next()); +// } +// pubMasterKeys = getMasterKey(pubKeys, pReturn); +// } +// +// InputStream inStream = null; +// if (isBlob) { +// ContentResolver cr = getContentResolver(); +// try { +// inStream = cr.openInputStream(Uri.parse(pArgs.getString(arg.BLOB.name()))); +// } catch (Exception e) { +// Log.e(TAG, "... exception on opening blob", e); +// } +// } else { +// inStream = new ByteArrayInputStream(pArgs.getString(arg.MESSAGE.name()).getBytes()); +// } +// InputData in = new InputData(inStream, 0); // XXX Size second param? +// +// OutputStream out = new ByteArrayOutputStream(); +// if (LOCAL_LOGV) +// Log.v(TAG, "About to encrypt"); +// try { +// PGPMain.encrypt(getBaseContext(), // context +// in, // input stream +// out, // output stream +// pArgs.getBoolean(arg.ARMORED_OUTPUT.name()), // ARMORED_OUTPUT +// pubMasterKeys, // encryption keys +// getMasterKey(pArgs.getString(arg.SIGNATURE_KEY.name()), pReturn), // signature +// // key +// pArgs.getString(arg.PRIVATE_KEY_PASSPHRASE.name()), // signature passphrase +// null, // progress +// pArgs.getInt(arg.ENCRYPTION_ALGORYTHM.name()), // encryption +// pArgs.getInt(arg.HASH_ALGORYTHM.name()), // hash +// pArgs.getInt(arg.COMPRESSION.name()), // compression +// pArgs.getBoolean(arg.FORCE_V3_SIGNATURE.name()), // mPreferences.getForceV3Signatures(), +// pArgs.getString(arg.SYMMETRIC_PASSPHRASE.name()) // passPhrase +// ); +// } catch (Exception e) { +// Log.e(TAG, "Exception in encrypt"); +// String msg = e.getMessage(); +// if (msg.equals(getBaseContext().getString(R.string.error_noSignaturePassPhrase))) { +// pReturn.getStringArrayList(ret.ERRORS.name()).add( +// "Cannot encrypt (" + arg.PRIVATE_KEY_PASSPHRASE.name() + " missing): " +// + msg); +// pReturn.putInt(ret.ERROR.name(), +// error.PRIVATE_KEY_PASSPHRASE_MISSING.shiftedOrdinal()); +// } else if (msg.equals(getBaseContext().getString( +// R.string.error_couldNotExtractPrivateKey))) { +// pReturn.getStringArrayList(ret.ERRORS.name()).add( +// "Cannot encrypt (" + arg.PRIVATE_KEY_PASSPHRASE.name() +// + " probably wrong): " + msg); +// pReturn.putInt(ret.ERROR.name(), +// error.PRIVATE_KEY_PASSPHRASE_WRONG.shiftedOrdinal()); +// } else { +// pReturn.getStringArrayList(ret.ERRORS.name()).add( +// "Internal failure (" + e.getClass() + ") in APG when encrypting: " +// + e.getMessage()); +// pReturn.putInt(ret.ERROR.name(), error.APG_FAILURE.shiftedOrdinal()); +// } +// return false; +// } +// if (LOCAL_LOGV) +// Log.v(TAG, "Encrypted"); +// if (isBlob) { +// ContentResolver cr = getContentResolver(); +// try { +// OutputStream outStream = cr.openOutputStream(Uri.parse(pArgs.getString(arg.BLOB +// .name()))); +// writeToOutputStream(new ByteArrayInputStream(out.toString().getBytes()), outStream); +// outStream.close(); +// } catch (Exception e) { +// Log.e(TAG, "... exception on writing blob", e); +// } +// } else { +// pReturn.putString(ret.RESULT.name(), out.toString()); +// } +// return true; +// } +// +// private final IApgService2.Stub mBinder = new IApgService2.Stub() { +// +// public boolean getKeys(Bundle pArgs, Bundle pReturn) { +// +// prepareArgs("get_keys", pArgs, pReturn); +// +// HashMap qParams = new HashMap(); +// qParams.put("columns", new String[] { +// KeyRings.TABLE_NAME + "." + KeyRings.MASTER_KEY_ID, // 0 +// UserIds.TABLE_NAME + "." + UserIds.USER_ID, // 1 +// }); +// +// qParams.put("key_type", pArgs.getInt(arg.KEY_TYPE.name())); +// +// Cursor cursor = getKeyEntries(qParams); +// ArrayList fPrints = new ArrayList(); +// ArrayList ids = new ArrayList(); +// while (cursor.moveToNext()) { +// if (LOCAL_LOGV) +// Log.v(TAG, "adding key " + PGPHelper.getSmallFingerPrint(cursor.getLong(0))); +// fPrints.add(PGPHelper.getSmallFingerPrint(cursor.getLong(0))); +// ids.add(cursor.getString(1)); +// } +// cursor.close(); +// +// pReturn.putStringArrayList(ret.FINGERPRINTS.name(), fPrints); +// pReturn.putStringArrayList(ret.USER_IDS.name(), ids); +// return true; +// } +// +// public boolean encryptWithPublicKey(Bundle pArgs, Bundle pReturn) { +// if (!prepareArgs("encrypt_with_public_key", pArgs, pReturn)) { +// return false; +// } +// +// return encrypt(pArgs, pReturn); +// } +// +// public boolean encryptWithPassphrase(Bundle pArgs, Bundle pReturn) { +// if (!prepareArgs("encrypt_with_passphrase", pArgs, pReturn)) { +// return false; +// } +// +// return encrypt(pArgs, pReturn); +// +// } +// +// public boolean decrypt(Bundle pArgs, Bundle pReturn) { +// if (!prepareArgs("decrypt", pArgs, pReturn)) { +// return false; +// } +// +// boolean isBlob = pArgs.containsKey(arg.BLOB.name()); +// +// String passphrase = pArgs.getString(arg.SYMMETRIC_PASSPHRASE.name()) != null ? pArgs +// .getString(arg.SYMMETRIC_PASSPHRASE.name()) : pArgs +// .getString(arg.PRIVATE_KEY_PASSPHRASE.name()); +// +// InputStream inStream = null; +// if (isBlob) { +// ContentResolver cr = getContentResolver(); +// try { +// inStream = cr.openInputStream(Uri.parse(pArgs.getString(arg.BLOB.name()))); +// } catch (Exception e) { +// Log.e(TAG, "... exception on opening blob", e); +// } +// } else { +// inStream = new ByteArrayInputStream(pArgs.getString(arg.MESSAGE.name()).getBytes()); +// } +// +// InputData in = new InputData(inStream, 0); // XXX what size in second parameter? +// OutputStream out = new ByteArrayOutputStream(); +// if (LOCAL_LOGV) +// Log.v(TAG, "About to decrypt"); +// try { +// PGPMain.decrypt(getBaseContext(), in, out, passphrase, null, // progress +// pArgs.getString(arg.SYMMETRIC_PASSPHRASE.name()) != null // symmetric +// ); +// } catch (Exception e) { +// Log.e(TAG, "Exception in decrypt"); +// String msg = e.getMessage(); +// if (msg.equals(getBaseContext().getString(R.string.error_noSecretKeyFound))) { +// pReturn.getStringArrayList(ret.ERRORS.name()).add("Cannot decrypt: " + msg); +// pReturn.putInt(ret.ERROR.name(), error.NO_MATCHING_SECRET_KEY.shiftedOrdinal()); +// } else if (msg.equals(getBaseContext().getString(R.string.error_wrongPassPhrase))) { +// pReturn.getStringArrayList(ret.ERRORS.name()).add( +// "Cannot decrypt (" + arg.PRIVATE_KEY_PASSPHRASE.name() +// + " wrong/missing): " + msg); +// pReturn.putInt(ret.ERROR.name(), +// error.PRIVATE_KEY_PASSPHRASE_WRONG.shiftedOrdinal()); +// } else { +// pReturn.getStringArrayList(ret.ERRORS.name()).add( +// "Internal failure (" + e.getClass() + ") in APG when decrypting: " +// + msg); +// pReturn.putInt(ret.ERROR.name(), error.APG_FAILURE.shiftedOrdinal()); +// } +// return false; +// } +// if (LOCAL_LOGV) +// Log.v(TAG, "... decrypted"); +// +// if (isBlob) { +// ContentResolver cr = getContentResolver(); +// try { +// OutputStream outStream = cr.openOutputStream(Uri.parse(pArgs.getString(arg.BLOB +// .name()))); +// writeToOutputStream(new ByteArrayInputStream(out.toString().getBytes()), +// outStream); +// outStream.close(); +// } catch (Exception e) { +// Log.e(TAG, "... exception on writing blob", e); +// } +// } else { +// pReturn.putString(ret.RESULT.name(), out.toString()); +// } +// return true; +// } +// +// }; +//} diff --git a/org_apg/src/org/thialfihar/android/apg/deprecated/ApgServiceBlobDatabase.java b/org_apg/src/org/thialfihar/android/apg/deprecated/ApgServiceBlobDatabase.java index d58fb3305..30d9ea778 100644 --- a/org_apg/src/org/thialfihar/android/apg/deprecated/ApgServiceBlobDatabase.java +++ b/org_apg/src/org/thialfihar/android/apg/deprecated/ApgServiceBlobDatabase.java @@ -1,71 +1,71 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.thialfihar.android.apg.deprecated; - - -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.Context; -import android.database.Cursor; -import android.database.sqlite.SQLiteDatabase; -import android.database.sqlite.SQLiteOpenHelper; -import android.net.Uri; -import org.thialfihar.android.apg.util.Log; - -public class ApgServiceBlobDatabase extends SQLiteOpenHelper { - - private static final String TAG = "ApgServiceBlobDatabase"; - - private static final int VERSION = 1; - private static final String NAME = "apg_service_blob_data"; - private static final String TABLE = "data"; - - public ApgServiceBlobDatabase(Context context) { - super(context, NAME, null, VERSION); - if (ApgService2.LOCAL_LOGD) - Log.d(TAG, "constructor called"); - } - - @Override - public void onCreate(SQLiteDatabase db) { - if (ApgService2.LOCAL_LOGD) - Log.d(TAG, "onCreate() called"); - db.execSQL("create table " + TABLE + " ( _id integer primary key autoincrement," - + "key text not null)"); - } - - @Override - public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { - if (ApgService2.LOCAL_LOGD) - Log.d(TAG, "onUpgrade() called"); - // no upgrade necessary yet - } - - public Uri insert(ContentValues vals) { - if (ApgService2.LOCAL_LOGD) - Log.d(TAG, "insert() called"); - SQLiteDatabase db = this.getWritableDatabase(); - long newId = db.insert(TABLE, null, vals); - return ContentUris.withAppendedId(ApgServiceBlobProvider.CONTENT_URI, newId); - } - - public Cursor query(String id, String key) { - if (ApgService2.LOCAL_LOGD) - Log.d(TAG, "query() called"); - SQLiteDatabase db = this.getReadableDatabase(); - return db.query(TABLE, new String[] { "_id" }, "_id = ? and key = ?", new String[] { id, - key }, null, null, null); - } -} +///* +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +// +//package org.thialfihar.android.apg.deprecated; +// +// +//import android.content.ContentUris; +//import android.content.ContentValues; +//import android.content.Context; +//import android.database.Cursor; +//import android.database.sqlite.SQLiteDatabase; +//import android.database.sqlite.SQLiteOpenHelper; +//import android.net.Uri; +//import org.thialfihar.android.apg.util.Log; +// +//public class ApgServiceBlobDatabase extends SQLiteOpenHelper { +// +// private static final String TAG = "ApgServiceBlobDatabase"; +// +// private static final int VERSION = 1; +// private static final String NAME = "apg_service_blob_data"; +// private static final String TABLE = "data"; +// +// public ApgServiceBlobDatabase(Context context) { +// super(context, NAME, null, VERSION); +// if (ApgService2.LOCAL_LOGD) +// Log.d(TAG, "constructor called"); +// } +// +// @Override +// public void onCreate(SQLiteDatabase db) { +// if (ApgService2.LOCAL_LOGD) +// Log.d(TAG, "onCreate() called"); +// db.execSQL("create table " + TABLE + " ( _id integer primary key autoincrement," +// + "key text not null)"); +// } +// +// @Override +// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { +// if (ApgService2.LOCAL_LOGD) +// Log.d(TAG, "onUpgrade() called"); +// // no upgrade necessary yet +// } +// +// public Uri insert(ContentValues vals) { +// if (ApgService2.LOCAL_LOGD) +// Log.d(TAG, "insert() called"); +// SQLiteDatabase db = this.getWritableDatabase(); +// long newId = db.insert(TABLE, null, vals); +// return ContentUris.withAppendedId(ApgServiceBlobProvider.CONTENT_URI, newId); +// } +// +// public Cursor query(String id, String key) { +// if (ApgService2.LOCAL_LOGD) +// Log.d(TAG, "query() called"); +// SQLiteDatabase db = this.getReadableDatabase(); +// return db.query(TABLE, new String[] { "_id" }, "_id = ? and key = ?", new String[] { id, +// key }, null, null, null); +// } +//} diff --git a/org_apg/src/org/thialfihar/android/apg/deprecated/ApgServiceBlobProvider.java b/org_apg/src/org/thialfihar/android/apg/deprecated/ApgServiceBlobProvider.java index 51ba32e38..9d117ac74 100644 --- a/org_apg/src/org/thialfihar/android/apg/deprecated/ApgServiceBlobProvider.java +++ b/org_apg/src/org/thialfihar/android/apg/deprecated/ApgServiceBlobProvider.java @@ -1,151 +1,151 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.thialfihar.android.apg.deprecated; - -import org.thialfihar.android.apg.Constants; - -import android.content.ContentProvider; -import android.content.ContentValues; -import android.database.Cursor; -import android.net.Uri; -import android.os.ParcelFileDescriptor; -import org.thialfihar.android.apg.util.Log; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.List; -import java.util.UUID; - -public class ApgServiceBlobProvider extends ContentProvider { - - private static final String TAG = "ApgServiceBlobProvider"; - - public static final Uri CONTENT_URI = Uri.parse("content://org.thialfihar.android.apg.provider.apgserviceblobprovider"); - - private static final String COLUMN_KEY = "key"; - - private static final String STORE_PATH = Constants.path.APP_DIR+"/ApgServiceBlobs"; - - private ApgServiceBlobDatabase mDb = null; - - public ApgServiceBlobProvider() { - if(ApgService2.LOCAL_LOGD) Log.d(TAG, "Constructor called"); - File dir = new File(STORE_PATH); - dir.mkdirs(); - if(ApgService2.LOCAL_LOGD) Log.d(TAG, "Constructor finished"); - } - - @Override - public int delete(Uri arg0, String arg1, String[] arg2) { - if(ApgService2.LOCAL_LOGD) Log.d(TAG, "delete() called"); - // TODO Auto-generated method stub - return 0; - } - - @Override - public String getType(Uri arg0) { - if(ApgService2.LOCAL_LOGD) Log.d(TAG, "getType() called"); - // not needed for now - return null; - } - - @Override - public Uri insert(Uri uri, ContentValues ignored) { - if(ApgService2.LOCAL_LOGD) Log.d(TAG, "insert() called"); - // ContentValues are actually ignored, because we want to store a blob with no more information - // but have to create an record with the password generated here first - - ContentValues vals = new ContentValues(); - - // Insert a random key in the database. This has to provided by the caller when updating or - // getting the blob - String password = UUID.randomUUID().toString(); - vals.put(COLUMN_KEY, password); - - Uri insertedUri = mDb.insert(vals); - return Uri.withAppendedPath(insertedUri, password); - } - - @Override - public boolean onCreate() { - if(ApgService2.LOCAL_LOGD) Log.d(TAG, "onCreate() called"); - mDb = new ApgServiceBlobDatabase(getContext()); - // TODO Auto-generated method stub - return true; - } - - @Override - public Cursor query(Uri arg0, String[] arg1, String arg2, String[] arg3, String arg4) { - if(ApgService2.LOCAL_LOGD) Log.d(TAG, "query() called"); - // TODO Auto-generated method stub - return null; - } - - @Override - public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) { - if(ApgService2.LOCAL_LOGD) Log.d(TAG, "update() called"); - // TODO Auto-generated method stub - return 0; - } - - @Override - public ParcelFileDescriptor openFile(Uri uri, String mode) throws SecurityException, FileNotFoundException { - if(ApgService2.LOCAL_LOGD) Log.d(TAG, "openFile() called"); - if(ApgService2.LOCAL_LOGD) Log.d(TAG, "... with uri: "+uri.toString()); - if(ApgService2.LOCAL_LOGD) Log.d(TAG, "... with mode: "+mode); - - List segments = uri.getPathSegments(); - if(segments.size() < 2) { - throw new SecurityException("Password not found in URI"); - } - String id = segments.get(0); - String key = segments.get(1); - - if(ApgService2.LOCAL_LOGD) Log.d(TAG, "... got id: "+id); - if(ApgService2.LOCAL_LOGD) Log.d(TAG, "... and key: "+key); - - // get the data - Cursor result = mDb.query(id, key); - - if(result.getCount() == 0) { - // either the key is wrong or no id exists - throw new FileNotFoundException("No file found with that ID and/or password"); - } - - File targetFile = new File(STORE_PATH, id); - if(mode.equals("w")) { - if(ApgService2.LOCAL_LOGD) Log.d(TAG, "... will try to open file w"); - if( !targetFile.exists() ) { - try { - targetFile.createNewFile(); - } catch (IOException e) { - Log.e(TAG, "... got IEOException on creating new file", e); - throw new FileNotFoundException("Could not create file to write to"); - } - } - return ParcelFileDescriptor.open(targetFile, ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_TRUNCATE ); - } else if(mode.equals("r")) { - if(ApgService2.LOCAL_LOGD) Log.d(TAG, "... will try to open file r"); - if( !targetFile.exists() ) { - throw new FileNotFoundException("Error: Could not find the file requested"); - } - return ParcelFileDescriptor.open(targetFile, ParcelFileDescriptor.MODE_READ_ONLY); - } - - return null; - } - -} +///* +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +// +//package org.thialfihar.android.apg.deprecated; +// +//import org.thialfihar.android.apg.Constants; +// +//import android.content.ContentProvider; +//import android.content.ContentValues; +//import android.database.Cursor; +//import android.net.Uri; +//import android.os.ParcelFileDescriptor; +//import org.thialfihar.android.apg.util.Log; +// +//import java.io.File; +//import java.io.FileNotFoundException; +//import java.io.IOException; +//import java.util.List; +//import java.util.UUID; +// +//public class ApgServiceBlobProvider extends ContentProvider { +// +// private static final String TAG = "ApgServiceBlobProvider"; +// +// public static final Uri CONTENT_URI = Uri.parse("content://org.thialfihar.android.apg.provider.apgserviceblobprovider"); +// +// private static final String COLUMN_KEY = "key"; +// +// private static final String STORE_PATH = Constants.path.APP_DIR+"/ApgServiceBlobs"; +// +// private ApgServiceBlobDatabase mDb = null; +// +// public ApgServiceBlobProvider() { +// if(ApgService2.LOCAL_LOGD) Log.d(TAG, "Constructor called"); +// File dir = new File(STORE_PATH); +// dir.mkdirs(); +// if(ApgService2.LOCAL_LOGD) Log.d(TAG, "Constructor finished"); +// } +// +// @Override +// public int delete(Uri arg0, String arg1, String[] arg2) { +// if(ApgService2.LOCAL_LOGD) Log.d(TAG, "delete() called"); +// // TODO Auto-generated method stub +// return 0; +// } +// +// @Override +// public String getType(Uri arg0) { +// if(ApgService2.LOCAL_LOGD) Log.d(TAG, "getType() called"); +// // not needed for now +// return null; +// } +// +// @Override +// public Uri insert(Uri uri, ContentValues ignored) { +// if(ApgService2.LOCAL_LOGD) Log.d(TAG, "insert() called"); +// // ContentValues are actually ignored, because we want to store a blob with no more information +// // but have to create an record with the password generated here first +// +// ContentValues vals = new ContentValues(); +// +// // Insert a random key in the database. This has to provided by the caller when updating or +// // getting the blob +// String password = UUID.randomUUID().toString(); +// vals.put(COLUMN_KEY, password); +// +// Uri insertedUri = mDb.insert(vals); +// return Uri.withAppendedPath(insertedUri, password); +// } +// +// @Override +// public boolean onCreate() { +// if(ApgService2.LOCAL_LOGD) Log.d(TAG, "onCreate() called"); +// mDb = new ApgServiceBlobDatabase(getContext()); +// // TODO Auto-generated method stub +// return true; +// } +// +// @Override +// public Cursor query(Uri arg0, String[] arg1, String arg2, String[] arg3, String arg4) { +// if(ApgService2.LOCAL_LOGD) Log.d(TAG, "query() called"); +// // TODO Auto-generated method stub +// return null; +// } +// +// @Override +// public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) { +// if(ApgService2.LOCAL_LOGD) Log.d(TAG, "update() called"); +// // TODO Auto-generated method stub +// return 0; +// } +// +// @Override +// public ParcelFileDescriptor openFile(Uri uri, String mode) throws SecurityException, FileNotFoundException { +// if(ApgService2.LOCAL_LOGD) Log.d(TAG, "openFile() called"); +// if(ApgService2.LOCAL_LOGD) Log.d(TAG, "... with uri: "+uri.toString()); +// if(ApgService2.LOCAL_LOGD) Log.d(TAG, "... with mode: "+mode); +// +// List segments = uri.getPathSegments(); +// if(segments.size() < 2) { +// throw new SecurityException("Password not found in URI"); +// } +// String id = segments.get(0); +// String key = segments.get(1); +// +// if(ApgService2.LOCAL_LOGD) Log.d(TAG, "... got id: "+id); +// if(ApgService2.LOCAL_LOGD) Log.d(TAG, "... and key: "+key); +// +// // get the data +// Cursor result = mDb.query(id, key); +// +// if(result.getCount() == 0) { +// // either the key is wrong or no id exists +// throw new FileNotFoundException("No file found with that ID and/or password"); +// } +// +// File targetFile = new File(STORE_PATH, id); +// if(mode.equals("w")) { +// if(ApgService2.LOCAL_LOGD) Log.d(TAG, "... will try to open file w"); +// if( !targetFile.exists() ) { +// try { +// targetFile.createNewFile(); +// } catch (IOException e) { +// Log.e(TAG, "... got IEOException on creating new file", e); +// throw new FileNotFoundException("Could not create file to write to"); +// } +// } +// return ParcelFileDescriptor.open(targetFile, ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_TRUNCATE ); +// } else if(mode.equals("r")) { +// if(ApgService2.LOCAL_LOGD) Log.d(TAG, "... will try to open file r"); +// if( !targetFile.exists() ) { +// throw new FileNotFoundException("Error: Could not find the file requested"); +// } +// return ParcelFileDescriptor.open(targetFile, ParcelFileDescriptor.MODE_READ_ONLY); +// } +// +// return null; +// } +// +//} diff --git a/org_apg/src/org/thialfihar/android/apg/deprecated/Database.java b/org_apg/src/org/thialfihar/android/apg/deprecated/Database.java index 92bbaed4f..d2ca3bded 100644 --- a/org_apg/src/org/thialfihar/android/apg/deprecated/Database.java +++ b/org_apg/src/org/thialfihar/android/apg/deprecated/Database.java @@ -1,582 +1,582 @@ -///* -// * Licensed under the Apache License, Version 2.0 (the "License"); -// * you may not use this file except in compliance with the License. -// * You may obtain a copy of the License at -// * -// * http://www.apache.org/licenses/LICENSE-2.0 -// * -// * Unless required by applicable law or agreed to in writing, software -// * distributed under the License is distributed on an "AS IS" BASIS, -// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// * See the License for the specific language governing permissions and -// * limitations under the License. -// */ -// -//package org.thialfihar.android.apg.deprecated; -// -//import org.spongycastle.openpgp.PGPException; -//import org.spongycastle.openpgp.PGPPublicKey; -//import org.spongycastle.openpgp.PGPPublicKeyRing; -//import org.spongycastle.openpgp.PGPSecretKey; -//import org.spongycastle.openpgp.PGPSecretKeyRing; -//import org.thialfihar.android.apg.Id; -//import org.thialfihar.android.apg.helper.PGPHelper; -//import org.thialfihar.android.apg.util.IterableIterator; -// -//import android.content.ContentValues; -//import android.content.Context; -//import android.database.Cursor; -//import android.database.sqlite.SQLiteDatabase; -//import android.database.sqlite.SQLiteOpenHelper; -//import org.thialfihar.android.apg.util.Log; -// -//import java.io.IOException; -//import java.util.Date; -//import java.util.HashMap; -//import java.util.Vector; -// -//public class Database extends SQLiteOpenHelper { -// public static class GeneralException extends Exception { -// static final long serialVersionUID = 0xf812773343L; -// -// public GeneralException(String message) { -// super(message); -// } -// } -// -// private static final String DATABASE_NAME = "apg"; -// private static final int DATABASE_VERSION = 2; -// -// public static final String AUTHORITY = "org.thialfihar.android.apg.database"; -// -// public static HashMap sKeyRingsProjection; -// public static HashMap sKeysProjection; -// public static HashMap sUserIdsProjection; -// -// private SQLiteDatabase mDb = null; -// private int mStatus = 0; -// -// static { -// sKeyRingsProjection = new HashMap(); -// sKeyRingsProjection.put(KeyRings._ID, KeyRings._ID); -// sKeyRingsProjection.put(KeyRings.MASTER_KEY_ID, KeyRings.MASTER_KEY_ID); -// sKeyRingsProjection.put(KeyRings.TYPE, KeyRings.TYPE); -// sKeyRingsProjection.put(KeyRings.WHO_ID, KeyRings.WHO_ID); -// sKeyRingsProjection.put(KeyRings.KEY_RING_DATA, KeyRings.KEY_RING_DATA); -// -// sKeysProjection = new HashMap(); -// sKeysProjection.put(Keys._ID, Keys._ID); -// sKeysProjection.put(Keys.KEY_ID, Keys.KEY_ID); -// sKeysProjection.put(Keys.TYPE, Keys.TYPE); -// sKeysProjection.put(Keys.IS_MASTER_KEY, Keys.IS_MASTER_KEY); -// sKeysProjection.put(Keys.ALGORITHM, Keys.ALGORITHM); -// sKeysProjection.put(Keys.KEY_SIZE, Keys.KEY_SIZE); -// sKeysProjection.put(Keys.CAN_SIGN, Keys.CAN_SIGN); -// sKeysProjection.put(Keys.CAN_ENCRYPT, Keys.CAN_ENCRYPT); -// sKeysProjection.put(Keys.IS_REVOKED, Keys.IS_REVOKED); -// sKeysProjection.put(Keys.CREATION, Keys.CREATION); -// sKeysProjection.put(Keys.EXPIRY, Keys.EXPIRY); -// sKeysProjection.put(Keys.KEY_DATA, Keys.KEY_DATA); -// sKeysProjection.put(Keys.RANK, Keys.RANK); -// -// sUserIdsProjection = new HashMap(); -// sUserIdsProjection.put(UserIds._ID, UserIds._ID); -// sUserIdsProjection.put(UserIds.KEY_ID, UserIds.KEY_ID); -// sUserIdsProjection.put(UserIds.USER_ID, UserIds.USER_ID); -// sUserIdsProjection.put(UserIds.RANK, UserIds.RANK); -// } -// -// public Database(Context context) { -// super(context, DATABASE_NAME, null, DATABASE_VERSION); -// // force upgrade to test things -// //onUpgrade(getWritableDatabase(), 1, 2); -// mDb = getWritableDatabase(); -// } -// -// @Override -// protected void finalize() throws Throwable { -// mDb.close(); -// super.finalize(); -// } -// -// @Override -// public void onCreate(SQLiteDatabase db) { -// db.execSQL("CREATE TABLE " + KeyRings.TABLE_NAME + " (" + -// KeyRings._ID + " " + KeyRings._ID_type + "," + -// KeyRings.MASTER_KEY_ID + " " + KeyRings.MASTER_KEY_ID_type + ", " + -// KeyRings.TYPE + " " + KeyRings.TYPE_type + ", " + -// KeyRings.WHO_ID + " " + KeyRings.WHO_ID_type + ", " + -// KeyRings.KEY_RING_DATA + " " + KeyRings.KEY_RING_DATA_type + ");"); -// -// db.execSQL("CREATE TABLE " + Keys.TABLE_NAME + " (" + -// Keys._ID + " " + Keys._ID_type + "," + -// Keys.KEY_ID + " " + Keys.KEY_ID_type + ", " + -// Keys.TYPE + " " + Keys.TYPE_type + ", " + -// Keys.IS_MASTER_KEY + " " + Keys.IS_MASTER_KEY_type + ", " + -// Keys.ALGORITHM + " " + Keys.ALGORITHM_type + ", " + -// Keys.KEY_SIZE + " " + Keys.KEY_SIZE_type + ", " + -// Keys.CAN_SIGN + " " + Keys.CAN_SIGN_type + ", " + -// Keys.CAN_ENCRYPT + " " + Keys.CAN_ENCRYPT_type + ", " + -// Keys.IS_REVOKED + " " + Keys.IS_REVOKED_type + ", " + -// Keys.CREATION + " " + Keys.CREATION_type + ", " + -// Keys.EXPIRY + " " + Keys.EXPIRY_type + ", " + -// Keys.KEY_RING_ID + " " + Keys.KEY_RING_ID_type + ", " + -// Keys.KEY_DATA + " " + Keys.KEY_DATA_type + -// Keys.RANK + " " + Keys.RANK_type + ");"); -// -// db.execSQL("CREATE TABLE " + UserIds.TABLE_NAME + " (" + -// UserIds._ID + " " + UserIds._ID_type + "," + -// UserIds.KEY_ID + " " + UserIds.KEY_ID_type + "," + -// UserIds.USER_ID + " " + UserIds.USER_ID_type + "," + -// UserIds.RANK + " " + UserIds.RANK_type + ");"); -// -// } -// -// @Override -// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { -// mDb = db; -// for (int version = oldVersion; version < newVersion; ++version) { -// switch (version) { -// case 1: { // upgrade 1 to 2 -// db.execSQL("DROP TABLE IF EXISTS " + KeyRings.TABLE_NAME + ";"); -// db.execSQL("DROP TABLE IF EXISTS " + Keys.TABLE_NAME + ";"); -// db.execSQL("DROP TABLE IF EXISTS " + UserIds.TABLE_NAME + ";"); -// -// db.execSQL("CREATE TABLE " + KeyRings.TABLE_NAME + " (" + -// KeyRings._ID + " " + KeyRings._ID_type + "," + -// KeyRings.MASTER_KEY_ID + " " + KeyRings.MASTER_KEY_ID_type + ", " + -// KeyRings.TYPE + " " + KeyRings.TYPE_type + ", " + -// KeyRings.WHO_ID + " " + KeyRings.WHO_ID_type + ", " + -// KeyRings.KEY_RING_DATA + " " + KeyRings.KEY_RING_DATA_type + ");"); -// -// -// db.execSQL("CREATE TABLE " + Keys.TABLE_NAME + " (" + -// Keys._ID + " " + Keys._ID_type + "," + -// Keys.KEY_ID + " " + Keys.KEY_ID_type + ", " + -// Keys.TYPE + " " + Keys.TYPE_type + ", " + -// Keys.IS_MASTER_KEY + " " + Keys.IS_MASTER_KEY_type + ", " + -// Keys.ALGORITHM + " " + Keys.ALGORITHM_type + ", " + -// Keys.KEY_SIZE + " " + Keys.KEY_SIZE_type + ", " + -// Keys.CAN_SIGN + " " + Keys.CAN_SIGN_type + ", " + -// Keys.CAN_ENCRYPT + " " + Keys.CAN_ENCRYPT_type + ", " + -// Keys.IS_REVOKED + " " + Keys.IS_REVOKED_type + ", " + -// Keys.CREATION + " " + Keys.CREATION_type + ", " + -// Keys.EXPIRY + " " + Keys.EXPIRY_type + ", " + -// Keys.KEY_RING_ID + " " + Keys.KEY_RING_ID_type + ", " + -// Keys.KEY_DATA + " " + Keys.KEY_DATA_type + -// Keys.RANK + " " + Keys.RANK_type + ");"); -// -// db.execSQL("CREATE TABLE " + UserIds.TABLE_NAME + " (" + -// UserIds._ID + " " + UserIds._ID_type + "," + -// UserIds.KEY_ID + " " + UserIds.KEY_ID_type + "," + -// UserIds.USER_ID + " " + UserIds.USER_ID_type + "," + -// UserIds.RANK + " " + UserIds.RANK_type + ");"); -// -// Cursor cursor = db.query("public_keys", new String[] { "c_key_data" }, -// null, null, null, null, null); -// if (cursor != null && cursor.moveToFirst()) { -// do { -// byte[] data = cursor.getBlob(0); -// try { -// PGPPublicKeyRing keyRing = new PGPPublicKeyRing(data); -// saveKeyRing(keyRing); -// } catch (IOException e) { -// Log.e("apg.db.upgrade", "key import failed: " + e); -// } catch (GeneralException e) { -// Log.e("apg.db.upgrade", "key import failed: " + e); -// } -// } while (cursor.moveToNext()); -// } -// -// if (cursor != null) { -// cursor.close(); -// } -// -// cursor = db.query("secret_keys", new String[]{ "c_key_data" }, -// null, null, null, null, null); -// if (cursor != null && cursor.moveToFirst()) { -// do { -// byte[] data = cursor.getBlob(0); -// try { -// PGPSecretKeyRing keyRing = new PGPSecretKeyRing(data); -// saveKeyRing(keyRing); -// } catch (IOException e) { -// Log.e("apg.db.upgrade", "key import failed: " + e); -// } catch (PGPException e) { -// Log.e("apg.db.upgrade", "key import failed: " + e); -// } catch (GeneralException e) { -// Log.e("apg.db.upgrade", "key import failed: " + e); -// } -// } while (cursor.moveToNext()); -// } -// -// if (cursor != null) { -// cursor.close(); -// } -// -// db.execSQL("DROP TABLE IF EXISTS public_keys;"); -// db.execSQL("DROP TABLE IF EXISTS secret_keys;"); -// -// break; -// } -// -// default: { -// break; -// } -// } -// } -// mDb = null; -// } -// -// public int saveKeyRing(PGPPublicKeyRing keyRing) throws IOException, GeneralException { -// mDb.beginTransaction(); -// ContentValues values = new ContentValues(); -// PGPPublicKey masterKey = keyRing.getPublicKey(); -// long masterKeyId = masterKey.getKeyID(); -// -// values.put(KeyRings.MASTER_KEY_ID, masterKeyId); -// values.put(KeyRings.TYPE, Id.database.type_public); -// values.put(KeyRings.KEY_RING_DATA, keyRing.getEncoded()); -// -// long rowId = insertOrUpdateKeyRing(values); -// int returnValue = mStatus; -// -// if (rowId == -1) { -// throw new GeneralException("saving public key ring " + masterKeyId + " failed"); -// } -// -// Vector seenIds = new Vector(); -// int rank = 0; -// for (PGPPublicKey key : new IterableIterator(keyRing.getPublicKeys())) { -// seenIds.add(saveKey(rowId, key, rank)); -// ++rank; -// } -// -// String seenIdsStr = ""; -// for (Integer id : seenIds) { -// if (seenIdsStr.length() > 0) { -// seenIdsStr += ","; -// } -// seenIdsStr += id; -// } -// mDb.delete(Keys.TABLE_NAME, -// Keys.KEY_RING_ID + " = ? AND " + -// Keys._ID + " NOT IN (" + seenIdsStr + ")", -// new String[] { "" + rowId }); -// -// mDb.setTransactionSuccessful(); -// mDb.endTransaction(); -// return returnValue; -// } -// -// public int saveKeyRing(PGPSecretKeyRing keyRing) throws IOException, GeneralException { -// mDb.beginTransaction(); -// ContentValues values = new ContentValues(); -// PGPSecretKey masterKey = keyRing.getSecretKey(); -// long masterKeyId = masterKey.getKeyID(); -// -// values.put(KeyRings.MASTER_KEY_ID, masterKeyId); -// values.put(KeyRings.TYPE, Id.database.type_secret); -// values.put(KeyRings.KEY_RING_DATA, keyRing.getEncoded()); -// -// long rowId = insertOrUpdateKeyRing(values); -// int returnValue = mStatus; -// -// if (rowId == -1) { -// throw new GeneralException("saving secret key ring " + masterKeyId + " failed"); -// } -// -// Vector seenIds = new Vector(); -// int rank = 0; -// for (PGPSecretKey key : new IterableIterator(keyRing.getSecretKeys())) { -// seenIds.add(saveKey(rowId, key, rank)); -// ++rank; -// } -// -// String seenIdsStr = ""; -// for (Integer id : seenIds) { -// if (seenIdsStr.length() > 0) { -// seenIdsStr += ","; -// } -// seenIdsStr += id; -// } -// mDb.delete(Keys.TABLE_NAME, -// Keys.KEY_RING_ID + " = ? AND " + -// Keys._ID + " NOT IN (" + seenIdsStr + ")", -// new String[] { "" + rowId }); -// -// mDb.setTransactionSuccessful(); -// mDb.endTransaction(); -// return returnValue; -// } -// -// private int saveKey(long keyRingId, PGPPublicKey key, int rank) -// throws IOException, GeneralException { -// ContentValues values = new ContentValues(); -// -// values.put(Keys.KEY_ID, key.getKeyID()); -// values.put(Keys.TYPE, Id.database.type_public); -// values.put(Keys.IS_MASTER_KEY, key.isMasterKey()); -// values.put(Keys.ALGORITHM, key.getAlgorithm()); -// values.put(Keys.KEY_SIZE, key.getBitStrength()); -// values.put(Keys.CAN_SIGN, PGPHelper.isSigningKey(key)); -// values.put(Keys.CAN_ENCRYPT, PGPHelper.isEncryptionKey(key)); -// values.put(Keys.IS_REVOKED, key.isRevoked()); -// values.put(Keys.CREATION, PGPHelper.getCreationDate(key).getTime() / 1000); -// Date expiryDate = PGPHelper.getExpiryDate(key); -// if (expiryDate != null) { -// values.put(Keys.EXPIRY, expiryDate.getTime() / 1000); -// } -// values.put(Keys.KEY_RING_ID, keyRingId); -// values.put(Keys.KEY_DATA, key.getEncoded()); -// values.put(Keys.RANK, rank); -// -// long rowId = insertOrUpdateKey(values); -// -// if (rowId == -1) { -// throw new GeneralException("saving public key " + key.getKeyID() + " failed"); -// } -// -// Vector seenIds = new Vector(); -// int userIdRank = 0; -// for (String userId : new IterableIterator(key.getUserIDs())) { -// seenIds.add(saveUserId(rowId, userId, userIdRank)); -// ++userIdRank; -// } -// -// String seenIdsStr = ""; -// for (Integer id : seenIds) { -// if (seenIdsStr.length() > 0) { -// seenIdsStr += ","; -// } -// seenIdsStr += id; -// } -// mDb.delete(UserIds.TABLE_NAME, -// UserIds.KEY_ID + " = ? AND " + -// UserIds._ID + " NOT IN (" + seenIdsStr + ")", -// new String[] { "" + rowId }); -// -// return (int)rowId; -// } -// -// private int saveKey(long keyRingId, PGPSecretKey key, int rank) -// throws IOException, GeneralException { -// ContentValues values = new ContentValues(); -// -// values.put(Keys.KEY_ID, key.getPublicKey().getKeyID()); -// values.put(Keys.TYPE, Id.database.type_secret); -// values.put(Keys.IS_MASTER_KEY, key.isMasterKey()); -// values.put(Keys.ALGORITHM, key.getPublicKey().getAlgorithm()); -// values.put(Keys.KEY_SIZE, key.getPublicKey().getBitStrength()); -// values.put(Keys.CAN_SIGN, PGPHelper.isSigningKey(key)); -// values.put(Keys.CAN_ENCRYPT, PGPHelper.isEncryptionKey(key)); -// values.put(Keys.IS_REVOKED, key.getPublicKey().isRevoked()); -// values.put(Keys.CREATION, PGPHelper.getCreationDate(key).getTime() / 1000); -// Date expiryDate = PGPHelper.getExpiryDate(key); -// if (expiryDate != null) { -// values.put(Keys.EXPIRY, expiryDate.getTime() / 1000); -// } -// values.put(Keys.KEY_RING_ID, keyRingId); -// values.put(Keys.KEY_DATA, key.getEncoded()); -// values.put(Keys.RANK, rank); -// -// long rowId = insertOrUpdateKey(values); -// -// if (rowId == -1) { -// throw new GeneralException("saving secret key " + key.getPublicKey().getKeyID() + " failed"); -// } -// -// Vector seenIds = new Vector(); -// int userIdRank = 0; -// for (String userId : new IterableIterator(key.getUserIDs())) { -// seenIds.add(saveUserId(rowId, userId, userIdRank)); -// ++userIdRank; -// } -// -// String seenIdsStr = ""; -// for (Integer id : seenIds) { -// if (seenIdsStr.length() > 0) { -// seenIdsStr += ","; -// } -// seenIdsStr += id; -// } -// mDb.delete(UserIds.TABLE_NAME, -// UserIds.KEY_ID + " = ? AND " + -// UserIds._ID + " NOT IN (" + seenIdsStr + ")", -// new String[] { "" + rowId }); -// -// return (int)rowId; -// } -// -// private int saveUserId(long keyId, String userId, int rank) throws GeneralException { -// ContentValues values = new ContentValues(); -// -// values.put(UserIds.KEY_ID, keyId); -// values.put(UserIds.USER_ID, userId); -// values.put(UserIds.RANK, rank); -// -// long rowId = insertOrUpdateUserId(values); -// -// if (rowId == -1) { -// throw new GeneralException("saving user id " + userId + " failed"); -// } -// -// return (int)rowId; -// } -// -// private long insertOrUpdateKeyRing(ContentValues values) { -// Cursor c = mDb.query(KeyRings.TABLE_NAME, new String[] { KeyRings._ID }, -// KeyRings.MASTER_KEY_ID + " = ? AND " + KeyRings.TYPE + " = ?", -// new String[] { -// values.getAsString(KeyRings.MASTER_KEY_ID), -// values.getAsString(KeyRings.TYPE), -// }, -// null, null, null); -// long rowId = -1; -// if (c != null && c.moveToFirst()) { -// rowId = c.getLong(0); -// mDb.update(KeyRings.TABLE_NAME, values, -// KeyRings._ID + " = ?", new String[] { "" + rowId }); -// mStatus = Id.return_value.updated; -// } else { -// rowId = mDb.insert(KeyRings.TABLE_NAME, KeyRings.WHO_ID, values); -// mStatus = Id.return_value.ok; -// } -// -// if (c != null) { -// c.close(); -// } -// -// return rowId; -// } -// -// private long insertOrUpdateKey(ContentValues values) { -// Cursor c = mDb.query(Keys.TABLE_NAME, new String[] { Keys._ID }, -// Keys.KEY_ID + " = ? AND " + Keys.TYPE + " = ?", -// new String[] { -// values.getAsString(Keys.KEY_ID), -// values.getAsString(Keys.TYPE), -// }, -// null, null, null); -// long rowId = -1; -// if (c != null && c.moveToFirst()) { -// rowId = c.getLong(0); -// mDb.update(Keys.TABLE_NAME, values, -// Keys._ID + " = ?", new String[] { "" + rowId }); -// } else { -// rowId = mDb.insert(Keys.TABLE_NAME, Keys.KEY_DATA, values); -// } -// -// if (c != null) { -// c.close(); -// } -// -// return rowId; -// } -// -// private long insertOrUpdateUserId(ContentValues values) { -// Cursor c = mDb.query(UserIds.TABLE_NAME, new String[] { UserIds._ID }, -// UserIds.KEY_ID + " = ? AND " + UserIds.USER_ID + " = ?", -// new String[] { -// values.getAsString(UserIds.KEY_ID), -// values.getAsString(UserIds.USER_ID), -// }, -// null, null, null); -// long rowId = -1; -// if (c != null && c.moveToFirst()) { -// rowId = c.getLong(0); -// mDb.update(UserIds.TABLE_NAME, values, -// UserIds._ID + " = ?", new String[] { "" + rowId }); -// } else { -// rowId = mDb.insert(UserIds.TABLE_NAME, UserIds.USER_ID, values); -// } -// -// if (c != null) { -// c.close(); -// } -// -// return rowId; -// } -// -// public Object getKeyRing(int keyRingId) { -// Cursor c = mDb.query(KeyRings.TABLE_NAME, -// new String[] { KeyRings.KEY_RING_DATA, KeyRings.TYPE }, -// KeyRings._ID + " = ?", -// new String[] { -// "" + keyRingId, -// }, -// null, null, null); -// byte[] data = null; -// Object keyRing = null; -// if (c != null && c.moveToFirst()) { -// data = c.getBlob(0); -// if (data != null) { -// try { -// if (c.getInt(1) == Id.database.type_public) { -// keyRing = new PGPPublicKeyRing(data); -// } else { -// keyRing = new PGPSecretKeyRing(data); -// } -// } catch (IOException e) { -// // can't load it, then -// } catch (PGPException e) { -// // can't load it, then -// } -// } -// } -// -// if (c != null) { -// c.close(); -// } -// -// return keyRing; -// } -// -// public byte[] getKeyRingDataFromKeyId(int type, long keyId) { -// Cursor c = mDb.query(Keys.TABLE_NAME + " INNER JOIN " + KeyRings.TABLE_NAME + " ON (" + -// KeyRings.TABLE_NAME + "." + KeyRings._ID + " = " + -// Keys.TABLE_NAME + "." + Keys.KEY_RING_ID + ")", -// new String[] { KeyRings.TABLE_NAME + "." + KeyRings.KEY_RING_DATA }, -// Keys.TABLE_NAME + "." + Keys.KEY_ID + " = ? AND " + -// KeyRings.TABLE_NAME + "." + KeyRings.TYPE + " = ?", -// new String[] { -// "" + keyId, -// "" + type, -// }, -// null, null, null); -// -// byte[] data = null; -// if (c != null && c.moveToFirst()) { -// data = c.getBlob(0); -// } -// -// if (c != null) { -// c.close(); -// } -// -// return data; -// } -// -// public byte[] getKeyDataFromKeyId(int type, long keyId) { -// Cursor c = mDb.query(Keys.TABLE_NAME, new String[] { Keys.KEY_DATA }, -// Keys.KEY_ID + " = ? AND " + Keys.TYPE + " = ?", -// new String[] { -// "" + keyId, -// "" + type, -// }, -// null, null, null); -// byte[] data = null; -// if (c != null && c.moveToFirst()) { -// data = c.getBlob(0); -// } -// -// if (c != null) { -// c.close(); -// } -// -// return data; -// } -// +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.thialfihar.android.apg.deprecated; + +import org.spongycastle.openpgp.PGPException; +import org.spongycastle.openpgp.PGPPublicKey; +import org.spongycastle.openpgp.PGPPublicKeyRing; +import org.spongycastle.openpgp.PGPSecretKey; +import org.spongycastle.openpgp.PGPSecretKeyRing; +import org.thialfihar.android.apg.Id; +import org.thialfihar.android.apg.helper.PGPHelper; +import org.thialfihar.android.apg.util.IterableIterator; + +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import org.thialfihar.android.apg.util.Log; + +import java.io.IOException; +import java.util.Date; +import java.util.HashMap; +import java.util.Vector; + +public class Database extends SQLiteOpenHelper { + public static class GeneralException extends Exception { + static final long serialVersionUID = 0xf812773343L; + + public GeneralException(String message) { + super(message); + } + } + + private static final String DATABASE_NAME = "apg"; + private static final int DATABASE_VERSION = 2; + + public static final String AUTHORITY = "org.thialfihar.android.apg.database"; + + public static HashMap sKeyRingsProjection; + public static HashMap sKeysProjection; + public static HashMap sUserIdsProjection; + + private SQLiteDatabase mDb = null; + private int mStatus = 0; + + static { + sKeyRingsProjection = new HashMap(); + sKeyRingsProjection.put(KeyRings._ID, KeyRings._ID); + sKeyRingsProjection.put(KeyRings.MASTER_KEY_ID, KeyRings.MASTER_KEY_ID); + sKeyRingsProjection.put(KeyRings.TYPE, KeyRings.TYPE); + sKeyRingsProjection.put(KeyRings.WHO_ID, KeyRings.WHO_ID); + sKeyRingsProjection.put(KeyRings.KEY_RING_DATA, KeyRings.KEY_RING_DATA); + + sKeysProjection = new HashMap(); + sKeysProjection.put(Keys._ID, Keys._ID); + sKeysProjection.put(Keys.KEY_ID, Keys.KEY_ID); + sKeysProjection.put(Keys.TYPE, Keys.TYPE); + sKeysProjection.put(Keys.IS_MASTER_KEY, Keys.IS_MASTER_KEY); + sKeysProjection.put(Keys.ALGORITHM, Keys.ALGORITHM); + sKeysProjection.put(Keys.KEY_SIZE, Keys.KEY_SIZE); + sKeysProjection.put(Keys.CAN_SIGN, Keys.CAN_SIGN); + sKeysProjection.put(Keys.CAN_ENCRYPT, Keys.CAN_ENCRYPT); + sKeysProjection.put(Keys.IS_REVOKED, Keys.IS_REVOKED); + sKeysProjection.put(Keys.CREATION, Keys.CREATION); + sKeysProjection.put(Keys.EXPIRY, Keys.EXPIRY); + sKeysProjection.put(Keys.KEY_DATA, Keys.KEY_DATA); + sKeysProjection.put(Keys.RANK, Keys.RANK); + + sUserIdsProjection = new HashMap(); + sUserIdsProjection.put(UserIds._ID, UserIds._ID); + sUserIdsProjection.put(UserIds.KEY_ID, UserIds.KEY_ID); + sUserIdsProjection.put(UserIds.USER_ID, UserIds.USER_ID); + sUserIdsProjection.put(UserIds.RANK, UserIds.RANK); + } + + public Database(Context context) { + super(context, DATABASE_NAME, null, DATABASE_VERSION); + // force upgrade to test things + //onUpgrade(getWritableDatabase(), 1, 2); + mDb = getWritableDatabase(); + } + + @Override + protected void finalize() throws Throwable { + mDb.close(); + super.finalize(); + } + + @Override + public void onCreate(SQLiteDatabase db) { + db.execSQL("CREATE TABLE " + KeyRings.TABLE_NAME + " (" + + KeyRings._ID + " " + KeyRings._ID_type + "," + + KeyRings.MASTER_KEY_ID + " " + KeyRings.MASTER_KEY_ID_type + ", " + + KeyRings.TYPE + " " + KeyRings.TYPE_type + ", " + + KeyRings.WHO_ID + " " + KeyRings.WHO_ID_type + ", " + + KeyRings.KEY_RING_DATA + " " + KeyRings.KEY_RING_DATA_type + ");"); + + db.execSQL("CREATE TABLE " + Keys.TABLE_NAME + " (" + + Keys._ID + " " + Keys._ID_type + "," + + Keys.KEY_ID + " " + Keys.KEY_ID_type + ", " + + Keys.TYPE + " " + Keys.TYPE_type + ", " + + Keys.IS_MASTER_KEY + " " + Keys.IS_MASTER_KEY_type + ", " + + Keys.ALGORITHM + " " + Keys.ALGORITHM_type + ", " + + Keys.KEY_SIZE + " " + Keys.KEY_SIZE_type + ", " + + Keys.CAN_SIGN + " " + Keys.CAN_SIGN_type + ", " + + Keys.CAN_ENCRYPT + " " + Keys.CAN_ENCRYPT_type + ", " + + Keys.IS_REVOKED + " " + Keys.IS_REVOKED_type + ", " + + Keys.CREATION + " " + Keys.CREATION_type + ", " + + Keys.EXPIRY + " " + Keys.EXPIRY_type + ", " + + Keys.KEY_RING_ID + " " + Keys.KEY_RING_ID_type + ", " + + Keys.KEY_DATA + " " + Keys.KEY_DATA_type + + Keys.RANK + " " + Keys.RANK_type + ");"); + + db.execSQL("CREATE TABLE " + UserIds.TABLE_NAME + " (" + + UserIds._ID + " " + UserIds._ID_type + "," + + UserIds.KEY_ID + " " + UserIds.KEY_ID_type + "," + + UserIds.USER_ID + " " + UserIds.USER_ID_type + "," + + UserIds.RANK + " " + UserIds.RANK_type + ");"); + + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + mDb = db; + for (int version = oldVersion; version < newVersion; ++version) { + switch (version) { + case 1: { // upgrade 1 to 2 + db.execSQL("DROP TABLE IF EXISTS " + KeyRings.TABLE_NAME + ";"); + db.execSQL("DROP TABLE IF EXISTS " + Keys.TABLE_NAME + ";"); + db.execSQL("DROP TABLE IF EXISTS " + UserIds.TABLE_NAME + ";"); + + db.execSQL("CREATE TABLE " + KeyRings.TABLE_NAME + " (" + + KeyRings._ID + " " + KeyRings._ID_type + "," + + KeyRings.MASTER_KEY_ID + " " + KeyRings.MASTER_KEY_ID_type + ", " + + KeyRings.TYPE + " " + KeyRings.TYPE_type + ", " + + KeyRings.WHO_ID + " " + KeyRings.WHO_ID_type + ", " + + KeyRings.KEY_RING_DATA + " " + KeyRings.KEY_RING_DATA_type + ");"); + + + db.execSQL("CREATE TABLE " + Keys.TABLE_NAME + " (" + + Keys._ID + " " + Keys._ID_type + "," + + Keys.KEY_ID + " " + Keys.KEY_ID_type + ", " + + Keys.TYPE + " " + Keys.TYPE_type + ", " + + Keys.IS_MASTER_KEY + " " + Keys.IS_MASTER_KEY_type + ", " + + Keys.ALGORITHM + " " + Keys.ALGORITHM_type + ", " + + Keys.KEY_SIZE + " " + Keys.KEY_SIZE_type + ", " + + Keys.CAN_SIGN + " " + Keys.CAN_SIGN_type + ", " + + Keys.CAN_ENCRYPT + " " + Keys.CAN_ENCRYPT_type + ", " + + Keys.IS_REVOKED + " " + Keys.IS_REVOKED_type + ", " + + Keys.CREATION + " " + Keys.CREATION_type + ", " + + Keys.EXPIRY + " " + Keys.EXPIRY_type + ", " + + Keys.KEY_RING_ID + " " + Keys.KEY_RING_ID_type + ", " + + Keys.KEY_DATA + " " + Keys.KEY_DATA_type + + Keys.RANK + " " + Keys.RANK_type + ");"); + + db.execSQL("CREATE TABLE " + UserIds.TABLE_NAME + " (" + + UserIds._ID + " " + UserIds._ID_type + "," + + UserIds.KEY_ID + " " + UserIds.KEY_ID_type + "," + + UserIds.USER_ID + " " + UserIds.USER_ID_type + "," + + UserIds.RANK + " " + UserIds.RANK_type + ");"); + + Cursor cursor = db.query("public_keys", new String[] { "c_key_data" }, + null, null, null, null, null); + if (cursor != null && cursor.moveToFirst()) { + do { + byte[] data = cursor.getBlob(0); + try { + PGPPublicKeyRing keyRing = new PGPPublicKeyRing(data); + saveKeyRing(keyRing); + } catch (IOException e) { + Log.e("apg.db.upgrade", "key import failed: " + e); + } catch (GeneralException e) { + Log.e("apg.db.upgrade", "key import failed: " + e); + } + } while (cursor.moveToNext()); + } + + if (cursor != null) { + cursor.close(); + } + + cursor = db.query("secret_keys", new String[]{ "c_key_data" }, + null, null, null, null, null); + if (cursor != null && cursor.moveToFirst()) { + do { + byte[] data = cursor.getBlob(0); + try { + PGPSecretKeyRing keyRing = new PGPSecretKeyRing(data); + saveKeyRing(keyRing); + } catch (IOException e) { + Log.e("apg.db.upgrade", "key import failed: " + e); + } catch (PGPException e) { + Log.e("apg.db.upgrade", "key import failed: " + e); + } catch (GeneralException e) { + Log.e("apg.db.upgrade", "key import failed: " + e); + } + } while (cursor.moveToNext()); + } + + if (cursor != null) { + cursor.close(); + } + + db.execSQL("DROP TABLE IF EXISTS public_keys;"); + db.execSQL("DROP TABLE IF EXISTS secret_keys;"); + + break; + } + + default: { + break; + } + } + } + mDb = null; + } + + public int saveKeyRing(PGPPublicKeyRing keyRing) throws IOException, GeneralException { + mDb.beginTransaction(); + ContentValues values = new ContentValues(); + PGPPublicKey masterKey = keyRing.getPublicKey(); + long masterKeyId = masterKey.getKeyID(); + + values.put(KeyRings.MASTER_KEY_ID, masterKeyId); + values.put(KeyRings.TYPE, Id.database.type_public); + values.put(KeyRings.KEY_RING_DATA, keyRing.getEncoded()); + + long rowId = insertOrUpdateKeyRing(values); + int returnValue = mStatus; + + if (rowId == -1) { + throw new GeneralException("saving public key ring " + masterKeyId + " failed"); + } + + Vector seenIds = new Vector(); + int rank = 0; + for (PGPPublicKey key : new IterableIterator(keyRing.getPublicKeys())) { + seenIds.add(saveKey(rowId, key, rank)); + ++rank; + } + + String seenIdsStr = ""; + for (Integer id : seenIds) { + if (seenIdsStr.length() > 0) { + seenIdsStr += ","; + } + seenIdsStr += id; + } + mDb.delete(Keys.TABLE_NAME, + Keys.KEY_RING_ID + " = ? AND " + + Keys._ID + " NOT IN (" + seenIdsStr + ")", + new String[] { "" + rowId }); + + mDb.setTransactionSuccessful(); + mDb.endTransaction(); + return returnValue; + } + + public int saveKeyRing(PGPSecretKeyRing keyRing) throws IOException, GeneralException { + mDb.beginTransaction(); + ContentValues values = new ContentValues(); + PGPSecretKey masterKey = keyRing.getSecretKey(); + long masterKeyId = masterKey.getKeyID(); + + values.put(KeyRings.MASTER_KEY_ID, masterKeyId); + values.put(KeyRings.TYPE, Id.database.type_secret); + values.put(KeyRings.KEY_RING_DATA, keyRing.getEncoded()); + + long rowId = insertOrUpdateKeyRing(values); + int returnValue = mStatus; + + if (rowId == -1) { + throw new GeneralException("saving secret key ring " + masterKeyId + " failed"); + } + + Vector seenIds = new Vector(); + int rank = 0; + for (PGPSecretKey key : new IterableIterator(keyRing.getSecretKeys())) { + seenIds.add(saveKey(rowId, key, rank)); + ++rank; + } + + String seenIdsStr = ""; + for (Integer id : seenIds) { + if (seenIdsStr.length() > 0) { + seenIdsStr += ","; + } + seenIdsStr += id; + } + mDb.delete(Keys.TABLE_NAME, + Keys.KEY_RING_ID + " = ? AND " + + Keys._ID + " NOT IN (" + seenIdsStr + ")", + new String[] { "" + rowId }); + + mDb.setTransactionSuccessful(); + mDb.endTransaction(); + return returnValue; + } + + private int saveKey(long keyRingId, PGPPublicKey key, int rank) + throws IOException, GeneralException { + ContentValues values = new ContentValues(); + + values.put(Keys.KEY_ID, key.getKeyID()); + values.put(Keys.TYPE, Id.database.type_public); + values.put(Keys.IS_MASTER_KEY, key.isMasterKey()); + values.put(Keys.ALGORITHM, key.getAlgorithm()); + values.put(Keys.KEY_SIZE, key.getBitStrength()); + values.put(Keys.CAN_SIGN, PGPHelper.isSigningKey(key)); + values.put(Keys.CAN_ENCRYPT, PGPHelper.isEncryptionKey(key)); + values.put(Keys.IS_REVOKED, key.isRevoked()); + values.put(Keys.CREATION, PGPHelper.getCreationDate(key).getTime() / 1000); + Date expiryDate = PGPHelper.getExpiryDate(key); + if (expiryDate != null) { + values.put(Keys.EXPIRY, expiryDate.getTime() / 1000); + } + values.put(Keys.KEY_RING_ID, keyRingId); + values.put(Keys.KEY_DATA, key.getEncoded()); + values.put(Keys.RANK, rank); + + long rowId = insertOrUpdateKey(values); + + if (rowId == -1) { + throw new GeneralException("saving public key " + key.getKeyID() + " failed"); + } + + Vector seenIds = new Vector(); + int userIdRank = 0; + for (String userId : new IterableIterator(key.getUserIDs())) { + seenIds.add(saveUserId(rowId, userId, userIdRank)); + ++userIdRank; + } + + String seenIdsStr = ""; + for (Integer id : seenIds) { + if (seenIdsStr.length() > 0) { + seenIdsStr += ","; + } + seenIdsStr += id; + } + mDb.delete(UserIds.TABLE_NAME, + UserIds.KEY_ID + " = ? AND " + + UserIds._ID + " NOT IN (" + seenIdsStr + ")", + new String[] { "" + rowId }); + + return (int)rowId; + } + + private int saveKey(long keyRingId, PGPSecretKey key, int rank) + throws IOException, GeneralException { + ContentValues values = new ContentValues(); + + values.put(Keys.KEY_ID, key.getPublicKey().getKeyID()); + values.put(Keys.TYPE, Id.database.type_secret); + values.put(Keys.IS_MASTER_KEY, key.isMasterKey()); + values.put(Keys.ALGORITHM, key.getPublicKey().getAlgorithm()); + values.put(Keys.KEY_SIZE, key.getPublicKey().getBitStrength()); + values.put(Keys.CAN_SIGN, PGPHelper.isSigningKey(key)); + values.put(Keys.CAN_ENCRYPT, PGPHelper.isEncryptionKey(key)); + values.put(Keys.IS_REVOKED, key.getPublicKey().isRevoked()); + values.put(Keys.CREATION, PGPHelper.getCreationDate(key).getTime() / 1000); + Date expiryDate = PGPHelper.getExpiryDate(key); + if (expiryDate != null) { + values.put(Keys.EXPIRY, expiryDate.getTime() / 1000); + } + values.put(Keys.KEY_RING_ID, keyRingId); + values.put(Keys.KEY_DATA, key.getEncoded()); + values.put(Keys.RANK, rank); + + long rowId = insertOrUpdateKey(values); + + if (rowId == -1) { + throw new GeneralException("saving secret key " + key.getPublicKey().getKeyID() + " failed"); + } + + Vector seenIds = new Vector(); + int userIdRank = 0; + for (String userId : new IterableIterator(key.getUserIDs())) { + seenIds.add(saveUserId(rowId, userId, userIdRank)); + ++userIdRank; + } + + String seenIdsStr = ""; + for (Integer id : seenIds) { + if (seenIdsStr.length() > 0) { + seenIdsStr += ","; + } + seenIdsStr += id; + } + mDb.delete(UserIds.TABLE_NAME, + UserIds.KEY_ID + " = ? AND " + + UserIds._ID + " NOT IN (" + seenIdsStr + ")", + new String[] { "" + rowId }); + + return (int)rowId; + } + + private int saveUserId(long keyId, String userId, int rank) throws GeneralException { + ContentValues values = new ContentValues(); + + values.put(UserIds.KEY_ID, keyId); + values.put(UserIds.USER_ID, userId); + values.put(UserIds.RANK, rank); + + long rowId = insertOrUpdateUserId(values); + + if (rowId == -1) { + throw new GeneralException("saving user id " + userId + " failed"); + } + + return (int)rowId; + } + + private long insertOrUpdateKeyRing(ContentValues values) { + Cursor c = mDb.query(KeyRings.TABLE_NAME, new String[] { KeyRings._ID }, + KeyRings.MASTER_KEY_ID + " = ? AND " + KeyRings.TYPE + " = ?", + new String[] { + values.getAsString(KeyRings.MASTER_KEY_ID), + values.getAsString(KeyRings.TYPE), + }, + null, null, null); + long rowId = -1; + if (c != null && c.moveToFirst()) { + rowId = c.getLong(0); + mDb.update(KeyRings.TABLE_NAME, values, + KeyRings._ID + " = ?", new String[] { "" + rowId }); + mStatus = Id.return_value.updated; + } else { + rowId = mDb.insert(KeyRings.TABLE_NAME, KeyRings.WHO_ID, values); + mStatus = Id.return_value.ok; + } + + if (c != null) { + c.close(); + } + + return rowId; + } + + private long insertOrUpdateKey(ContentValues values) { + Cursor c = mDb.query(Keys.TABLE_NAME, new String[] { Keys._ID }, + Keys.KEY_ID + " = ? AND " + Keys.TYPE + " = ?", + new String[] { + values.getAsString(Keys.KEY_ID), + values.getAsString(Keys.TYPE), + }, + null, null, null); + long rowId = -1; + if (c != null && c.moveToFirst()) { + rowId = c.getLong(0); + mDb.update(Keys.TABLE_NAME, values, + Keys._ID + " = ?", new String[] { "" + rowId }); + } else { + rowId = mDb.insert(Keys.TABLE_NAME, Keys.KEY_DATA, values); + } + + if (c != null) { + c.close(); + } + + return rowId; + } + + private long insertOrUpdateUserId(ContentValues values) { + Cursor c = mDb.query(UserIds.TABLE_NAME, new String[] { UserIds._ID }, + UserIds.KEY_ID + " = ? AND " + UserIds.USER_ID + " = ?", + new String[] { + values.getAsString(UserIds.KEY_ID), + values.getAsString(UserIds.USER_ID), + }, + null, null, null); + long rowId = -1; + if (c != null && c.moveToFirst()) { + rowId = c.getLong(0); + mDb.update(UserIds.TABLE_NAME, values, + UserIds._ID + " = ?", new String[] { "" + rowId }); + } else { + rowId = mDb.insert(UserIds.TABLE_NAME, UserIds.USER_ID, values); + } + + if (c != null) { + c.close(); + } + + return rowId; + } + + public Object getKeyRing(int keyRingId) { + Cursor c = mDb.query(KeyRings.TABLE_NAME, + new String[] { KeyRings.KEY_RING_DATA, KeyRings.TYPE }, + KeyRings._ID + " = ?", + new String[] { + "" + keyRingId, + }, + null, null, null); + byte[] data = null; + Object keyRing = null; + if (c != null && c.moveToFirst()) { + data = c.getBlob(0); + if (data != null) { + try { + if (c.getInt(1) == Id.database.type_public) { + keyRing = new PGPPublicKeyRing(data); + } else { + keyRing = new PGPSecretKeyRing(data); + } + } catch (IOException e) { + // can't load it, then + } catch (PGPException e) { + // can't load it, then + } + } + } + + if (c != null) { + c.close(); + } + + return keyRing; + } + + public byte[] getKeyRingDataFromKeyId(int type, long keyId) { + Cursor c = mDb.query(Keys.TABLE_NAME + " INNER JOIN " + KeyRings.TABLE_NAME + " ON (" + + KeyRings.TABLE_NAME + "." + KeyRings._ID + " = " + + Keys.TABLE_NAME + "." + Keys.KEY_RING_ID + ")", + new String[] { KeyRings.TABLE_NAME + "." + KeyRings.KEY_RING_DATA }, + Keys.TABLE_NAME + "." + Keys.KEY_ID + " = ? AND " + + KeyRings.TABLE_NAME + "." + KeyRings.TYPE + " = ?", + new String[] { + "" + keyId, + "" + type, + }, + null, null, null); + + byte[] data = null; + if (c != null && c.moveToFirst()) { + data = c.getBlob(0); + } + + if (c != null) { + c.close(); + } + + return data; + } + + public byte[] getKeyDataFromKeyId(int type, long keyId) { + Cursor c = mDb.query(Keys.TABLE_NAME, new String[] { Keys.KEY_DATA }, + Keys.KEY_ID + " = ? AND " + Keys.TYPE + " = ?", + new String[] { + "" + keyId, + "" + type, + }, + null, null, null); + byte[] data = null; + if (c != null && c.moveToFirst()) { + data = c.getBlob(0); + } + + if (c != null) { + c.close(); + } + + return data; + } + // public void deleteKeyRing(int keyRingId) { // mDb.beginTransaction(); // mDb.delete(KeyRings.TABLE_NAME, @@ -614,4 +614,4 @@ // public SQLiteDatabase db() { // return mDb; // } -//} +} diff --git a/org_apg/src/org/thialfihar/android/apg/helper/PGPHelper.java b/org_apg/src/org/thialfihar/android/apg/helper/PGPHelper.java index 65b782c96..960d71286 100644 --- a/org_apg/src/org/thialfihar/android/apg/helper/PGPHelper.java +++ b/org_apg/src/org/thialfihar/android/apg/helper/PGPHelper.java @@ -38,6 +38,7 @@ import org.spongycastle.openpgp.PGPSignatureSubpacketVector; import org.spongycastle.openpgp.PGPUtil; import org.thialfihar.android.apg.Constants; import org.thialfihar.android.apg.R; +import org.thialfihar.android.apg.provider.ProviderHelper; import org.thialfihar.android.apg.util.IterableIterator; import org.thialfihar.android.apg.util.Log; @@ -189,9 +190,8 @@ public class PGPHelper { return getExpiryDate(key.getPublicKey()); } - public static PGPPublicKey getEncryptPublicKey(long masterKeyId) { - // TODO: externalize getSecretKeyRing from PGPWrapper into a DatabaseHelper - PGPPublicKeyRing keyRing = PGPMain.getPublicKeyRing(masterKeyId); + public static PGPPublicKey getEncryptPublicKey(Context context, long masterKeyId) { + PGPPublicKeyRing keyRing = ProviderHelper.getPGPPublicKeyRing(context, masterKeyId); if (keyRing == null) { return null; } @@ -202,9 +202,8 @@ public class PGPHelper { return encryptKeys.get(0); } - public static PGPSecretKey getSigningKey(long masterKeyId) { - // TODO: externalize getSecretKeyRing from PGPWrapper into a DatabaseHelper - PGPSecretKeyRing keyRing = PGPMain.getSecretKeyRing(masterKeyId); + public static PGPSecretKey getSigningKey(Context context, long masterKeyId) { + PGPSecretKeyRing keyRing = ProviderHelper.getPGPSecretKeyRing(context, masterKeyId); if (keyRing == null) { return null; } @@ -385,10 +384,10 @@ public class PGPHelper { } public static String getPubkeyAsArmoredString(Context context, long keyId) { - PGPPublicKey key = PGPMain.getPublicKey(keyId); + PGPPublicKey key = ProviderHelper.getPGPPublicKey(context, keyId); // if it is no public key get it from your own keys... if (key == null) { - PGPSecretKey secretKey = PGPMain.getSecretKey(keyId); + PGPSecretKey secretKey = ProviderHelper.getPGPSecretKey(context, keyId); if (secretKey == null) { Log.e(Constants.TAG, "Key could not be found!"); return null; @@ -415,10 +414,11 @@ public class PGPHelper { return armouredKey; } - public static String getFingerPrint(long keyId) { - PGPPublicKey key = PGPMain.getPublicKey(keyId); + public static String getFingerPrint(Context context, long keyId) { + PGPPublicKey key = ProviderHelper.getPGPPublicKey(context, keyId); + // if it is no public key get it from your own keys... if (key == null) { - PGPSecretKey secretKey = PGPMain.getSecretKey(keyId); + PGPSecretKey secretKey = ProviderHelper.getPGPSecretKey(context, keyId); if (secretKey == null) { Log.e(Constants.TAG, "Key could not be found!"); return null; diff --git a/org_apg/src/org/thialfihar/android/apg/helper/PGPMain.java b/org_apg/src/org/thialfihar/android/apg/helper/PGPMain.java index 8a7ffc538..dc4323090 100644 --- a/org_apg/src/org/thialfihar/android/apg/helper/PGPMain.java +++ b/org_apg/src/org/thialfihar/android/apg/helper/PGPMain.java @@ -72,6 +72,7 @@ import org.spongycastle.openpgp.operator.jcajce.JcePBESecretKeyEncryptorBuilder; import org.spongycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder; import org.spongycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder; import org.spongycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator; +import org.thialfihar.android.apg.provider.ProviderHelper; import org.thialfihar.android.apg.service.ApgService; import org.thialfihar.android.apg.util.HkpKeyServer; import org.thialfihar.android.apg.util.InputData; @@ -153,8 +154,6 @@ public class PGPMain { // public static final Uri CONTENT_URI_PUBLIC_KEY_RING_BY_EMAILS = Uri.parse("content://" // + AUTHORITY + "/key_rings/public/emails/"); - private static String VERSION = null; - private static final int[] PREFERRED_SYMMETRIC_ALGORITHMS = new int[] { SymmetricKeyAlgorithmTags.AES_256, SymmetricKeyAlgorithmTags.AES_192, SymmetricKeyAlgorithmTags.AES_128, SymmetricKeyAlgorithmTags.CAST5, @@ -521,8 +520,6 @@ public class PGPMain { } } catch (IOException e) { status = Id.return_value.error; - } catch (ApgGeneralException.GeneralException e) { - status = Id.return_value.error; } return status; @@ -641,18 +638,20 @@ public class PGPMain { int numKeys = 0; for (int i = 0; i < keyRingIds.size(); ++i) { updateProgress(progress, i * 100 / keyRingIds.size(), 100); - Object obj = mDatabase.getKeyRing(keyRingIds.get(i)); - PGPPublicKeyRing publicKeyRing; - PGPSecretKeyRing secretKeyRing; - - if (obj instanceof PGPSecretKeyRing) { - secretKeyRing = (PGPSecretKeyRing) obj; - secretKeyRing.encode(out); - } else if (obj instanceof PGPPublicKeyRing) { - publicKeyRing = (PGPPublicKeyRing) obj; + + // try to get it as a PGPPublicKeyRing, if that fails try to get it as a SecretKeyRing + PGPPublicKeyRing publicKeyRing = ProviderHelper.getPGPPublicKeyRing(context, + keyRingIds.get(i)); + if (publicKeyRing != null) { publicKeyRing.encode(out); } else { - continue; + PGPSecretKeyRing secretKeyRing = ProviderHelper.getPGPSecretKeyRing(context, + keyRingIds.get(i)); + if (secretKeyRing != null) { + secretKeyRing.encode(out); + } else { + continue; + } } ++numKeys; } @@ -664,90 +663,69 @@ public class PGPMain { return returnData; } - public static void deleteKey(int keyRingId) { - mDatabase.deleteKeyRing(keyRingId); - } - - public static PGPKeyRing getKeyRing(int keyRingId) { - return (PGPKeyRing) mDatabase.getKeyRing(keyRingId); - } - - public static PGPSecretKeyRing getSecretKeyRing(long keyId) { - byte[] data = mDatabase.getKeyRingDataFromKeyId(Id.database.type_secret, keyId); - if (data == null) { - return null; - } - return PGPConversionHelper.BytesToPGPSecretKeyRing(data); - } - - public static PGPPublicKeyRing getPublicKeyRing(long keyId) { - byte[] data = mDatabase.getKeyRingDataFromKeyId(Id.database.type_public, keyId); - if (data == null) { - return null; - } - return PGPConversionHelper.BytesToPGPPublicKeyRing(data); - } - - public static PGPSecretKey getSecretKey(long keyId) { - PGPSecretKeyRing keyRing = getSecretKeyRing(keyId); - if (keyRing == null) { - return null; - } - return keyRing.getSecretKey(keyId); - } - - public static PGPPublicKey getPublicKey(long keyId) { - PGPPublicKeyRing keyRing = getPublicKeyRing(keyId); - if (keyRing == null) { - return null; - } - - return keyRing.getPublicKey(keyId); - } - - public static Vector getKeyRingIds(int type) { - SQLiteDatabase db = mDatabase.db(); - Vector keyIds = new Vector(); - Cursor c = db.query(KeyRings.TABLE_NAME, new String[] { KeyRings._ID }, KeyRings.TYPE - + " = ?", new String[] { "" + type }, null, null, null); - if (c != null && c.moveToFirst()) { - do { - keyIds.add(c.getInt(0)); - } while (c.moveToNext()); - } - - if (c != null) { - c.close(); - } - - return keyIds; - } + // public static PGPKeyRing getKeyRing(int keyRingId) { + // return (PGPKeyRing) mDatabase.getKeyRing(keyRingId); + // } - public static String getMainUserId(long keyId, int type) { - SQLiteDatabase db = mDatabase.db(); - Cursor c = db.query(Keys.TABLE_NAME + " INNER JOIN " + KeyRings.TABLE_NAME + " ON (" - + KeyRings.TABLE_NAME + "." + KeyRings._ID + " = " + Keys.TABLE_NAME + "." - + Keys.KEY_RING_ID + ") " + " INNER JOIN " + Keys.TABLE_NAME + " AS masterKey ON (" - + KeyRings.TABLE_NAME + "." + KeyRings._ID + " = " + "masterKey." - + Keys.KEY_RING_ID + " AND " + "masterKey." + Keys.IS_MASTER_KEY + " = '1') " - + " INNER JOIN " + UserIds.TABLE_NAME + " ON (" + UserIds.TABLE_NAME + "." - + UserIds.KEY_ID + " = " + "masterKey." + Keys._ID + " AND " + UserIds.TABLE_NAME - + "." + UserIds.RANK + " = '0')", new String[] { UserIds.USER_ID }, Keys.TABLE_NAME - + "." + Keys.KEY_ID + " = ? AND " + KeyRings.TABLE_NAME + "." + KeyRings.TYPE - + " = ?", new String[] { "" + keyId, "" + type, }, null, null, null); - String userId = ""; - if (c != null && c.moveToFirst()) { - do { - userId = c.getString(0); - } while (c.moveToNext()); - } + // public static PGPSecretKeyRing getSecretKeyRing(long keyId) { + // byte[] data = mDatabase.getKeyRingDataFromKeyId(Id.database.type_secret, keyId); + // if (data == null) { + // return null; + // } + // return PGPConversionHelper.BytesToPGPSecretKeyRing(data); + // } + // + // public static PGPPublicKeyRing getPublicKeyRing(long keyId) { + // byte[] data = mDatabase.getKeyRingDataFromKeyId(Id.database.type_public, keyId); + // if (data == null) { + // return null; + // } + // return PGPConversionHelper.BytesToPGPPublicKeyRing(data); + // } - if (c != null) { - c.close(); - } + // public static Vector getKeyRingIds(int type) { + // SQLiteDatabase db = mDatabase.db(); + // Vector keyIds = new Vector(); + // Cursor c = db.query(KeyRings.TABLE_NAME, new String[] { KeyRings._ID }, KeyRings.TYPE + // + " = ?", new String[] { "" + type }, null, null, null); + // if (c != null && c.moveToFirst()) { + // do { + // keyIds.add(c.getInt(0)); + // } while (c.moveToNext()); + // } + // + // if (c != null) { + // c.close(); + // } + // + // return keyIds; + // } - return userId; - } + // public static String getMainUserId(long keyId, int type) { + // SQLiteDatabase db = mDatabase.db(); + // Cursor c = db.query(Keys.TABLE_NAME + " INNER JOIN " + KeyRings.TABLE_NAME + " ON (" + // + KeyRings.TABLE_NAME + "." + KeyRings._ID + " = " + Keys.TABLE_NAME + "." + // + Keys.KEY_RING_ID + ") " + " INNER JOIN " + Keys.TABLE_NAME + " AS masterKey ON (" + // + KeyRings.TABLE_NAME + "." + KeyRings._ID + " = " + "masterKey." + // + Keys.KEY_RING_ID + " AND " + "masterKey." + Keys.IS_MASTER_KEY + " = '1') " + // + " INNER JOIN " + UserIds.TABLE_NAME + " ON (" + UserIds.TABLE_NAME + "." + // + UserIds.KEY_ID + " = " + "masterKey." + Keys._ID + " AND " + UserIds.TABLE_NAME + // + "." + UserIds.RANK + " = '0')", new String[] { UserIds.USER_ID }, Keys.TABLE_NAME + // + "." + Keys.KEY_ID + " = ? AND " + KeyRings.TABLE_NAME + "." + KeyRings.TYPE + // + " = ?", new String[] { "" + keyId, "" + type, }, null, null, null); + // String userId = ""; + // if (c != null && c.moveToFirst()) { + // do { + // userId = c.getString(0); + // } while (c.moveToNext()); + // } + // + // if (c != null) { + // c.close(); + // } + // + // return userId; + // } public static void encrypt(Context context, InputData data, OutputStream outStream, boolean armored, long encryptionKeyIds[], long signatureKeyId, @@ -780,8 +758,8 @@ public class PGPMain { } if (signatureKeyId != Id.key.none) { - signingKeyRing = getSecretKeyRing(signatureKeyId); - signingKey = PGPHelper.getSigningKey(signatureKeyId); + signingKeyRing = ProviderHelper.getPGPSecretKeyRing(context, signatureKeyId); + signingKey = PGPHelper.getSigningKey(context, signatureKeyId); if (signingKey == null) { throw new ApgGeneralException(context.getString(R.string.error_signatureFailed)); } @@ -818,7 +796,7 @@ public class PGPMain { cPk.addMethod(symmetricEncryptionGenerator); } for (int i = 0; i < encryptionKeyIds.length; ++i) { - PGPPublicKey key = PGPHelper.getEncryptPublicKey(encryptionKeyIds[i]); + PGPPublicKey key = PGPHelper.getEncryptPublicKey(context, encryptionKeyIds[i]); if (key != null) { JcePublicKeyKeyEncryptionMethodGenerator pubKeyEncryptionGenerator = new JcePublicKeyKeyEncryptionMethodGenerator( @@ -933,8 +911,8 @@ public class PGPMain { throw new ApgGeneralException(context.getString(R.string.error_noSignatureKey)); } - signingKeyRing = getSecretKeyRing(signatureKeyId); - signingKey = PGPHelper.getSigningKey(signatureKeyId); + signingKeyRing = ProviderHelper.getPGPSecretKeyRing(context, signatureKeyId); + signingKey = PGPHelper.getSigningKey(context, signatureKeyId); if (signingKey == null) { armorOut.close(); throw new ApgGeneralException(context.getString(R.string.error_signatureFailed)); @@ -1049,8 +1027,8 @@ public class PGPMain { throw new ApgGeneralException(context.getString(R.string.error_noSignatureKey)); } - signingKeyRing = getSecretKeyRing(signatureKeyId); - signingKey = PGPHelper.getSigningKey(signatureKeyId); + signingKeyRing = ProviderHelper.getPGPSecretKeyRing(context, signatureKeyId); + signingKey = PGPHelper.getSigningKey(context, signatureKeyId); if (signingKey == null) { throw new ApgGeneralException(context.getString(R.string.error_signatureFailed)); } @@ -1149,9 +1127,9 @@ public class PGPMain { if (passphrase == null || passphrase.length() <= 0) { throw new ApgGeneralException("Unable to obtain passphrase"); } else { - PGPPublicKeyRing pubring = PGPMain.getPublicKeyRing(pubKeyId); + PGPPublicKeyRing pubring = ProviderHelper.getPGPPublicKeyRing(context, pubKeyId); - PGPSecretKey signingKey = PGPHelper.getSigningKey(masterKeyId); + PGPSecretKey signingKey = PGPHelper.getSigningKey(context, masterKeyId); if (signingKey == null) { throw new ApgGeneralException(context.getString(R.string.error_signatureFailed)); } @@ -1215,7 +1193,7 @@ public class PGPMain { if (obj instanceof PGPPublicKeyEncryptedData) { gotAsymmetricEncryption = true; PGPPublicKeyEncryptedData pbe = (PGPPublicKeyEncryptedData) obj; - secretKey = getSecretKey(pbe.getKeyID()); + secretKey = ProviderHelper.getPGPSecretKey(context, pbe.getKeyID()); if (secretKey != null) { break; } @@ -1336,7 +1314,7 @@ public class PGPMain { Object obj = it.next(); if (obj instanceof PGPPublicKeyEncryptedData) { PGPPublicKeyEncryptedData encData = (PGPPublicKeyEncryptedData) obj; - secretKey = getSecretKey(encData.getKeyID()); + secretKey = ProviderHelper.getPGPSecretKey(context, encData.getKeyID()); if (secretKey != null) { pbe = encData; break; @@ -1397,7 +1375,7 @@ public class PGPMain { PGPOnePassSignatureList sigList = (PGPOnePassSignatureList) dataChunk; for (int i = 0; i < sigList.size(); ++i) { signature = sigList.get(i); - signatureKey = getPublicKey(signature.getKeyID()); + signatureKey = ProviderHelper.getPGPPublicKey(context, signature.getKeyID()); if (signatureKeyId == 0) { signatureKeyId = signature.getKeyID(); } @@ -1407,7 +1385,8 @@ public class PGPMain { signatureIndex = i; signatureKeyId = signature.getKeyID(); String userId = null; - PGPPublicKeyRing sigKeyRing = getPublicKeyRing(signatureKeyId); + PGPPublicKeyRing sigKeyRing = ProviderHelper.getPGPPublicKeyRing(context, + signatureKeyId); if (sigKeyRing != null) { userId = PGPHelper.getMainUserId(PGPHelper.getMasterKey(sigKeyRing)); } @@ -1552,7 +1531,7 @@ public class PGPMain { PGPPublicKey signatureKey = null; for (int i = 0; i < sigList.size(); ++i) { signature = sigList.get(i); - signatureKey = getPublicKey(signature.getKeyID()); + signatureKey = ProviderHelper.getPGPPublicKey(context, signature.getKeyID()); if (signatureKeyId == 0) { signatureKeyId = signature.getKeyID(); } @@ -1572,7 +1551,8 @@ public class PGPMain { } else { signatureKeyId = signature.getKeyID(); String userId = null; - PGPPublicKeyRing sigKeyRing = getPublicKeyRing(signatureKeyId); + PGPPublicKeyRing sigKeyRing = ProviderHelper.getPGPPublicKeyRing(context, + signatureKeyId); if (sigKeyRing != null) { userId = PGPHelper.getMainUserId(PGPHelper.getMasterKey(sigKeyRing)); } @@ -1799,15 +1779,13 @@ public class PGPMain { } public static String getVersion(Context context) { - if (VERSION != null) { - return VERSION; - } + String version = null; try { PackageInfo pi = context.getPackageManager().getPackageInfo(Constants.PACKAGE_NAME, 0); - VERSION = pi.versionName; - return VERSION; + version = pi.versionName; + return version; } catch (NameNotFoundException e) { - // impossible! + Log.e(Constants.TAG, "Version could not be retrieved!", e); return "0.0.0"; } } diff --git a/org_apg/src/org/thialfihar/android/apg/provider/ApgContract.java b/org_apg/src/org/thialfihar/android/apg/provider/ApgContract.java index 10f9fa05e..66c611d4b 100644 --- a/org_apg/src/org/thialfihar/android/apg/provider/ApgContract.java +++ b/org_apg/src/org/thialfihar/android/apg/provider/ApgContract.java @@ -17,6 +17,8 @@ package org.thialfihar.android.apg.provider; +import org.thialfihar.android.apg.Constants; + import android.net.Uri; import android.provider.BaseColumns; @@ -32,10 +34,12 @@ import android.provider.BaseColumns; */ public class ApgContract { + // APG1: all rows had a "c_" prefix + interface KeyRingsColumns { - String MASTER_KEY_ID = "master_key_id"; // TODO: clarify + String MASTER_KEY_ROW_ID = "master_key_id"; // TODO: clarify String TYPE = "type"; // see KeyTypes - String WHO_ID = "who_id"; + String WHO_ID = "who_id"; // TODO: is this used? String KEY_RING_DATA = "key_ring_data"; // blob } @@ -51,8 +55,8 @@ public class ApgContract { String CREATION = "creation"; String EXPIRY = "expiry"; String KEY_RING_ROW_ID = "key_ring_id"; // foreign key to key_rings._ID - String KEY_DATA = "key_data"; - String RANK = "key_data"; // blob + String KEY_DATA = "key_data"; // blob + String RANK = "rank"; // APG1: this was "key_data", TODO: Bug? Is this even used? } interface UserIdsColumns { @@ -66,8 +70,8 @@ public class ApgContract { public static final int SECRET = 1; } - public static final String CONTENT_AUTHORITY = "org.thialfihar.android.apg.provider"; - // public static final String CONTENT_AUTHORITY = Constants.PACKAGE_NAME; + // APG1: "org.thialfihar.android.apg.provider"; + public static final String CONTENT_AUTHORITY = Constants.PACKAGE_NAME; private static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); diff --git a/org_apg/src/org/thialfihar/android/apg/provider/ApgDatabase.java b/org_apg/src/org/thialfihar/android/apg/provider/ApgDatabase.java index fdee2f101..b70cfa7b6 100644 --- a/org_apg/src/org/thialfihar/android/apg/provider/ApgDatabase.java +++ b/org_apg/src/org/thialfihar/android/apg/provider/ApgDatabase.java @@ -30,18 +30,20 @@ import android.provider.BaseColumns; import org.thialfihar.android.apg.util.Log; public class ApgDatabase extends SQLiteOpenHelper { + // APG1: "apg" private static final String DATABASE_NAME = "apg.db"; - // Last APG 1 db version was 2 + // APG1: 2 private static final int DATABASE_VERSION = 3; public interface Tables { String KEY_RINGS = "key_rings"; String KEYS = "keys"; - String USER_IDS = "user_ids"; + String USERS = "user_ids"; } + // APG1: REFERENCES where not implemented private static final String CREATE_KEY_RINGS = "CREATE TABLE IF NOT EXISTS " + Tables.KEY_RINGS - + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY, " + KeyRingsColumns.MASTER_KEY_ID + + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY, " + KeyRingsColumns.MASTER_KEY_ROW_ID + " INT64, " + KeyRingsColumns.TYPE + " INTEGER, " + KeyRingsColumns.WHO_ID + " INTEGER, " + KeyRingsColumns.KEY_RING_DATA + " BLOB)"; @@ -55,7 +57,7 @@ public class ApgDatabase extends SQLiteOpenHelper { + " INTEGER REFERENCES " + Tables.KEY_RINGS + " ON DELETE CASCADE, " + KeysColumns.KEY_DATA + " BLOB," + KeysColumns.RANK + " INTEGER)"; - private static final String CREATE_USER_IDS = "CREATE TABLE IF NOT EXISTS " + Tables.USER_IDS + private static final String CREATE_USER_IDS = "CREATE TABLE IF NOT EXISTS " + Tables.USERS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY, " + UserIdsColumns.KEY_ROW_ID + " INTEGER REFERENCES " + Tables.KEYS + " ON DELETE CASCADE, " + UserIdsColumns.USER_ID + " TEXT, " + UserIdsColumns.RANK + " INTEGER)"; @@ -129,9 +131,6 @@ public class ApgDatabase extends SQLiteOpenHelper { Log.w(Constants.TAG, "Upgrading database to version " + version); switch (version) { - case 1: - - break; default: break; diff --git a/org_apg/src/org/thialfihar/android/apg/provider/ApgProvider.java b/org_apg/src/org/thialfihar/android/apg/provider/ApgProvider.java index e25228434..06d07fe5e 100644 --- a/org_apg/src/org/thialfihar/android/apg/provider/ApgProvider.java +++ b/org_apg/src/org/thialfihar/android/apg/provider/ApgProvider.java @@ -54,8 +54,8 @@ public class ApgProvider extends ContentProvider { private static final UriMatcher sUriMatcher = buildUriMatcher(); private static final int PUBLIC_KEY_RING = 101; - private static final int PUBLIC_KEY_RING_ID = 102; - private static final int PUBLIC_KEY_RING_BY_KEY_ID = 103; + private static final int PUBLIC_KEY_RING_ROW_ID = 102; + private static final int PUBLIC_KEY_RING_BY_KEY_ID = 103; // TODO: Is this row id??? private static final int PUBLIC_KEY_RING_BY_EMAILS = 104; private static final int PUBLIC_KEY_RING_KEY = 111; private static final int PUBLIC_KEY_RING_KEY_RANK = 112; @@ -63,7 +63,7 @@ public class ApgProvider extends ContentProvider { private static final int PUBLIC_KEY_RING_USER_ID_RANK = 122; private static final int SECRET_KEY_RING = 201; - private static final int SECRET_KEY_RING_ID = 202; + private static final int SECRET_KEY_RING_ROW_ID = 202; private static final int SECRET_KEY_RING_BY_KEY_ID = 203; private static final int SECRET_KEY_RING_BY_EMAILS = 204; private static final int SECRET_KEY_RING_KEY = 211; @@ -95,7 +95,7 @@ public class ApgProvider extends ContentProvider { PUBLIC_KEY_RING); matcher.addURI(authority, ApgContract.BASE_KEY_RINGS + "/" + ApgContract.PATH_PUBLIC + "/*", - PUBLIC_KEY_RING_ID); + PUBLIC_KEY_RING_ROW_ID); matcher.addURI(authority, ApgContract.BASE_KEY_RINGS + "/" + ApgContract.PATH_PUBLIC + "/" + ApgContract.PATH_BY_KEY_ID + "/*", PUBLIC_KEY_RING_BY_KEY_ID); matcher.addURI(authority, ApgContract.BASE_KEY_RINGS + "/" + ApgContract.PATH_PUBLIC + "/" @@ -143,7 +143,7 @@ public class ApgProvider extends ContentProvider { SECRET_KEY_RING); matcher.addURI(authority, ApgContract.BASE_KEY_RINGS + "/" + ApgContract.PATH_SECRET + "/*", - SECRET_KEY_RING_ID); + SECRET_KEY_RING_ROW_ID); matcher.addURI(authority, ApgContract.BASE_KEY_RINGS + "/" + ApgContract.PATH_SECRET + "/" + ApgContract.PATH_BY_KEY_ID + "/*", SECRET_KEY_RING_BY_KEY_ID); matcher.addURI(authority, ApgContract.BASE_KEY_RINGS + "/" + ApgContract.PATH_SECRET + "/" @@ -208,7 +208,7 @@ public class ApgProvider extends ContentProvider { case PUBLIC_KEY_RING_BY_EMAILS: return PublicKeyRings.CONTENT_TYPE; - case PUBLIC_KEY_RING_ID: + case PUBLIC_KEY_RING_ROW_ID: case PUBLIC_KEY_RING_BY_KEY_ID: return PublicKeyRings.CONTENT_ITEM_TYPE; @@ -228,7 +228,7 @@ public class ApgProvider extends ContentProvider { case SECRET_KEY_RING_BY_EMAILS: return SecretKeyRings.CONTENT_TYPE; - case SECRET_KEY_RING_ID: + case SECRET_KEY_RING_ROW_ID: case SECRET_KEY_RING_BY_KEY_ID: return SecretKeyRings.CONTENT_ITEM_TYPE; @@ -259,7 +259,7 @@ public class ApgProvider extends ContentProvider { int type; switch (match) { case PUBLIC_KEY_RING: - case PUBLIC_KEY_RING_ID: + case PUBLIC_KEY_RING_ROW_ID: case PUBLIC_KEY_RING_BY_KEY_ID: case PUBLIC_KEY_RING_BY_EMAILS: case PUBLIC_KEY_RING_KEY: @@ -270,7 +270,7 @@ public class ApgProvider extends ContentProvider { break; case SECRET_KEY_RING: - case SECRET_KEY_RING_ID: + case SECRET_KEY_RING_ROW_ID: case SECRET_KEY_RING_BY_KEY_ID: case SECRET_KEY_RING_BY_EMAILS: case SECRET_KEY_RING_KEY: @@ -304,9 +304,10 @@ public class ApgProvider extends ContentProvider { qb.appendWhere(Tables.KEY_RINGS + "." + KeyRingsColumns.TYPE + " = " + getKeyType(match)); switch (match) { - case PUBLIC_KEY_RING_ID: - case SECRET_KEY_RING_ID: - qb.appendWhere(" AND " + Tables.KEY_RINGS + "." + KeyRingsColumns.MASTER_KEY_ID + " = "); + case PUBLIC_KEY_RING_ROW_ID: + case SECRET_KEY_RING_ROW_ID: + qb.appendWhere(" AND " + Tables.KEY_RINGS + "." + KeyRingsColumns.MASTER_KEY_ROW_ID + + " = "); qb.appendWhereEscapeString(uri.getPathSegments().get(2)); // break omitted intentionally @@ -315,20 +316,19 @@ public class ApgProvider extends ContentProvider { case SECRET_KEY_RING: qb.setTables(Tables.KEY_RINGS + " INNER JOIN " + Tables.KEYS + " ON " + "(" + Tables.KEY_RINGS + "." + BaseColumns._ID + " = " + Tables.KEYS + "." - + KeysColumns.KEY_RING_ID + " AND " + Tables.KEYS + "." - + KeysColumns.IS_MASTER_KEY + " = '1'" + ") " + " INNER JOIN " - + Tables.USER_IDS + " ON " + "(" + Tables.KEYS + "." + BaseColumns._ID + " = " - + Tables.USER_IDS + "." + UserIdsColumns.KEY_ID + " AND " + Tables.USER_IDS - + "." + UserIdsColumns.RANK + " = '0') "); + + KeysColumns.KEY_RING_ROW_ID + " AND " + Tables.KEYS + "." + + KeysColumns.IS_MASTER_KEY + " = '1'" + ") " + " INNER JOIN " + Tables.USERS + + " ON " + "(" + Tables.KEYS + "." + BaseColumns._ID + " = " + Tables.USERS + + "." + UserIdsColumns.KEY_ROW_ID + " AND " + Tables.USERS + "." + + UserIdsColumns.RANK + " = '0') "); projectionMap.put(BaseColumns._ID, Tables.KEY_RINGS + "." + BaseColumns._ID); - projectionMap.put(KeyRingsColumns.MASTER_KEY_ID, Tables.KEY_RINGS + "." - + KeyRingsColumns.MASTER_KEY_ID); - projectionMap.put(UserIdsColumns.USER_ID, Tables.USER_IDS + "." - + UserIdsColumns.USER_ID); + projectionMap.put(KeyRingsColumns.MASTER_KEY_ROW_ID, Tables.KEY_RINGS + "." + + KeyRingsColumns.MASTER_KEY_ROW_ID); + projectionMap.put(UserIdsColumns.USER_ID, Tables.USERS + "." + UserIdsColumns.USER_ID); if (TextUtils.isEmpty(sortOrder)) { - sortOrder = Tables.USER_IDS + "." + UserIdsColumns.USER_ID + " ASC"; + sortOrder = Tables.USERS + "." + UserIdsColumns.USER_ID + " ASC"; } break; @@ -337,19 +337,18 @@ public class ApgProvider extends ContentProvider { case PUBLIC_KEY_RING_BY_KEY_ID: qb.setTables(Tables.KEYS + " AS tmp INNER JOIN " + Tables.KEY_RINGS + " ON (" + Tables.KEY_RINGS + "." + BaseColumns._ID + " = " + "tmp." - + KeysColumns.KEY_RING_ID + ")" + " INNER JOIN " + Tables.KEYS + " ON " + "(" - + Tables.KEY_RINGS + "." + BaseColumns._ID + " = " + Tables.KEYS + "." - + KeysColumns.KEY_RING_ID + " AND " + Tables.KEYS + "." - + KeysColumns.IS_MASTER_KEY + " = '1'" + ") " + " INNER JOIN " - + Tables.USER_IDS + " ON " + "(" + Tables.KEYS + "." + BaseColumns._ID + " = " - + Tables.USER_IDS + "." + UserIdsColumns.KEY_ID + " AND " + Tables.USER_IDS - + "." + UserIdsColumns.RANK + " = '0') "); + + KeysColumns.KEY_RING_ROW_ID + ")" + " INNER JOIN " + Tables.KEYS + " ON " + + "(" + Tables.KEY_RINGS + "." + BaseColumns._ID + " = " + Tables.KEYS + "." + + KeysColumns.KEY_RING_ROW_ID + " AND " + Tables.KEYS + "." + + KeysColumns.IS_MASTER_KEY + " = '1'" + ") " + " INNER JOIN " + Tables.USERS + + " ON " + "(" + Tables.KEYS + "." + BaseColumns._ID + " = " + Tables.USERS + + "." + UserIdsColumns.KEY_ROW_ID + " AND " + Tables.USERS + "." + + UserIdsColumns.RANK + " = '0') "); projectionMap.put(BaseColumns._ID, Tables.KEY_RINGS + "." + BaseColumns._ID); - projectionMap.put(KeyRingsColumns.MASTER_KEY_ID, Tables.KEY_RINGS + "." - + KeyRingsColumns.MASTER_KEY_ID); - projectionMap.put(UserIdsColumns.USER_ID, Tables.USER_IDS + "." - + UserIdsColumns.USER_ID); + projectionMap.put(KeyRingsColumns.MASTER_KEY_ROW_ID, Tables.KEY_RINGS + "." + + KeyRingsColumns.MASTER_KEY_ROW_ID); + projectionMap.put(UserIdsColumns.USER_ID, Tables.USERS + "." + UserIdsColumns.USER_ID); qb.appendWhere(" AND tmp." + KeysColumns.KEY_ID + " = "); qb.appendWhereEscapeString(uri.getPathSegments().get(3)); @@ -360,17 +359,16 @@ public class ApgProvider extends ContentProvider { case PUBLIC_KEY_RING_BY_EMAILS: qb.setTables(Tables.KEY_RINGS + " INNER JOIN " + Tables.KEYS + " ON " + "(" + Tables.KEY_RINGS + "." + BaseColumns._ID + " = " + Tables.KEYS + "." - + KeysColumns.KEY_RING_ID + " AND " + Tables.KEYS + "." - + KeysColumns.IS_MASTER_KEY + " = '1'" + ") " + " INNER JOIN " - + Tables.USER_IDS + " ON " + "(" + Tables.KEYS + "." + BaseColumns._ID + " = " - + Tables.USER_IDS + "." + UserIdsColumns.KEY_ID + " AND " + Tables.USER_IDS - + "." + UserIdsColumns.RANK + " = '0') "); + + KeysColumns.KEY_RING_ROW_ID + " AND " + Tables.KEYS + "." + + KeysColumns.IS_MASTER_KEY + " = '1'" + ") " + " INNER JOIN " + Tables.USERS + + " ON " + "(" + Tables.KEYS + "." + BaseColumns._ID + " = " + Tables.USERS + + "." + UserIdsColumns.KEY_ROW_ID + " AND " + Tables.USERS + "." + + UserIdsColumns.RANK + " = '0') "); projectionMap.put(BaseColumns._ID, Tables.KEY_RINGS + "." + BaseColumns._ID); - projectionMap.put(KeyRingsColumns.MASTER_KEY_ID, Tables.KEY_RINGS + "." - + KeyRingsColumns.MASTER_KEY_ID); - projectionMap.put(UserIdsColumns.USER_ID, Tables.USER_IDS + "." - + UserIdsColumns.USER_ID); + projectionMap.put(KeyRingsColumns.MASTER_KEY_ROW_ID, Tables.KEY_RINGS + "." + + KeyRingsColumns.MASTER_KEY_ROW_ID); + projectionMap.put(UserIdsColumns.USER_ID, Tables.USERS + "." + UserIdsColumns.USER_ID); String emails = uri.getPathSegments().get(3); String chunks[] = emails.split(" *, *"); @@ -391,7 +389,7 @@ public class ApgProvider extends ContentProvider { if (gotCondition) { qb.appendWhere(" AND EXISTS (SELECT tmp." + BaseColumns._ID + " FROM " - + Tables.USER_IDS + " AS tmp WHERE tmp." + UserIdsColumns.KEY_ID + " = " + + Tables.USERS + " AS tmp WHERE tmp." + UserIdsColumns.KEY_ROW_ID + " = " + Tables.KEYS + "." + BaseColumns._ID + " AND (" + emailWhere + "))"); } @@ -450,7 +448,7 @@ public class ApgProvider extends ContentProvider { break; case PUBLIC_KEY_RING_USER_ID: - db.insertOrThrow(Tables.USER_IDS, null, values); + db.insertOrThrow(Tables.USERS, null, values); rowUri = PublicUserIds.buildPublicUserIdsUri(values.getAsString(PublicUserIds._ID)); break; @@ -470,7 +468,7 @@ public class ApgProvider extends ContentProvider { break; case SECRET_KEY_RING_USER_ID: - db.insertOrThrow(Tables.USER_IDS, null, values); + db.insertOrThrow(Tables.USERS, null, values); rowUri = SecretUserIds.buildSecretUserIdsUri(values.getAsString(SecretUserIds._ID)); break; @@ -498,16 +496,13 @@ public class ApgProvider extends ContentProvider { final int match = sUriMatcher.match(uri); switch (match) { - case PUBLIC_KEY_RING_ID: - // delete corresponding keys and userids - // db.delete(Tables.KEYS, whereClause, whereArgs) - // TODO + case PUBLIC_KEY_RING_ROW_ID: + // corresponding keys and userids are deleted by ON DELETE CASCADE count = db.delete(Tables.KEY_RINGS, buildDefaultSelection(uri, KeyTypes.PUBLIC, selection), selectionArgs); break; - case SECRET_KEY_RING_ID: - // delete corresponding keys and userids - // TODO + case SECRET_KEY_RING_ROW_ID: + // corresponding keys and userids are deleted by ON DELETE CASCADE count = db.delete(Tables.KEY_RINGS, buildDefaultSelection(uri, KeyTypes.SECRET, selection), selectionArgs); break; @@ -532,13 +527,13 @@ public class ApgProvider extends ContentProvider { try { final int match = sUriMatcher.match(uri); switch (match) { - case PUBLIC_KEY_RING_ID: + case PUBLIC_KEY_RING_ROW_ID: count = db.update(Tables.KEY_RINGS, values, buildDefaultSelection(uri, KeyTypes.PUBLIC, selection), selectionArgs); break; - case SECRET_KEY_RING_ID: + case SECRET_KEY_RING_ROW_ID: count = db.update(Tables.KEY_RINGS, values, - buildDefaultSelection(uri, KeyTypes.PUBLIC, selection), selectionArgs); + buildDefaultSelection(uri, KeyTypes.SECRET, selection), selectionArgs); break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); diff --git a/org_apg/src/org/thialfihar/android/apg/provider/ProviderHelper.java b/org_apg/src/org/thialfihar/android/apg/provider/ProviderHelper.java index 234f96bd0..00fe51a7b 100644 --- a/org_apg/src/org/thialfihar/android/apg/provider/ProviderHelper.java +++ b/org_apg/src/org/thialfihar/android/apg/provider/ProviderHelper.java @@ -1,79 +1,207 @@ package org.thialfihar.android.apg.provider; import java.io.IOException; +import java.util.Vector; +import org.spongycastle.openpgp.PGPException; +import org.spongycastle.openpgp.PGPKeyRing; import org.spongycastle.openpgp.PGPPublicKey; import org.spongycastle.openpgp.PGPPublicKeyRing; +import org.spongycastle.openpgp.PGPSecretKey; +import org.spongycastle.openpgp.PGPSecretKeyRing; +import org.thialfihar.android.apg.Constants; +import org.thialfihar.android.apg.Id; +import org.thialfihar.android.apg.helper.PGPConversionHelper; +import org.thialfihar.android.apg.helper.PGPHelper; import org.thialfihar.android.apg.helper.PGPMain.ApgGeneralException; import org.thialfihar.android.apg.provider.ApgContract.PublicKeyRings; import org.thialfihar.android.apg.provider.ApgContract.PublicKeys; +import org.thialfihar.android.apg.provider.ApgContract.SecretKeyRings; import org.thialfihar.android.apg.provider.ApgContract.SecretKeys; +import org.thialfihar.android.apg.util.Log; +import android.content.ContentResolver; +import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.net.Uri; public class ProviderHelper { - // public static void insertHostsSource(Context context, String url) { - // ContentValues values = new ContentValues(); - // values.put(HostsSources.URL, url); - // values.put(HostsSources.ENABLED, true); // default is enabled - // values.put(HostsSources.LAST_MODIFIED_LOCAL, 0); // last_modified_local starts at 0 - // values.put(HostsSources.LAST_MODIFIED_ONLINE, 0); // last_modified_onlinestarts at 0 - // context.getContentResolver().insert(HostsSources.CONTENT_URI, values); - // } - // public int saveKeyRing(Context context, PGPPublicKeyRing keyRing) throws IOException, - // ApgGeneralException { - // // mDb.beginTransaction(); - // ContentValues values = new ContentValues(); - // PGPPublicKey masterKey = keyRing.getPublicKey(); - // long masterKeyId = masterKey.getKeyID(); - // - // values.put(PublicKeyRings.MASTER_KEY_ID, masterKeyId); - // // values.put(KeyRings.TYPE, Id.database.type_public); - // values.put(PublicKeyRings.KEY_RING_DATA, keyRing.getEncoded()); - // - // context.getContentResolver().insert(PublicKeyRings.CONTENT_URI, values); - // - // long rowId = insertOrUpdateKeyRing(values); - // int returnValue = mStatus; - // - // if (rowId == -1) { - // throw new ApgGeneralException("saving public key ring " + masterKeyId + " failed"); - // } - // - // Vector seenIds = new Vector(); - // int rank = 0; - // for (PGPPublicKey key : new IterableIterator(keyRing.getPublicKeys())) { - // seenIds.add(saveKey(rowId, key, rank)); - // ++rank; + /** + * Retrieves the actual PGPPublicKeyRing object from the database blob associated with the rowId + * + * @param context + * @param rowId + * @return + */ + public static PGPPublicKeyRing getPGPPublicKeyRing(Context context, long rowId) { + Uri queryUri = PublicKeyRings.buildPublicKeyRingsUri(Long.toString(rowId)); + Cursor cursor = context.getContentResolver() + .query(queryUri, new String[] { PublicKeyRings._ID, PublicKeyRings.KEY_RING_DATA }, + null, null, null); + + PGPPublicKeyRing keyRing = null; + if (cursor != null && cursor.moveToFirst()) { + int keyRingDataCol = cursor.getColumnIndex(PublicKeyRings.KEY_RING_DATA); + + byte[] data = cursor.getBlob(keyRingDataCol); + if (data != null) { + keyRing = PGPConversionHelper.BytesToPGPPublicKeyRing(data); + } + } + + if (cursor != null) { + cursor.close(); + } + + return keyRing; + } + + /** + * Retrieves the actual PGPSecretKeyRing object from the database blob associated with the rowId + * + * @param context + * @param rowId + * @return + */ + public static PGPSecretKeyRing getPGPSecretKeyRing(Context context, long rowId) { + Uri queryUri = SecretKeyRings.buildSecretKeyRingsUri(Long.toString(rowId)); + Cursor cursor = context.getContentResolver() + .query(queryUri, new String[] { SecretKeyRings._ID, SecretKeyRings.KEY_RING_DATA }, + null, null, null); + + PGPSecretKeyRing keyRing = null; + if (cursor != null && cursor.moveToFirst()) { + int keyRingDataCol = cursor.getColumnIndex(SecretKeyRings.KEY_RING_DATA); + + byte[] data = cursor.getBlob(keyRingDataCol); + if (data != null) { + keyRing = PGPConversionHelper.BytesToPGPSecretKeyRing(data); + } + } + + if (cursor != null) { + cursor.close(); + } + + return keyRing; + } + + public static PGPSecretKey getPGPSecretKey(Context context, long keyId) { + PGPSecretKeyRing keyRing = ProviderHelper.getPGPSecretKeyRing(context, keyId); + if (keyRing == null) { + return null; + } + return keyRing.getSecretKey(keyId); + } + + public static PGPPublicKey getPGPPublicKey(Context context, long keyId) { + PGPPublicKeyRing keyRing = ProviderHelper.getPGPPublicKeyRing(context, keyId); + if (keyRing == null) { + return null; + } + + return keyRing.getPublicKey(keyId); + } + + // public static String getMainUserId(long keyRowId, int type) { + // Uri queryUri = SecretKeyRings.buildSecretKeyRingsUri(Long.toString(rowId)); + // Cursor cursor = context.getContentResolver() + // .query(queryUri, new String[] { SecretKeyRings._ID, SecretKeyRings.KEY_RING_DATA }, + // null, null, null); + + // SQLiteDatabase db = mDatabase.db(); + // Cursor c = db.query(Keys.TABLE_NAME + " INNER JOIN " + KeyRings.TABLE_NAME + " ON (" + // + KeyRings.TABLE_NAME + "." + KeyRings._ID + " = " + Keys.TABLE_NAME + "." + // + Keys.KEY_RING_ID + ") " + " INNER JOIN " + Keys.TABLE_NAME + " AS masterKey ON (" + // + KeyRings.TABLE_NAME + "." + KeyRings._ID + " = " + "masterKey." + // + Keys.KEY_RING_ID + " AND " + "masterKey." + Keys.IS_MASTER_KEY + " = '1') " + // + " INNER JOIN " + UserIds.TABLE_NAME + " ON (" + UserIds.TABLE_NAME + "." + // + UserIds.KEY_ID + " = " + "masterKey." + Keys._ID + " AND " + UserIds.TABLE_NAME + // + "." + UserIds.RANK + " = '0')", new String[] { UserIds.USER_ID }, Keys.TABLE_NAME + // + "." + Keys.KEY_ID + " = ? AND " + KeyRings.TABLE_NAME + "." + KeyRings.TYPE + // + " = ?", new String[] { "" + keyRowId, "" + type, }, null, null, null); + // String userId = ""; + // if (c != null && c.moveToFirst()) { + // do { + // userId = c.getString(0); + // } while (c.moveToNext()); // } // - // String seenIdsStr = ""; - // for (Integer id : seenIds) { - // if (seenIdsStr.length() > 0) { - // seenIdsStr += ","; - // } - // seenIdsStr += id; + // if (c != null) { + // c.close(); // } - // mDb.delete(Keys.TABLE_NAME, Keys.KEY_RING_ID + " = ? AND " + Keys._ID + " NOT IN (" - // + seenIdsStr + ")", new String[] { "" + rowId }); // - // mDb.setTransactionSuccessful(); - // mDb.endTransaction(); - // return returnValue; + // return userId; // } /** - * Deletes public and secret keys + * Retrieves ids of all SecretKeyRings * * @param context - * @param rowId + * @return */ - public static void deleteKey(Context context, long rowId) { - context.getContentResolver().delete(PublicKeys.buildPublicKeysUri(Long.toString(rowId)), - null, null); - context.getContentResolver().delete(SecretKeys.buildSecretKeysUri(Long.toString(rowId)), - null, null); + public static Vector getSecretKeyRingsRowIds(Context context) { + Uri queryUri = SecretKeyRings.buildSecretKeyRingsUri(); + Cursor cursor = context.getContentResolver().query(queryUri, + new String[] { SecretKeyRings._ID }, null, null, null); + + Vector keyIds = new Vector(); + if (cursor != null) { + int idCol = cursor.getColumnIndex(SecretKeyRings._ID); + if (cursor.moveToFirst()) { + do { + keyIds.add(cursor.getInt(idCol)); + } while (cursor.moveToNext()); + } + } + + if (cursor != null) { + cursor.close(); + } + + return keyIds; } + + /** + * Retrieves ids of all PublicKeyRings + * + * @param context + * @return + */ + public static Vector getPublicKeyRingsRowIds(Context context) { + Uri queryUri = PublicKeyRings.buildPublicKeyRingsUri(); + Cursor cursor = context.getContentResolver().query(queryUri, + new String[] { PublicKeyRings._ID }, null, null, null); + + Vector keyIds = new Vector(); + if (cursor != null) { + int idCol = cursor.getColumnIndex(PublicKeyRings._ID); + if (cursor.moveToFirst()) { + do { + keyIds.add(cursor.getInt(idCol)); + } while (cursor.moveToNext()); + } + } + + if (cursor != null) { + cursor.close(); + } + + return keyIds; + } + + public static void deletePublicKeyRing(Context context, long rowId) { + ContentResolver cr = context.getContentResolver(); + cr.delete(PublicKeyRings.buildPublicKeyRingsUri(Long.toString(rowId)), null, null); + } + + public static void deleteSecretKeyRing(Context context, long rowId) { + ContentResolver cr = context.getContentResolver(); + cr.delete(SecretKeyRings.buildSecretKeyRingsUri(Long.toString(rowId)), null, null); + } + } diff --git a/org_apg/src/org/thialfihar/android/apg/service/ApgService.java b/org_apg/src/org/thialfihar/android/apg/service/ApgService.java index c324c4c62..95434ab30 100644 --- a/org_apg/src/org/thialfihar/android/apg/service/ApgService.java +++ b/org_apg/src/org/thialfihar/android/apg/service/ApgService.java @@ -35,7 +35,6 @@ import org.spongycastle.openpgp.PGPSecretKeyRing; import org.thialfihar.android.apg.Constants; import org.thialfihar.android.apg.Id; import org.thialfihar.android.apg.R; -import org.thialfihar.android.apg.deprecated.DataProvider; import org.thialfihar.android.apg.helper.FileHelper; import org.thialfihar.android.apg.helper.OtherHelper; import org.thialfihar.android.apg.helper.PGPMain; @@ -43,7 +42,7 @@ import org.thialfihar.android.apg.helper.Preferences; import org.thialfihar.android.apg.helper.PGPMain.ApgGeneralException; import org.thialfihar.android.apg.helper.PGPConversionHelper; import org.thialfihar.android.apg.provider.ApgContract.DataStream; -import org.thialfihar.android.apg.provider.ApgProvider; +import org.thialfihar.android.apg.provider.ProviderHelper; import org.thialfihar.android.apg.util.HkpKeyServer; import org.thialfihar.android.apg.util.InputData; import org.thialfihar.android.apg.util.KeyServer.KeyInfo; @@ -622,8 +621,8 @@ public class ApgService extends IntentService implements ProgressDialogUpdater { throw new PGPMain.ApgGeneralException(getString(R.string.error_fileNotFound, deleteFile)); } catch (IOException e) { - throw new PGPMain.ApgGeneralException(getString(R.string.error_fileDeleteFailed, - deleteFile)); + throw new PGPMain.ApgGeneralException(getString( + R.string.error_fileDeleteFailed, deleteFile)); } /* Output */ @@ -715,9 +714,11 @@ public class ApgService extends IntentService implements ProgressDialogUpdater { Vector keyRingIds = new Vector(); if (exportAll) { - keyRingIds = PGPMain - .getKeyRingIds(keyType == Id.type.public_key ? Id.database.type_public - : Id.database.type_secret); + if (keyType == Id.type.public_key) { + keyRingIds = ProviderHelper.getPublicKeyRingsRowIds(this); + } else { + keyRingIds = ProviderHelper.getSecretKeyRingsRowIds(this); + } } else { keyRingIds.add(keyRingId); } @@ -742,8 +743,8 @@ public class ApgService extends IntentService implements ProgressDialogUpdater { /* Operation */ HkpKeyServer server = new HkpKeyServer(keyServer); - PGPKeyRing keyring = PGPMain.getKeyRing(keyRingId); - if (keyring != null && keyring instanceof PGPPublicKeyRing) { + PGPPublicKeyRing keyring = ProviderHelper.getPGPPublicKeyRing(this, keyRingId); + if (keyring != null) { boolean uploaded = PGPMain.uploadKeyRingToServer(server, (PGPPublicKeyRing) keyring); if (!uploaded) { diff --git a/org_apg/src/org/thialfihar/android/apg/service/PassphraseCacheService.java b/org_apg/src/org/thialfihar/android/apg/service/PassphraseCacheService.java index 6e2fc1d86..1909facd3 100644 --- a/org_apg/src/org/thialfihar/android/apg/service/PassphraseCacheService.java +++ b/org_apg/src/org/thialfihar/android/apg/service/PassphraseCacheService.java @@ -24,8 +24,8 @@ import org.spongycastle.openpgp.PGPSecretKeyRing; import org.thialfihar.android.apg.Constants; import org.thialfihar.android.apg.Id; import org.thialfihar.android.apg.helper.PGPHelper; -import org.thialfihar.android.apg.helper.PGPMain; import org.thialfihar.android.apg.helper.Preferences; +import org.thialfihar.android.apg.provider.ProviderHelper; import android.app.AlarmManager; import android.app.PendingIntent; @@ -88,7 +88,7 @@ public class PassphraseCacheService extends Service { // try to get real key id long realId = keyId; if (realId != Id.key.symmetric) { - PGPSecretKeyRing keyRing = PGPMain.getSecretKeyRing(keyId); + PGPSecretKeyRing keyRing = ProviderHelper.getPGPSecretKeyRing(context, keyId); if (keyRing == null) { return null; } diff --git a/org_apg/src/org/thialfihar/android/apg/ui/DecryptActivity.java b/org_apg/src/org/thialfihar/android/apg/ui/DecryptActivity.java index 7e7344c4e..a72842369 100644 --- a/org_apg/src/org/thialfihar/android/apg/ui/DecryptActivity.java +++ b/org_apg/src/org/thialfihar/android/apg/ui/DecryptActivity.java @@ -24,6 +24,7 @@ import org.thialfihar.android.apg.helper.FileHelper; import org.thialfihar.android.apg.helper.OtherHelper; import org.thialfihar.android.apg.helper.PGPHelper; import org.thialfihar.android.apg.helper.PGPMain; +import org.thialfihar.android.apg.provider.ProviderHelper; import org.thialfihar.android.apg.service.ApgServiceHandler; import org.thialfihar.android.apg.service.ApgService; import org.thialfihar.android.apg.service.PassphraseCacheService; @@ -333,7 +334,8 @@ public class DecryptActivity extends SherlockFragmentActivity { if (mSignatureKeyId == 0) { return; } - PGPPublicKeyRing key = PGPMain.getPublicKeyRing(mSignatureKeyId); + PGPPublicKeyRing key = ProviderHelper.getPGPPublicKeyRing(DecryptActivity.this, + mSignatureKeyId); if (key != null) { Intent intent = new Intent(DecryptActivity.this, KeyServerQueryActivity.class); intent.setAction(KeyServerQueryActivity.ACTION_LOOK_UP_KEY_ID); @@ -655,7 +657,8 @@ public class DecryptActivity extends SherlockFragmentActivity { try { setSecretKeyId(PGPMain.getDecryptionKeyId(this, inStream)); if (getSecretKeyId() == Id.key.none) { - throw new PGPMain.ApgGeneralException(getString(R.string.error_noSecretKeyFound)); + throw new PGPMain.ApgGeneralException( + getString(R.string.error_noSecretKeyFound)); } mAssumeSymmetricEncryption = false; } catch (PGPMain.NoAsymmetricEncryptionException e) { diff --git a/org_apg/src/org/thialfihar/android/apg/ui/EditKeyActivity.java b/org_apg/src/org/thialfihar/android/apg/ui/EditKeyActivity.java index 0d15014b7..ca0c1f281 100644 --- a/org_apg/src/org/thialfihar/android/apg/ui/EditKeyActivity.java +++ b/org_apg/src/org/thialfihar/android/apg/ui/EditKeyActivity.java @@ -25,6 +25,7 @@ import org.thialfihar.android.apg.helper.OtherHelper; import org.thialfihar.android.apg.helper.PGPHelper; import org.thialfihar.android.apg.helper.PGPMain; import org.thialfihar.android.apg.helper.PGPConversionHelper; +import org.thialfihar.android.apg.provider.ProviderHelper; import org.thialfihar.android.apg.service.ApgServiceHandler; import org.thialfihar.android.apg.service.ApgService; import org.thialfihar.android.apg.ui.dialog.SetPassphraseDialogFragment; @@ -308,7 +309,7 @@ public class EditKeyActivity extends SherlockFragmentActivity { if (keyId != 0) { PGPSecretKey masterKey = null; - mKeyRing = PGPMain.getSecretKeyRing(keyId); + mKeyRing = ProviderHelper.getPGPSecretKeyRing(this, keyId); if (mKeyRing != null) { masterKey = PGPHelper.getMasterKey(mKeyRing); for (PGPSecretKey key : new IterableIterator( @@ -460,7 +461,8 @@ public class EditKeyActivity extends SherlockFragmentActivity { * @param userIdsView * @return */ - private ArrayList getUserIds(SectionView userIdsView) throws PGPMain.ApgGeneralException { + private ArrayList getUserIds(SectionView userIdsView) + throws PGPMain.ApgGeneralException { ArrayList userIds = new ArrayList(); ViewGroup userIdEditors = userIdsView.getEditors(); @@ -472,7 +474,8 @@ public class EditKeyActivity extends SherlockFragmentActivity { try { userId = editor.getValue(); } catch (UserIdEditor.NoNameException e) { - throw new PGPMain.ApgGeneralException(this.getString(R.string.error_userIdNeedsAName)); + throw new PGPMain.ApgGeneralException( + this.getString(R.string.error_userIdNeedsAName)); } catch (UserIdEditor.NoEmailException e) { throw new PGPMain.ApgGeneralException( this.getString(R.string.error_userIdNeedsAnEmailAddress)); @@ -497,7 +500,8 @@ public class EditKeyActivity extends SherlockFragmentActivity { } if (!gotMainUserId) { - throw new PGPMain.ApgGeneralException(getString(R.string.error_mainUserIdMustNotBeEmpty)); + throw new PGPMain.ApgGeneralException( + getString(R.string.error_mainUserIdMustNotBeEmpty)); } return userIds; @@ -509,7 +513,8 @@ public class EditKeyActivity extends SherlockFragmentActivity { * @param keysView * @return */ - private ArrayList getKeys(SectionView keysView) throws PGPMain.ApgGeneralException { + private ArrayList getKeys(SectionView keysView) + throws PGPMain.ApgGeneralException { ArrayList keys = new ArrayList(); ViewGroup keyEditors = keysView.getEditors(); @@ -532,7 +537,8 @@ public class EditKeyActivity extends SherlockFragmentActivity { * @param keysView * @return */ - private ArrayList getKeysUsages(SectionView keysView) throws PGPMain.ApgGeneralException { + private ArrayList getKeysUsages(SectionView keysView) + throws PGPMain.ApgGeneralException { ArrayList getKeysUsages = new ArrayList(); ViewGroup keyEditors = keysView.getEditors(); diff --git a/org_apg/src/org/thialfihar/android/apg/ui/EncryptActivity.java b/org_apg/src/org/thialfihar/android/apg/ui/EncryptActivity.java index dfdfe4d5c..7a4686d53 100644 --- a/org_apg/src/org/thialfihar/android/apg/ui/EncryptActivity.java +++ b/org_apg/src/org/thialfihar/android/apg/ui/EncryptActivity.java @@ -28,6 +28,7 @@ import org.thialfihar.android.apg.helper.OtherHelper; import org.thialfihar.android.apg.helper.PGPHelper; import org.thialfihar.android.apg.helper.PGPMain; import org.thialfihar.android.apg.helper.Preferences; +import org.thialfihar.android.apg.provider.ProviderHelper; import org.thialfihar.android.apg.service.ApgServiceHandler; import org.thialfihar.android.apg.service.ApgService; import org.thialfihar.android.apg.service.PassphraseCacheService; @@ -440,7 +441,7 @@ public class EncryptActivity extends SherlockFragmentActivity { long signatureKeyId = extras.getLong(EXTRA_SIGNATURE_KEY_ID); long encryptionKeyIds[] = extras.getLongArray(EXTRA_ENCRYPTION_KEY_IDS); if (signatureKeyId != 0) { - PGPSecretKeyRing keyRing = PGPMain.getSecretKeyRing(signatureKeyId); + PGPSecretKeyRing keyRing = ProviderHelper.getPGPSecretKeyRing(this, signatureKeyId); PGPSecretKey masterKey = null; if (keyRing != null) { masterKey = PGPHelper.getMasterKey(keyRing); @@ -456,7 +457,8 @@ public class EncryptActivity extends SherlockFragmentActivity { if (encryptionKeyIds != null) { Vector goodIds = new Vector(); for (int i = 0; i < encryptionKeyIds.length; ++i) { - PGPPublicKeyRing keyRing = PGPMain.getPublicKeyRing(encryptionKeyIds[i]); + PGPPublicKeyRing keyRing = ProviderHelper.getPGPPublicKeyRing(this, + encryptionKeyIds[i]); PGPPublicKey masterKey = null; if (keyRing == null) { continue; @@ -956,7 +958,7 @@ public class EncryptActivity extends SherlockFragmentActivity { } else { String uid = getResources().getString(R.string.unknownUserId); String uidExtra = ""; - PGPSecretKeyRing keyRing = PGPMain.getSecretKeyRing(getSecretKeyId()); + PGPSecretKeyRing keyRing = ProviderHelper.getPGPSecretKeyRing(this, getSecretKeyId()); if (keyRing != null) { PGPSecretKey key = PGPHelper.getMasterKey(keyRing); if (key != null) { diff --git a/org_apg/src/org/thialfihar/android/apg/ui/KeyListActivity.java b/org_apg/src/org/thialfihar/android/apg/ui/KeyListActivity.java index 8ca686217..f251608e2 100644 --- a/org_apg/src/org/thialfihar/android/apg/ui/KeyListActivity.java +++ b/org_apg/src/org/thialfihar/android/apg/ui/KeyListActivity.java @@ -601,7 +601,7 @@ public class KeyListActivity extends SherlockFragmentActivity { if (masterKeyId != -1) { children.insertElementAt( - new KeyChild(PGPHelper.getFingerPrint(fingerPrintId), true), 0); + new KeyChild(PGPHelper.getFingerPrint(KeyListActivity.this, fingerPrintId), true), 0); c = mDatabase.query(UserIds.TABLE_NAME, new String[] { UserIds.USER_ID, // 0 }, UserIds.KEY_ID + " = ? AND " + UserIds.RANK + " > 0", new String[] { "" + masterKeyId }, null, null, UserIds.RANK + " ASC"); diff --git a/org_apg/src/org/thialfihar/android/apg/ui/PublicKeyListActivity.java b/org_apg/src/org/thialfihar/android/apg/ui/PublicKeyListActivity.java index f14a6083e..03f76a6c0 100644 --- a/org_apg/src/org/thialfihar/android/apg/ui/PublicKeyListActivity.java +++ b/org_apg/src/org/thialfihar/android/apg/ui/PublicKeyListActivity.java @@ -22,6 +22,7 @@ import org.thialfihar.android.apg.Id; import org.thialfihar.android.apg.R; import org.thialfihar.android.apg.helper.PGPHelper; import org.thialfihar.android.apg.helper.PGPMain; +import org.thialfihar.android.apg.provider.ProviderHelper; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; @@ -115,8 +116,8 @@ public class PublicKeyListActivity extends KeyListActivity { mSelectedItem = groupPosition; final int keyRingId = mListAdapter.getKeyRingId(groupPosition); long keyId = 0; - Object keyRing = PGPMain.getKeyRing(keyRingId); - if (keyRing != null && keyRing instanceof PGPPublicKeyRing) { + PGPPublicKeyRing keyRing = ProviderHelper.getPGPPublicKeyRing(this, keyRingId); + if (keyRing != null) { keyId = PGPHelper.getMasterKey((PGPPublicKeyRing) keyRing).getKeyID(); } if (keyId == 0) { @@ -148,8 +149,8 @@ public class PublicKeyListActivity extends KeyListActivity { mSelectedItem = groupPosition; final int keyRingId = mListAdapter.getKeyRingId(groupPosition); long keyId = 0; - Object keyRing = PGPMain.getKeyRing(keyRingId); - if (keyRing != null && keyRing instanceof PGPPublicKeyRing) { + PGPPublicKeyRing keyRing = ProviderHelper.getPGPPublicKeyRing(this, keyRingId); + if (keyRing != null) { keyId = PGPHelper.getMasterKey((PGPPublicKeyRing) keyRing).getKeyID(); } diff --git a/org_apg/src/org/thialfihar/android/apg/ui/SignKeyActivity.java b/org_apg/src/org/thialfihar/android/apg/ui/SignKeyActivity.java index 3311c320e..e711109fc 100644 --- a/org_apg/src/org/thialfihar/android/apg/ui/SignKeyActivity.java +++ b/org_apg/src/org/thialfihar/android/apg/ui/SignKeyActivity.java @@ -25,6 +25,7 @@ import org.thialfihar.android.apg.Id; import org.thialfihar.android.apg.R; import org.thialfihar.android.apg.helper.PGPMain; import org.thialfihar.android.apg.helper.Preferences; +import org.thialfihar.android.apg.provider.ProviderHelper; import org.thialfihar.android.apg.service.ApgService; import org.thialfihar.android.apg.service.ApgServiceHandler; import org.thialfihar.android.apg.service.PassphraseCacheService; @@ -154,7 +155,7 @@ public class SignKeyActivity extends SherlockFragmentActivity { * handles the UI bits of the signing process on the UI thread */ private void initiateSigning() { - PGPPublicKeyRing pubring = PGPMain.getPublicKeyRing(mPubKeyId); + PGPPublicKeyRing pubring = ProviderHelper.getPGPPublicKeyRing(this, mPubKeyId); if (pubring != null) { // if we have already signed this key, dont bother doing it again boolean alreadySigned = false; diff --git a/org_apg/src/org/thialfihar/android/apg/ui/dialog/DeleteKeyDialogFragment.java b/org_apg/src/org/thialfihar/android/apg/ui/dialog/DeleteKeyDialogFragment.java index d8a0cb33b..3a5ed9948 100644 --- a/org_apg/src/org/thialfihar/android/apg/ui/dialog/DeleteKeyDialogFragment.java +++ b/org_apg/src/org/thialfihar/android/apg/ui/dialog/DeleteKeyDialogFragment.java @@ -23,6 +23,7 @@ import org.thialfihar.android.apg.Id; import org.thialfihar.android.apg.R; import org.thialfihar.android.apg.helper.PGPHelper; import org.thialfihar.android.apg.helper.PGPMain; +import org.thialfihar.android.apg.provider.ProviderHelper; import org.thialfihar.android.apg.util.Log; import android.app.AlertDialog; @@ -93,8 +94,11 @@ public class DeleteKeyDialogFragment extends DialogFragment { builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setPositiveButton(R.string.btn_delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { - // deleteKey(deleteKeyRingId); - PGPMain.deleteKey(deleteKeyRingId); + if (keyType == Id.type.public_key) { + ProviderHelper.deletePublicKeyRing(activity, deleteKeyRingId); + } else { + ProviderHelper.deleteSecretKeyRing(activity, deleteKeyRingId); + } dismiss(); -- cgit v1.2.3