package org.security.common.utils;

import org.apache.commons.io.IOUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class InputStreamAESUtil {
    // 加密盐
    private static final String key = "mb69ZaWX7NhdsbJR";
    // 加密向量
    private static final String initVector = "fquxS65OPV9WEOgx";

    public static InputStream encryptStream(InputStream is) throws Exception {
        byte[] nonEncryptedByteArray = IOUtils.toByteArray(is);
        IvParameterSpec iv = new IvParameterSpec(initVector.getBytes(StandardCharsets.UTF_8));
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        byte[] encryptedByteArray = cipher.doFinal(nonEncryptedByteArray);
        return new ByteArrayInputStream(encryptedByteArray);
    }

    public static InputStream decryptStream(InputStream is) throws Exception {
        byte[] encryptToDecryptByteArray = IOUtils.toByteArray(is);
        IvParameterSpec iv = new IvParameterSpec(initVector.getBytes(StandardCharsets.UTF_8));
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        byte[] decryptedByteArray = cipher.doFinal(encryptToDecryptByteArray);
        return new ByteArrayInputStream(decryptedByteArray);
    }
}
