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
)的安全性,因为它是解密文件所必需的。