package com.mcwl.web.controller.resource;

import com.mcwl.web.controller.common.OssUtil;
import org.springframework.mock.web.MockMultipartFile;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.AlgorithmParameters;
import java.util.Base64;

/**
 * 加解密文件工具类
 * @author DaiZibo
 * @date 2025/1/25
 * @apiNote
 */

public class FileEncryptDecryptUtil {

    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    private static final String TRANSFORMATION = "AES";
    private static final String KEY = "iamkeyeeddzasdfs"; // 实际应用中应使用更安全的密钥生成方式
    private static byte[] SAVED_IV; // 静态变量存储IV，确保解密时可访问

    public static void main(String[] args) throws Exception {
// 示例：加密文件
        encryptFile("D:\\ASE\\encryption\\测试文件1.txt", "D:\\ASE\\decode\\加密测试文件1.txt");
//// 解密文件
        decryptFile("C:\\Users\\Dzb\\Desktop\\a.enc", "D:\\\\ASE\\\\encryption\\\\解密测试文件2.txt");
        uploadEncryptedFileToOSS("D:\\ASE\\encryption\\测试文件1.txt", "encrypted-test-file1.enc");

    }

    public static void encryptFile(String sourcePath, String encryptedPath) throws Exception {
        Cipher cipher = initCipher(Cipher.ENCRYPT_MODE);
        try (FileInputStream fis = new FileInputStream(sourcePath);
             FileOutputStream fos = new FileOutputStream(encryptedPath);
             CipherOutputStream cos = new CipherOutputStream(fos, cipher)) {
            byte[] buffer = new byte[1024];
            int read;
            while ((read = fis.read(buffer)) != -1) {
                cos.write(buffer, 0, read);
            }
        }
        System.out.println("加密完成");
    }

    public static void decryptFile(String encryptedPath, String decryptedPath) throws Exception {
        Cipher cipher = initCipher(Cipher.DECRYPT_MODE);
        try (FileInputStream fis = new FileInputStream(encryptedPath);
             CipherInputStream cis = new CipherInputStream(fis, cipher);
             FileOutputStream fos = new FileOutputStream(decryptedPath)) {
            byte[] buffer = new byte[1024];
            int read;
            while ((read = cis.read(buffer)) != -1) {
                fos.write(buffer, 0, read);
            }
        }
        System.out.println("解密完成");
    }

    private static Cipher initCipher(int mode) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKey secretKey = new SecretKeySpec(KEY.getBytes(), TRANSFORMATION);
        if (mode == Cipher.ENCRYPT_MODE && SAVED_IV == null) {
            cipher.init(mode, secretKey);
            AlgorithmParameters params = cipher.getParameters();
            SAVED_IV = params.getParameterSpec(IvParameterSpec.class).getIV();
            System.out.println("Generated IV: " + Base64.getEncoder().encodeToString(SAVED_IV));
        } else {
            cipher.init(mode, secretKey, new IvParameterSpec(SAVED_IV));
        }
        return cipher;
    }


    public static void uploadEncryptedFileToOSS(String sourcePath, String ossFileName) throws Exception {
        Cipher cipher = initCipher(Cipher.ENCRYPT_MODE);

        // 使用ByteArrayOutputStream代替FileOutputStream
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try (FileInputStream fis = new FileInputStream(sourcePath);
             CipherInputStream cis = new CipherInputStream(fis, cipher)) {
            byte[] buffer = new byte[1024];
            int read;
            while ((read = cis.read(buffer)) != -1) {
                bos.write(buffer, 0, read);
            }
        }
        System.out.println("加密完成");

        // 将加密后的字节数组转换为MultipartFile
        MockMultipartFile multipartFile = new MockMultipartFile(ossFileName, ossFileName, "application/octet-stream", bos.toByteArray());
        // 调用上传方法
        String s = OssUtil.uploadMultipartFile(multipartFile);
        System.out.println("文件已上传至: " + s);
    }
}
