package com.fitbank.common.crypto;

import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

/**
 * Clase que sirve para encriptar y desencriptar una cadena de texto mediante el
 * algoritmo DES.
 * 
 * @author Fitbank
 * @version 2.0
 */

public class Encrypter {
    Cipher ecipher;

    Cipher dcipher;

    // constructor que crea los objetos Cipher para encriptar y desencriptar

    public Encrypter(String passPhrase, String pAlgorithm) {
        try {
            // interpreta la cadena como 8 bytes (cada dos un hexadecimal)
            char[] ca = passPhrase.toCharArray();
            byte[] ba = Util.decodeHex(ca);

            // Create the key
            KeySpec keySpec = new DESKeySpec(ba);
            SecretKey key = SecretKeyFactory.getInstance(pAlgorithm).generateSecret(keySpec);
            this.ecipher = Cipher.getInstance(key.getAlgorithm());
            this.dcipher = Cipher.getInstance(key.getAlgorithm());

            // Create the ciphers
            this.ecipher.init(Cipher.ENCRYPT_MODE, key);
            this.dcipher.init(Cipher.DECRYPT_MODE, key);
        } catch (java.security.spec.InvalidKeySpecException e) {
        } catch (javax.crypto.NoSuchPaddingException e) {
        } catch (java.security.NoSuchAlgorithmException e) {
        } catch (java.security.InvalidKeyException e) {
        }
    }

    public byte[] encrypt(String str) {
        try {
            // interpreta la cadena como 8 bytes (cada dos un hexadecimal)
            char[] ca = str.toCharArray();
            byte[] ba = Util.decodeHex(ca);

            // encrypt
            byte[] enc = this.ecipher.doFinal(ba);

            // retorna los bytes encriptados
            return enc;
        } catch (javax.crypto.BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        }
        return null;
    }

}