You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android Kotlin项目中集成SQLCipher v4.5.4最新版本

Android 集成 SQLCipher v4.5.4 实操指南

一、依赖配置

  1. 确保项目仓库包含Maven Central(AGP 7.0+ 配置在settings.gradle,旧版本在根目录build.gradle):
    repositories {
        mavenCentral()
    }
    
  2. 在app模块的build.gradle中添加依赖:
    dependencies {
        implementation 'net.zetetic:android-database-sqlcipher:4.5.4'
        implementation 'androidx.sqlite:sqlite-framework:2.3.0' // 适配AndroidX,推荐添加
    }
    

二、数据库文件路径获取

根据存储需求选择合适的路径,以下是三种常用场景:

1. 内部私有存储(推荐)

仅当前应用可访问,卸载应用时自动清理,无需权限:

// 获取数据库文件的父目录
File dbParentDir = getApplicationContext().getDatabasePath("my_encrypted_db.db").getParentFile();
// 确保目录存在
if (!dbParentDir.exists()) {
    dbParentDir.mkdirs();
}
// 完整数据库文件对象
File dbFile = new File(dbParentDir, "my_encrypted_db.db");

2. 应用专属外部存储(API 19+)

属于外部存储但仅当前应用可访问,卸载时自动清理,无需权限:

File appExternalDir = getApplicationContext().getExternalFilesDir(null);
File dbDir = new File(appExternalDir, "EncryptedDB");
if (!dbDir.exists()) {
    dbDir.mkdirs();
}
File dbFile = new File(dbDir, "my_encrypted_db.db");

3. 外部公共存储(需权限)

其他应用可访问,卸载应用不会删除,需申请WRITE_EXTERNAL_STORAGE权限(Android 13+ 需对应细分媒体权限):

File publicDocsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File dbDir = new File(publicDocsDir, "MyAppDB");
if (!dbDir.exists()) {
    dbDir.mkdirs();
}
File dbFile = new File(dbDir, "my_encrypted_db.db");

三、初始化与使用加密数据库

import net.sqlcipher.database.SQLiteDatabase;
import net.sqlcipher.database.SQLiteOpenHelper;

// 必须先加载SQLCipher原生库,建议在Application启动时调用
SQLiteDatabase.loadLibs(getApplicationContext());

// 自定义数据库帮助类
public class EncryptedDBHelper extends SQLiteOpenHelper {
    private static final String DB_NAME = "my_encrypted_db.db";
    private static final int DB_VERSION = 1;
    private final String dbPassword;

    public EncryptedDBHelper(Context context, String password) {
        super(context, DB_NAME, null, DB_VERSION);
        this.dbPassword = password;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // 创建示例表
        db.execSQL("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY AUTOINCREMENT, content TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 版本升级逻辑,比如新增字段
        if (oldVersion < 2) {
            db.execSQL("ALTER TABLE notes ADD COLUMN create_time INTEGER");
        }
    }

    // 重写获取数据库方法,传入加密密码
    @Override
    public SQLiteDatabase getWritableDatabase() {
        return super.getWritableDatabase(dbPassword);
    }

    @Override
    public SQLiteDatabase getReadableDatabase() {
        return super.getReadableDatabase(dbPassword);
    }
}

// 调用示例
EncryptedDBHelper dbHelper = new EncryptedDBHelper(getApplicationContext(), "your_strong_password");
SQLiteDatabase db = dbHelper.getWritableDatabase();

// 插入数据示例
ContentValues values = new ContentValues();
values.put("content", "Hello SQLCipher v4.5.4");
db.insert("notes", null, values);

// 关闭数据库
db.close();

四、兼容旧版本SQLCipher(可选)

如果需要兼容v3版本的加密数据库,打开时需指定兼容模式:

SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile, "your_password", null, 
    SQLiteDatabase.OPEN_READWRITE | SQLiteDatabase.CREATE_IF_NECESSARY,
    new SQLiteDatabaseHook() {
        @Override
        public void preKey(SQLiteDatabase db) {
            db.execSQL("PRAGMA cipher_compatibility = 3;");
        }

        @Override
        public void postKey(SQLiteDatabase db) {}
    });

内容的提问来源于stack exchange,提问作者Dhana_prakash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 15:54:59