Java Code Examples for net.sqlcipher.database.SQLiteDatabase#openDatabase()

The following examples show how to use net.sqlcipher.database.SQLiteDatabase#openDatabase() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SQLCipherUtils.java    From cwac-saferoom with Apache License 2.0 6 votes vote down vote up
/**
 * Determine whether or not this database appears to be encrypted, based
 * on whether we can open it without a passphrase.
 *
 * NOTE: You are responsible for ensuring that net.sqlcipher.database.SQLiteDatabase.loadLibs()
 * is called before calling this method. This is handled automatically with the
 * getDatabaseState() method that takes a Context as a parameter.
 *
 * @param dbPath a File pointing to the database
 * @return the detected state of the database
 */
public static State getDatabaseState(File dbPath) {
  if (dbPath.exists()) {
    SQLiteDatabase db=null;

    try {
      db=
        SQLiteDatabase.openDatabase(dbPath.getAbsolutePath(), "",
          null, SQLiteDatabase.OPEN_READONLY);

      db.getVersion();

      return(State.UNENCRYPTED);
    }
    catch (Exception e) {
      return(State.ENCRYPTED);
    }
    finally {
      if (db != null) {
        db.close();
      }
    }
  }

  return(State.DOES_NOT_EXIST);
}
 
Example 2
Source File: SQLCipherDriver.java    From alchemy with Apache License 2.0 6 votes vote down vote up
@Override
public SQLiteDb open(String path, boolean readOnly, boolean fullMutex) {
    int flags = 0;
    if (readOnly) {
        flags |= SQLiteDatabase.OPEN_READONLY;
    } else {
        flags |= SQLiteDatabase.OPEN_READWRITE;
        flags |= SQLiteDatabase.CREATE_IF_NECESSARY;
    }
    final SQLiteDatabase db = SQLiteDatabase.openDatabase(path, mPassword, null, flags);
    /*final SQLiteDatabase db = SQLiteDatabase.openDatabase(path, null, flags);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        db.setForeignKeyConstraintsEnabled(true);
    } else {
        db.execSQL("PRAGMA foreign_keys = ON;");
    }*/
    return new SQLCipherDb(db);
}
 
Example 3
Source File: SQLCipherUtils.java    From kripton with Apache License 2.0 6 votes vote down vote up
/**
 * Determine whether or not this database appears to be encrypted, based
 * on whether we can open it without a passphrase.
 *
 * NOTE: You are responsible for ensuring that net.sqlcipher.database.SQLiteDatabase.loadLibs()
 * is called before calling this method. This is handled automatically with the
 * getDatabaseState() method that takes a Context as a parameter.
 *
 * @param dbPath a File pointing to the database
 * @return the detected state of the database
 */
public static State getDatabaseState(File dbPath) {
  if (dbPath.exists()) {
    SQLiteDatabase db=null;

    try {
      db=
        SQLiteDatabase.openDatabase(dbPath.getAbsolutePath(), "",
          null, SQLiteDatabase.OPEN_READONLY);

      db.getVersion();

      return(State.UNENCRYPTED);
    }
    catch (Exception e) {
      return(State.ENCRYPTED);
    }
    finally {
      if (db != null) {
        db.close();
      }
    }
  }

  return(State.DOES_NOT_EXIST);
}
 
Example 4
Source File: SQLCipherUtils.java    From cwac-saferoom with Apache License 2.0 5 votes vote down vote up
/**
 * Replaces this database with a version encrypted with the supplied
 * passphrase, deleting the original. Do not call this while the database
 * is open, which includes during any Room migrations.
 *
 * The passphrase is untouched in this call. If you are going to turn around
 * and use it with SafeHelperFactory.fromUser(), fromUser() will clear the
 * passphrase. If not, please set all bytes of the passphrase to 0 or something
 * to clear out the passphrase.
 *
 * @param ctxt a Context
 * @param originalFile a File pointing to the database
 * @param passphrase the passphrase from the user
 * @throws IOException
 */
public static void encrypt(Context ctxt, File originalFile, byte[] passphrase)
  throws IOException {
  SQLiteDatabase.loadLibs(ctxt);

  if (originalFile.exists()) {
    File newFile=File.createTempFile("sqlcipherutils", "tmp",
        ctxt.getCacheDir());
    SQLiteDatabase db=
      SQLiteDatabase.openDatabase(originalFile.getAbsolutePath(),
        "", null, SQLiteDatabase.OPEN_READWRITE);
    int version=db.getVersion();

    db.close();

    db=SQLiteDatabase.openDatabase(newFile.getAbsolutePath(), passphrase,
      null, SQLiteDatabase.OPEN_READWRITE, null, null);

    final SQLiteStatement st=db.compileStatement("ATTACH DATABASE ? AS plaintext KEY ''");

    st.bindString(1, originalFile.getAbsolutePath());
    st.execute();

    db.rawExecSQL("SELECT sqlcipher_export('main', 'plaintext')");
    db.rawExecSQL("DETACH DATABASE plaintext");
    db.setVersion(version);
    st.close();
    db.close();

    originalFile.delete();
    newFile.renameTo(originalFile);
  }
  else {
    throw new FileNotFoundException(originalFile.getAbsolutePath()+" not found");
  }
}
 
Example 5
Source File: SQLCipherUtils.java    From cwac-saferoom with Apache License 2.0 5 votes vote down vote up
/**
 * Replaces this database with a decrypted version, deleting the original
 * encrypted database. Do not call this while the database is open, which
 * includes during any Room migrations.
 *
 * The passphrase is untouched in this call. Please set all bytes of the
 * passphrase to 0 or something to clear out the passphrase if you are done
 * with it.
 *
 * @param ctxt a Context
 * @param originalFile a File pointing to the encrypted database
 * @param passphrase the passphrase from the user for the encrypted database
 * @throws IOException
 */
public static void decrypt(Context ctxt, File originalFile, byte[] passphrase)
  throws IOException {
  SQLiteDatabase.loadLibs(ctxt);

  if (originalFile.exists()) {
    File newFile=
      File.createTempFile("sqlcipherutils", "tmp",
        ctxt.getCacheDir());
    SQLiteDatabase db=
      SQLiteDatabase.openDatabase(originalFile.getAbsolutePath(),
        passphrase, null, SQLiteDatabase.OPEN_READWRITE, null, null);

    final SQLiteStatement st=db.compileStatement("ATTACH DATABASE ? AS plaintext KEY ''");

    st.bindString(1, newFile.getAbsolutePath());
    st.execute();

    db.rawExecSQL("SELECT sqlcipher_export('plaintext')");
    db.rawExecSQL("DETACH DATABASE plaintext");

    int version=db.getVersion();

    st.close();
    db.close();

    db=SQLiteDatabase.openDatabase(newFile.getAbsolutePath(), "",
      null, SQLiteDatabase.OPEN_READWRITE);
    db.setVersion(version);
    db.close();

    originalFile.delete();
    newFile.renameTo(originalFile);
  }
  else {
    throw new FileNotFoundException(originalFile.getAbsolutePath()+" not found");
  }
}
 
Example 6
Source File: SQLCipherUtils.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * Replaces this database with a version encrypted with the supplied
 * passphrase, deleting the original. Do not call this while the database
 * is open, which includes during any Room migrations.
 *
 * The passphrase is untouched in this call. If you are going to turn around
 * and use it with SafeHelperFactory.fromUser(), fromUser() will clear the
 * passphrase. If not, please set all bytes of the passphrase to 0 or something
 * to clear out the passphrase.
 *
 * @param ctxt a Context
 * @param originalFile a File pointing to the database
 * @param passphrase the passphrase from the user
 * @throws IOException
 */
public static void encrypt(Context ctxt, File originalFile, byte[] passphrase)
  throws IOException {
  SQLiteDatabase.loadLibs(ctxt);

  if (originalFile.exists()) {
    File newFile=File.createTempFile("sqlcipherutils", "tmp",
        ctxt.getCacheDir());
    SQLiteDatabase db=
      SQLiteDatabase.openDatabase(originalFile.getAbsolutePath(),
        "", null, SQLiteDatabase.OPEN_READWRITE);
    int version=db.getVersion();

    db.close();

    db=SQLiteDatabase.openDatabase(newFile.getAbsolutePath(), passphrase,
      null, SQLiteDatabase.OPEN_READWRITE, null, null);

    final SQLiteStatement st=db.compileStatement("ATTACH DATABASE ? AS plaintext KEY ''");

    st.bindString(1, originalFile.getAbsolutePath());
    st.execute();

    db.rawExecSQL("SELECT sqlcipher_export('main', 'plaintext')");
    db.rawExecSQL("DETACH DATABASE plaintext");
    db.setVersion(version);
    st.close();
    db.close();

    originalFile.delete();
    newFile.renameTo(originalFile);
  }
  else {
    throw new FileNotFoundException(originalFile.getAbsolutePath()+" not found");
  }
}
 
Example 7
Source File: SQLCipherUtils.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * Replaces this database with a decrypted version, deleting the original
 * encrypted database. Do not call this while the database is open, which
 * includes during any Room migrations.
 *
 * The passphrase is untouched in this call. Please set all bytes of the
 * passphrase to 0 or something to clear out the passphrase if you are done
 * with it.
 *
 * @param ctxt a Context
 * @param originalFile a File pointing to the encrypted database
 * @param passphrase the passphrase from the user for the encrypted database
 * @throws IOException
 */
public static void decrypt(Context ctxt, File originalFile, byte[] passphrase)
  throws IOException {
  SQLiteDatabase.loadLibs(ctxt);

  if (originalFile.exists()) {
    File newFile=
      File.createTempFile("sqlcipherutils", "tmp",
        ctxt.getCacheDir());
    SQLiteDatabase db=
      SQLiteDatabase.openDatabase(originalFile.getAbsolutePath(),
        passphrase, null, SQLiteDatabase.OPEN_READWRITE, null, null);

    final SQLiteStatement st=db.compileStatement("ATTACH DATABASE ? AS plaintext KEY ''");

    st.bindString(1, newFile.getAbsolutePath());
    st.execute();

    db.rawExecSQL("SELECT sqlcipher_export('plaintext')");
    db.rawExecSQL("DETACH DATABASE plaintext");

    int version=db.getVersion();

    st.close();
    db.close();

    db=SQLiteDatabase.openDatabase(newFile.getAbsolutePath(), "",
      null, SQLiteDatabase.OPEN_READWRITE);
    db.setVersion(version);
    db.close();

    originalFile.delete();
    newFile.renameTo(originalFile);
  }
  else {
    throw new FileNotFoundException(originalFile.getAbsolutePath()+" not found");
  }
}
 
Example 8
Source File: UserSandboxUtils.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
/**
 * Make a copy of the incoming sandbox's database and re-key it to use the new key.
 */
private static String rekeyDB(Context c, UserKeyRecord incomingSandbox, UserKeyRecord newSandbox,
                              byte[] unwrappedOldKey, byte[] unwrappedNewKey)
        throws IOException {
    File oldDb = c.getDatabasePath(DatabaseUserOpenHelper.getDbName(incomingSandbox.getUuid()));
    File newDb = c.getDatabasePath(DatabaseUserOpenHelper.getDbName(newSandbox.getUuid()));

    //TODO: Make sure old sandbox is already on newest version?
    if (newDb.exists()) {
        if (!newDb.delete()) {
            throw new IOException("Couldn't clear file location " + newDb.getAbsolutePath() + " for new sandbox database");
        }
    }

    FileUtil.copyFile(oldDb, newDb);

    Logger.log(LogTypes.TYPE_MAINTENANCE, "Created a copy of the DB for the new sandbox. Re-keying it...");

    String oldKeyEncoded = getSqlCipherEncodedKey(unwrappedOldKey);
    String newKeyEncoded = getSqlCipherEncodedKey(unwrappedNewKey);
    SQLiteDatabase rawDbHandle = SQLiteDatabase.openDatabase(newDb.getAbsolutePath(), oldKeyEncoded, null, SQLiteDatabase.OPEN_READWRITE);

    rawDbHandle.execSQL("PRAGMA key = '" + oldKeyEncoded + "';");
    rawDbHandle.execSQL("PRAGMA rekey  = '" + newKeyEncoded + "';");
    rawDbHandle.close();
    return newKeyEncoded;
}