在Android中,SharedPreferences本身不提供内置的数据加密功能。但是,您可以在将数据存储到SharedPreferences之前对其进行加密,并在从SharedPreferences读取数据时进行解密。以下是一个使用AES加密和解密的示例:
首先,您需要添加加密库,例如:
implementation 'com.google.crypto:crypto-commons:1.1.1'
然后,您可以使用以下代码进行加密和解密:
import android.content.Context;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class EncryptionHelper {
private static final String KEY_ALIAS = "my_key_alias";
private static final String TRANSFORMATION = "AES";
public static SecretKey getSecretKey(Context context) throws NoSuchAlgorithmException, UnrecoverableKeyException {
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
if (!keyStore.containsAlias(KEY_ALIAS)) {
KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
KeyGenParameterSpec keyGenParameterSpec = new KeyGenParameterSpec.Builder(
KEY_ALIAS, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build();
keyGenerator.init(keyGenParameterSpec);
keyGenerator.generateKey();
}
return (SecretKey) keyStore.getKey(KEY_ALIAS, null);
}
public static String encrypt(String data, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedData, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedData);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
现在,您可以使用EncryptionHelper
类来加密和解密数据:
try {
Context context = getApplicationContext();
SecretKey secretKey = EncryptionHelper.getSecretKey(context);
String originalData = "Hello, World!";
String encryptedData = EncryptionHelper.encrypt(originalData, secretKey);
String decryptedData = EncryptionHelper.decrypt(encryptedData, secretKey);
System.out.println("Original Data: " + originalData);
System.out.println("Encrypted Data: " + encryptedData);
System.out.println("Decrypted Data: " + decryptedData);
} catch (Exception e) {
e.printStackTrace();
}
请注意,这个示例使用了Android KeyStore系统来生成和存储密钥。这样,即使设备受到攻击,密钥也不会轻易泄露。