SQLCipher android database encryption

After the introduction of SQLCipher in the project, the size of your program will suddenly increase, and it will probably become several megabytes larger after being converted into an APK. Whether it is more focused on file size or more focused on program security, you should make appropriate adjustments according to specific needs. judgment.

The manifest configuration write file permission because copy the database file to the created directory
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


module 下的build.gradle
compile 'net.zetetic:android-database-sqlcipher:3.5.3@aar'


application or the activity you are currently using first add this sentence
SQLiteDatabase.loadLibs(this);


Create a MyDatabaseHelper
public class MyDatabaseHelper extends SQLiteOpenHelper {       
    public static final String CREATE_TABLE = "create table Book(name text, pages integer)";    
    public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }      
    @Override      
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE);
    }      
    @Override     
    public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
    }
}


key code activity
public class MainActivity extends AppCompatActivity {

    private SQLiteDatabase db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
//Because many mobile phones have not been rooted, you can't find your db file and copy it to view it. At this time, you need to manually create a directory    
       createSdcardFolder();
        setContentView(R.layout.main);
        SQLiteDatabase.loadLibs(this);
        MyDatabaseHelper dbHelper = new MyDatabaseHelper(this, "cipher.db", null, 1);
        db = dbHelper.getWritableDatabase("secret_key");
        Button addData = (Button) findViewById(R.id.add_data);
        Button queryData = (Button) findViewById(R.id.query_data);
        addData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ContentValues values = new ContentValues();
                values.put("name", "The Da Vinci Code");
                values.put("pages", 566);
                db.insert("Book", null, values);
            }
        });
        queryData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Cursor cursor = db.query("Book", null, null, null, null, null, null);
                if (cursor != null) {
                    while (cursor.moveToNext()) {
                        String name = cursor.getString(cursor.getColumnIndex("name"));
                        int pages = cursor.getInt(cursor.getColumnIndex("pages"));
                        Log.d("TAG", "book name is " + name);
                        Log.d("TAG", "book pages is " + pages);
                    }
                }
                cursor.close();
            }
        });
//copy out the database file
    copyfile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                copyDatabaseToSdcard(MainActivity.this);
            }
        });
    }
  /** * Create SdcardFolder */
    public void createSdcardFolder(){
        if(SDCardUtils.isSDCardEnable()){
            File file =null;
            file = new File(String.format("%s%s",SDCardUtils.getSDCardPath(), "/cliper/temp"));
            if(!file.exists()){//Determine whether there is a directory on the sdcard card, and generate a directory if there is no directory
                file.mkdirs();
            }
        }
    }
/** * Copy database files */
   public static void copyDatabaseToSdcard(Context context){
        copyDatabaseToSdcard(context,"dbfile");
    }
/** * Copy database files */
public static void copyDatabaseToSdcard(Context context,String name){
        try {
            File file = context.getDatabasePath("cipher.db");
            FileUtil.writeFile(new FileInputStream(file.getAbsolutePath()), SDCardUtils.getSDCardPath()
                    +"/cipher/temp" + "/"+name);
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }
}


After the database is encrypted, the tool cannot be opened. This is enough to show that the data in the database is very safe at present, and the data in the database can only be accessed through the API provided by SQLCipher in the application program, and the data cannot be obtained by other methods.


Create a directory
/**
   * Create SdcardFolder
   */

     public void createSdcardFolder(){
      if(SDCardUtils.isSDCardEnable()){
          File file =null;
          file = new File(String.format("%s%s",SDCardUtils.getSDCardPath(), "/cipher/temp"));
          if(!file.exists()){
              file.mkdirs();
          }
      }
  }


SDCardUtils
public static String getSDCardPath(){
   return Environment.getExternalStorageDirectory().toString();
  }


FileUtil
public final static void writeFile(InputStream input, String fileName) throws IOException {
      writeFile(input, new FileOutputStream(fileName));
  }
public final static void writeFile(InputStream input, OutputStream os) throws IOException
{  
     byte[] bs = new byte[1024]; // set data buffer  
      int len; // length of data read
      while ((len = input.read(bs)) != -1) {   
     os.write(bs, 0, len);   }  
     os.close();  
     input.close();
}


The mistakes I have experienced myself:
1. You must first make sure that your phone does not have the db file you have built now, otherwise it will tell you that you cannot encrypt this file:


2. I used the eclipse configuration method in as but not in the build In the .gradle file, configure the eclipse configuration. These so files, jar packages, and zip files must have
sourceSets {
        main {
            manifest.srcFile 'src/main/AndroidManifest.xml'
            java.srcDirs = ['src/main/java']
            res.srcDirs = ['src/main/res']
            assets.srcDirs = ['assets']
            jniLibs.srcDirs = ['libs']
        }
    }



Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326607892&siteId=291194637