import android.os.Build;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.util.Log;
import androidx.annotation.RequiresApi;
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AesEncryptorUtils {
// 加密MP4文件
public static void encryptVideo(File inputFile, File outputFile) throws Exception {
Log.i("xxxxxx", "encryptVideo: ");
String key2 = "1234567890123456"; // 16 bytes for AES-128
String initVector = "RandomInitVector";
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key2.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//AES/CBC/PKCS5Padding
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
Log.i("xxxx", " 1111111");
// 将IV写入文件头部(16字节)
try (FileOutputStream fos = new FileOutputStream(outputFile);
FileInputStream fis = new FileInputStream(inputFile)) {
Log.i("xxxx", " 2222222222");
fos.write(cipher.getIV()); // 保存IV
try (CipherOutputStream cos = new CipherOutputStream(fos, cipher)) {
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
cos.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
Log.i("xxxx", " 44444444");
}
} catch (Exception e) {
Log.i("xxxx", " 5555555555555");
}
Log.i("xxxxxx", "66666666666666 ");
}
// 解密MP4文件
public static void decryptVideo(File inputFile, File outputFile) throws Exception {
try (FileInputStream fis = new FileInputStream(inputFile);
FileOutputStream fos = new FileOutputStream(outputFile)) {
// 从文件头部读取IV
String key2 = "1234567890123456"; // 16 bytes for AES-128
String initVector = "RandomInitVector";
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key2.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//AES/CBC/PKCS5Padding
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
Log.i("xxxxxx", "777777 ");
try (CipherInputStream cis = new CipherInputStream(fis, cipher)) {
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = cis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
}
}
Log.i("xxxxxx", "8888888888888 ");
}
}
方法调用:
private void aesEncryptor() {
try {
File origVideo = new File(path);
File encryptedVideo = new File(encryptedVideoPath);
File decryptedVideo = new File(decryptVideoPath);
// 加密原视频
// AesEncryptorUtils.encryptVideo(origVideo, encryptedVideo);
// 解密视频
AesEncryptorUtils.decryptVideo(encryptedVideo, decryptedVideo);
} catch (Exception e) {
e.printStackTrace();
}
}