android aes加密解密文件
时间: 2023-10-14 13:06:55 浏览: 140
好的,这里是一个简单的示例,展示了如何在 Android 中使用 AES 加密和解密文件:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.MessageDigest;
import java.util.Arrays;
public class AesUtil {
private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
private static final String SECRET_KEY = "my_secret_key";
private static final String IV = "my_initialization_vector";
public static void encrypt(String inputFile, String outputFile) throws Exception {
SecretKeySpec secretKeySpec = generateKey(SECRET_KEY);
IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes("UTF-8"));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
byte[] output = cipher.update(buffer, 0, bytesRead);
if (output != null) {
outputStream.write(output);
}
}
byte[] output = cipher.doFinal();
if (output != null) {
outputStream.write(output);
}
inputStream.close();
outputStream.close();
}
public static void decrypt(String inputFile, String outputFile) throws Exception {
SecretKeySpec secretKeySpec = generateKey(SECRET_KEY);
IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes("UTF-8"));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
byte[] output = cipher.update(buffer, 0, bytesRead);
if (output != null) {
outputStream.write(output);
}
}
byte[] output = cipher.doFinal();
if (output != null) {
outputStream.write(output);
}
inputStream.close();
outputStream.close();
}
private static SecretKeySpec generateKey(String key) throws Exception {
byte[] keyBytes = key.getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-256");
keyBytes = sha.digest(keyBytes);
keyBytes = Arrays.copyOf(keyBytes, 16);
return new SecretKeySpec(keyBytes, "AES");
}
}
```
在此示例中,我们使用 AES/CBC/PKCS5Padding 加密模式和 SHA-256 哈希算法生成密钥。我们将密钥和初始向量 IV 保存为常量,但您可以根据需要进行更改。
要使用此示例,请在您的代码中调用 `AesUtil.encrypt(inputFile, outputFile)` 或 `AesUtil.decrypt(inputFile, outputFile)` 方法,其中 `inputFile` 是要加密或解密的文件路径,而 `outputFile` 是加密或解密后的文件路径。
请注意,此示例中的加密和解密操作是阻塞的,并且使用了相对较小的缓冲区。对于大文件和需要异步处理的情况,您需要进行适当的优化。
阅读全文