如何加密Android SQLite数据库中的特定列数据。使用SQLCipher实用程序

时间:2015-05-25 04:48:09

标签: android database encryption sqliteopenhelper sqlcipher

我在android中有一个SQLite DB,我想只加密该DB中的几列。我发现它可用整个数据库进行加密,但我只需要加密几列数据。

2 个答案:

答案 0 :(得分:2)

您可以使用此类加密和解密数据:

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import android.util.Base64;

public class SimpleCrypto {

    private String charsetName = "UTF8";
    private String algorithm = "DES";
    private int base64Mode = Base64.DEFAULT;

    public String getCharsetName() {
        return charsetName;
    }

    public void setCharsetName(String charsetName) {
        this.charsetName = charsetName;
    }

    public String getAlgorithm() {
        return algorithm;
    }

    public void setAlgorithm(String algorithm) {
        this.algorithm = algorithm;
    }

    public int getBase64Mode() {
        return base64Mode;
    }

    public void setBase64Mode(int base64Mode) {
        this.base64Mode = base64Mode;
    }

    public String encrypt(String key, String data) {
        if (key == null || data == null)
            return null;
        try {
            DESKeySpec desKeySpec = new DESKeySpec(key.getBytes(charsetName));
            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
            SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);
            byte[] dataBytes = data.getBytes(charsetName);
            Cipher cipher = Cipher.getInstance(algorithm);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return Base64.encodeToString(cipher.doFinal(dataBytes), base64Mode);
        } catch (Exception e) {
            return null;
        }
    }

    public String decrypt(String key, String data) {
        if (key == null || data == null)
            return null;
        try {
            byte[] dataBytes = Base64.decode(data, base64Mode);
            DESKeySpec desKeySpec = new DESKeySpec(key.getBytes(charsetName));
            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
            SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);
            Cipher cipher = Cipher.getInstance(algorithm);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] dataBytesDecrypted = (cipher.doFinal(dataBytes));
            return new String(dataBytesDecrypted);
        } catch (Exception e) {
            return null;
        }
    }
}

您可以像这样加密数据:

private SimpleCrypto simpleCrypto = new SimpleCrypto();

String MasterPassword = "qssfFs32fFwada";

String encryptedText = simpleCrypto.encrypt(MasterPassword, "Hello World");
Log.i(encryptedText, encryptedText);

然后你可以像这样解密它们:

String decryptedText = decrypt(MasterPassword, encryptedText);
Log.i(decryptedText, decryptedText);

答案 1 :(得分:2)

您无法使用SQLCipher执行此操作。 SQLCipher加密数据库的全部内容,包括模式和数据。如果您仍然对在Android应用程序中使用SQLCipher感兴趣,我们提供了集成here的教程。