import java.io.*;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.*;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.swing.ImageIcon;

public class Crypto
{

    public Crypto(String passPhrase)
    {
        iterationCount = 19;
        bufi = new byte[1024];
        m_buffer = new byte[10240];
        try
        {
            java.security.spec.KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
            javax.crypto.SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
            ecipher = Cipher.getInstance(key.getAlgorithm());
            dcipher = Cipher.getInstance(key.getAlgorithm());
            java.security.spec.AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
            ecipher.init(1, key, paramSpec);
            dcipher.init(2, key, paramSpec);
        }
        catch(InvalidAlgorithmParameterException e) { }
        catch(InvalidKeySpecException e) { }
        catch(NoSuchPaddingException e) { }
        catch(NoSuchAlgorithmException e) { }
        catch(InvalidKeyException e) { }
    }

    public InputStream encrypt(InputStream in)
    {
        try
        {
            in = new CipherInputStream(in, ecipher);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return in;
    }

    public InputStream decrypt(InputStream in)
    {
        //if(AccederADatos.leer("h.desencriptarModulos").compareToIgnoreCase("S\355") == 0)
            try
            {
                in = new CipherInputStream(in, dcipher);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        return in;
    }

    public ImageIcon convert(InputStream is, String pictureName)
        throws IOException
    {
        byte imageBytes[] = readStream(is, 0L);
        return new ImageIcon(imageBytes, pictureName);
    }

    private byte[] readStream(InputStream is, long sizeIfKnown)
        throws IOException
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int r = -1;
        do
        {
            r = is.read(m_buffer, 0, 10240);
            if(r > -1)
                baos.write(m_buffer, 0, r);
        } while(r > -1);
        return baos.toByteArray();
    }

    Cipher ecipher;
    Cipher dcipher;
    byte salt[] = {
        -87, -101, -56, 50, 86, 53, -29, 3
    };
    int iterationCount;
    byte bufi[];
    public byte m_buffer[];
}