gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 07:54:16 26 4
gpt4 key购买 nike

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

最佳答案

你可以使用这个类来加密和解密你的数据:

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);

关于android - 我如何加密 Android SQLite 数据库中的特定列数据。使用 SQLCipher 实用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30431400/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com