在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系統來生成和存儲密鑰。這樣,即使設備受到攻擊,密鑰也不會輕易泄露。