package moduly.file.cruptlog;



import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;


public class CryptLog {

    // реальзовать функцию криптовки лога
    public static void cryptZipArchive(String inputZipFile, String outputZipFile, String key) throws Exception {

        byte[] iv = new byte[16]; // Initialization Vector
        SecretKey secretKey = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);

        try (ZipInputStream zipIn = new ZipInputStream(new FileInputStream(inputZipFile));
             ZipOutputStream zipOut = new ZipOutputStream(new CipherOutputStream(new FileOutputStream(outputZipFile), cipher))) {
            ZipEntry entry;
            while ((entry = zipIn.getNextEntry()) != null) {
                zipOut.putNextEntry(new ZipEntry(entry.getName()));
                byte[] buffer = new byte[1024];
                int len;
                while ((len = zipIn.read(buffer)) > 0) {
                    zipOut.write(buffer, 0, len);
                }
                zipOut.closeEntry();
            }
        }
        // удаляем старый просто zip архив
        new File(inputZipFile).delete();
    }

}
