存储身份证正反面,认证文件等用的工具类,存储在oss中是不可以直接查看的图片文件,需要经过解密才行
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class ImageEncryptionExample {
public static void main(String[] args) {
String originalImagePath = "E:\\1.jpg";
String encryptedImagePath = "E:\\2.jpg";
String decryptedImagePath = "E:\\3.jpg";
String key = "WxappEncrypteKey"; // 密钥,必须是16个字符长度的字符串
try {
// 读取原始图片
byte[] originalImageBytes = Files.readAllBytes(Paths.get(originalImagePath));
// 加密图片
byte[] encryptedImageBytes = encrypt(originalImageBytes, key);
// 将加密后的图片保存到文件
Files.write(Paths.get(encryptedImagePath), encryptedImageBytes);
// 读取加密后的图片
byte[] encryptedImageBytesFromFile = Files.readAllBytes(Paths.get(encryptedImagePath));
// 解密图片
byte[] decryptedImageBytes = decrypt(encryptedImageBytesFromFile, key);
// 将解密后的图片保存到文件
Files.write(Paths.get(decryptedImagePath), decryptedImageBytes);
System.out.println("图片加密解密完成!");
} catch (IOException | NoSuchAlgorithmException | NoSuchPaddingException |
InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
}
}
private static byte[] encrypt(byte[] input, String key) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
SecretKey secretKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return cipher.doFinal(input);
}
private static byte[] decrypt(byte[] input, String key) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
SecretKey secretKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return cipher.doFinal(input);
}
}