Android提供了File Encryption和Folder Encryption的API,可以使用这些API来保护用户的数据。通过使用加密技术,文件和文件夹中的数据可以被保护,只有授权的用户才能访问它们。
以下是一些示例代码来演示如何使用这些API:
使用CipherInputStream和CipherOutputStream来实现文件加密和解密。以下是一个示例代码:
public static void encryptFile(String inputPath, String outputPath, String password) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
FileInputStream inputStream = new FileInputStream(inputPath);
FileOutputStream outputStream = new FileOutputStream(outputPath);
SecretKeySpec keySpec = new SecretKeySpec(password.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
byte[] buffer = new byte[1024];
int numRead = 0;
while ((numRead = inputStream.read(buffer)) >= 0) {
cipherOutputStream.write(buffer, 0, numRead);
}
cipherOutputStream.close();
inputStream.close();
}
public static void decryptFile(String inputPath, String outputPath, String password) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
FileInputStream inputStream = new FileInputStream(inputPath);
FileOutputStream outputStream = new FileOutputStream(outputPath);
SecretKeySpec keySpec = new SecretKeySpec(password.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec);
CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
byte[] buffer = new byte[1024];
int numRead = 0;
while ((numRead = cipherInputStream.read(buffer)) >= 0) {
outputStream.write(buffer, 0, numRead);
}
outputStream.close();
cipherInputStream.close();
}
使用递归方法来遍历文件夹中的所有文件,并对它们进行加密和解密。以下是一个示例代码:
public static void encryptFolder(String inputPath, String