package admin.cryptor;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Optional;

public class Crupt {
    public String cryptor(String algorithm, String input, SecretKey key,
                        IvParameterSpec iv) throws Exception {

        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);
        byte[] cipherText = cipher.doFinal(input.getBytes());
        String base64 = Base64.getEncoder()
                .encodeToString(cipherText);

        String i = Optional.ofNullable(base64)
                .filter(str -> str.length() != 0)
                .map(str -> str.substring(0, str.length() - 1))
                .orElse(base64);

        String rez = Optional.ofNullable(i)
                .filter(str -> str.length() != 0)
                .map(str -> str.substring(0, str.length() - 1))
                .orElse(i);
        return rez;
    }

    public String encryptBase64(String input) {
        byte[] encodedBytes = input.getBytes();
        String enc = Base64.getEncoder().encodeToString(encodedBytes);
        return enc;
    }
}
