Java AES 加解密文件

27 阅读1分钟

使用 Java AES 128 加解密文件

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.Key;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.spec.SecretKeySpec;

// AES128 加解密文件
public class AESEncryptionUtil {

    public static void main(String[] args) throws Exception{
        String inputFile = "hello.jpg"; // 替换成要加密的文件路径
        String encryptedFile = "hello_encry.jpg"; // 替换成加密后的文件输出路径
        String decryptedFile = "hello_decrypt.jpg"; // 替换成解密后的文件输出路径
        String key = "Isgh2_c^&@uvAIK4"; // 密钥长度16位 替换成你的加密密钥

       AESEncryptionUtil.encryptFile(inputFile, encryptedFile, key);
       AESEncryptionUtil.decryptFile(encryptedFile, decryptedFile, key);
       System.out.println("文件加密解密成功!");
  }

  private static final String ALGORITHM = "AES";
  private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";

  private static Key generateKey(byte[] keyValue) {
    return new SecretKeySpec(keyValue, ALGORITHM);
  }

  public static void encryptFile(String inputFile, String outputFile, String key) {
    Cipher cipher = getCipher(key);

    try (FileInputStream inputStream = new FileInputStream(inputFile);
         FileOutputStream outputStream = new FileOutputStream(outputFile)) {
      byte[] buffer = new byte[1024];
      int bytesRead;
      while ((bytesRead = inputStream.read(buffer)) != -1) {
        byte[] encryptedBytes = cipher.update(buffer, 0, bytesRead);
        outputStream.write(encryptedBytes);
      }
      byte[] encryptedBytes = cipher.doFinal();
      outputStream.write(encryptedBytes);
    } catch (IOException | IllegalBlockSizeException | BadPaddingException e) {
      throw new RuntimeException("加密失败");
    }
  }

  public static void decryptFile(String inputFile, String outputFile, String key) {
    Cipher cipher = getCipher(key);

    try (FileInputStream inputStream = new FileInputStream(inputFile);
         FileOutputStream outputStream = new FileOutputStream(outputFile)) {
      byte[] buffer = new byte[1024];
      int bytesRead;
      while ((bytesRead = inputStream.read(buffer)) != -1) {
        byte[] decryptedBytes = cipher.update(buffer, 0, bytesRead);
        outputStream.write(decryptedBytes);
      }
      byte[] decryptedBytes = cipher.doFinal();
      outputStream.write(decryptedBytes);
    } catch (IOException | IllegalBlockSizeException | BadPaddingException e) {
      throw new RuntimeException("解密失败");
    }
  }

  private static Cipher getCipher(String key) {
    byte[] keyValue = key.getBytes();
    Key secretKey = generateKey(keyValue);
    Cipher cipher = null;
    try {
      cipher = Cipher.getInstance(TRANSFORMATION);
      cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    } catch (Exception e) {
      throw new RuntimeException("密钥错误");
    }
    return cipher;
  }

}