getFilesDir()
方法用于獲取應用內部存儲的目錄,這個目錄下的文件默認是加密存儲的
如果你需要加密存儲文件,可以使用 Cipher
類來實現加密和解密操作。以下是一個簡單的示例:
import android.util.Base64;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class EncryptionUtil {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";
private static final String CHARSET = "UTF-8";
public static String encrypt(String data, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(CHARSET), ALGORITHM);
IvParameterSpec ivParameterSpec = new IvParameterSpec(new byte[16]);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encryptedData = cipher.doFinal(data.getBytes(CHARSET));
return Base64.encodeToString(encryptedData, Base64.DEFAULT);
}
public static String decrypt(String data, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(CHARSET), ALGORITHM);
IvParameterSpec ivParameterSpec = new IvParameterSpec(new byte[16]);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decodedData = Base64.decode(data, Base64.DEFAULT);
return new String(cipher.doFinal(decodedData), CHARSET);
}
}
使用這個工具類,你可以在 getFilesDir()
目錄下加密和解密文件。但請注意,你需要確保密鑰(key
)的安全性,因為它是解密文件所必需的。