package com.jscape.util.io;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import static com.jscape.util.Parameters.assertNotNull;

/**
 * @author Alex Usun
 */
public class JceStreamProtectionService
        implements StreamProtectionService {

    //    private static final String ALGORITHM_TEMPLATE = "%s/CFB8/NoPadding";
    private static final String ALGORITHM_TEMPLATE = "%s/CBC/PKCS5Padding";

    private final String algorithm;
    private final byte[] key;

    public JceStreamProtectionService(String algorithm, byte[] key) {
        assertNotNull(algorithm);
        this.algorithm = algorithm;

        assertNotNull(key);
        this.key = key;
    }

    public InputStream protect(InputStream base)
            throws IOException {
        try {
            Cipher cipher = cipherFor(Cipher.ENCRYPT_MODE);
            return new CipherInputStream(base, cipher);
        } catch (Exception e) {
            throw new OperationException(e);
        }
    }

    public InputStream unprotect(InputStream base)
            throws IOException {
        try {
            Cipher cipher = cipherFor(Cipher.DECRYPT_MODE);
            return new CipherInputStream(base, cipher);
        } catch (Exception e) {
            throw new OperationException(e);
        }
    }

    public OutputStream protect(OutputStream base)
            throws IOException {
        try {
            Cipher cipher = cipherFor(Cipher.ENCRYPT_MODE);
            return new CipherOutputStream(base, cipher);
        } catch (Exception e) {
            throw new OperationException(e);
        }
    }

    public OutputStream unprotect(OutputStream base)
            throws IOException {
        try {
            Cipher cipher = cipherFor(Cipher.DECRYPT_MODE);
            return new CipherOutputStream(base, cipher);
        } catch (Exception e) {
            throw new OperationException(e);
        }
    }

    private Cipher cipherFor(int mode)
            throws Exception {
        String name = String.format(ALGORITHM_TEMPLATE, this.algorithm);
        Cipher cipher = Cipher.getInstance(name);
        byte[] iv = new byte[cipher.getBlockSize()];
        cipher.init(mode, new SecretKeySpec(this.key, this.algorithm), new IvParameterSpec(iv));

        return cipher;
    }


}
