package com.hdkj.lt.utils.encrypt;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @Description:
 * @Author: wenhao
 * @Create: 2022/10/19 13:48
 * @Version: 1.0
 */
public class AESUtils {

    private AESUtils() {
    }

    /**
     * Cipher初始化
     *
     * @param sKey
     * @param cipherMode
     * @return
     */
    public static Cipher initAESCipher(String sKey, int cipherMode) {
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(sKey.getBytes(), "AES");
            cipher.init(cipherMode, keySpec);
        } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException e) {
            e.printStackTrace();
        }
        return cipher;
    }

    /**
     * 加密
     *
     * @param is
     * @param os
     * @param cipher
     */
    public static void encrypt(InputStream is, OutputStream os, Cipher cipher) {
        try (CipherInputStream cis = new CipherInputStream(is, cipher);
             BufferedOutputStream bos = new BufferedOutputStream(os)) {
            byte[] cache = new byte[1024];
            int readLine;
            while ((readLine = cis.read(cache)) != -1) {
                bos.write(cache, 0, readLine);
            }
            bos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
