吉安感知网项目-后端
xiebin
2026-01-06 d207a86cdf1ab52ef8cb7cd83bad8fceab8038cf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package org.sxkj.common.utils;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
 
public class DbEncrypt {
    /**
     * 使用 SQLCipher 对数据库进行加密
     *
     * @param originalDbPath 原始未加密数据库的路径
     * @param newDbPath 新加密数据库的存储路径
     * @param newDbPassword 新加密数据库的密码
     * @return 加密是否成功
     */
    public static boolean encryptDatabase(String originalDbPath, String newDbPath, String newDbPassword) {
        try {
            // SQLCipher命令
            String[] command = {
                "sqlcipher", originalDbPath,
                "-cmd", "PRAGMA key='';",  // 空密钥,用于未加密的原数据库
                "-cmd", String.format("ATTACH DATABASE '%s' AS encrypted KEY '%s';", newDbPath, newDbPassword),
                "-cmd", "SELECT sqlcipher_export('encrypted');",
                "-cmd", "DETACH DATABASE encrypted;",
                "-cmd", ".exit"
            };
 
            // 执行命令
            Process process = Runtime.getRuntime().exec(command);
 
            // 读取命令行输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
 
            // 等待命令执行完成
            process.waitFor();
            reader.close();
 
            // 检查执行结果
            int exitCode = process.exitValue();
            return exitCode == 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}