package com.javarush.task.task18.task1826;

/*
Шифровка
*/

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;

public class Solution {

    public static void main(String[] args) {

        if (args.length == 0 || args.length == 1 || args.length == 2 && (args[0] != "-e" || args[0] != "-d")) {
            return;
        }
        String fileInputName = args[1];
        String fileOutputName = args[2];
        byte[] decodedKey = Base64.getDecoder().decode("fVv4DXYPFIYqXiSo".getBytes());
        SecretKeySpec key = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
        byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        try (FileInputStream fileInputStream = new FileInputStream(fileInputName);
             BufferedOutputStream fileOutputStream = new BufferedOutputStream(
                     new FileOutputStream(fileOutputName));) {
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            encryptCipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
            Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            decryptCipher.init(Cipher.DECRYPT_MODE, key, ivSpec);

            byte[] bytes = new byte[fileInputStream.available()];
            while (fileInputStream.available() > 0) {
                fileInputStream.read(bytes);
            }
            if (args[0].equals("-e")) {
                byte[] finale = Base64.getEncoder().encode(encryptCipher.doFinal(bytes));
                fileOutputStream.write(finale);

            }

            if (args[0].equals("-d")) {
                byte[] finale = decryptCipher.doFinal(Base64.getEncoder().encode(bytes));
                fileOutputStream.write(finale);
            }
        } catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException | BadPaddingException | IllegalBlockSizeException | IOException e) {
            e.printStackTrace();
        }
    }
}