package org.bouncycastle.jce.provider;

import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;

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.PBEParameterSpec;
import javax.crypto.spec.RC2ParameterSpec;
import javax.crypto.spec.RC5ParameterSpec;

import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.*;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.modes.CFBBlockCipher;
import org.bouncycastle.crypto.modes.CTSBlockCipher;
import org.bouncycastle.crypto.modes.OFBBlockCipher;
import org.bouncycastle.crypto.modes.PGPCFBBlockCipher;
import org.bouncycastle.crypto.modes.SICBlockCipher;
import org.bouncycastle.crypto.paddings.ISO10126d2Padding;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.paddings.X923Padding;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.crypto.params.RC2Parameters;
import org.bouncycastle.crypto.params.RC5Parameters;

public class JCEBlockCipher extends WrapCipherSpi
    implements PBE
{
    //
    // specs we can handle.
    //
    private Class[]                 availableSpecs =
                                    {
                                        RC2ParameterSpec.class,
                                        RC5ParameterSpec.class,
                                        IvParameterSpec.class,
                                        PBEParameterSpec.class
                                    };
 
    private BlockCipher             baseEngine;
    private BufferedBlockCipher     cipher;
    private ParametersWithIV        ivParam;

    private int                     pbeType = PKCS12;
    private int                     pbeHash = SHA1;
    private int                     pbeKeySize;
    private int                     pbeIvSize;

    private int                     ivLength = 0;

    private AlgorithmParameters     engineParams = null;

    private boolean                 padded = true;

    protected JCEBlockCipher(
        BlockCipher engine)
    {
        baseEngine = engine;

        cipher = new PaddedBufferedBlockCipher(engine);
    }
        
    protected JCEBlockCipher(
        BlockCipher engine,
        int         ivLength)
    {
        baseEngine = engine;

        this.cipher = new PaddedBufferedBlockCipher(engine);
        this.ivLength = ivLength / 8;
    }
        
    protected JCEBlockCipher(
        BlockCipher engine,
        int         pbeType,
        int         pbeHash,
        int         pbeKeySize,
        int         pbeIvSize)
    {
        baseEngine = engine;
        cipher = new PaddedBufferedBlockCipher(engine);

        this.pbeType = pbeType;
        this.pbeHash = pbeHash;
        this.pbeKeySize = pbeKeySize;
        this.pbeIvSize = pbeIvSize;
    }

    protected int engineGetBlockSize() 
    {
        return baseEngine.getBlockSize();
    }

    protected byte[] engineGetIV() 
    {
        return (ivParam != null) ? ivParam.getIV() : null;
    }

    protected int engineGetKeySize(
        Key     key) 
    {
        return key.getEncoded().length * 8;
    }

    protected int engineGetOutputSize(
        int     inputLen) 
    {
        return cipher.getOutputSize(inputLen);
    }

    protected AlgorithmParameters engineGetParameters() 
    {
        if (engineParams == null)
        {
            if (ivParam != null)
            {
                String  name = cipher.getUnderlyingCipher().getAlgorithmName();

                if (name.indexOf('/') >= 0)
                {
                    name = name.substring(0, name.indexOf('/'));
                }

                try
                {
                    engineParams = AlgorithmParameters.getInstance(name, "BC");
                    engineParams.init(ivParam.getIV());
                }
                catch (Exception e)
                {
                    throw new RuntimeException(e.toString());
                }
            }
        }

        return engineParams;
    }

    protected void engineSetMode(
        String  mode) 
    {
        String  modeName = mode.toUpperCase();

        if (modeName.equals("ECB"))
        {
            ivLength = 0;
            cipher = new PaddedBufferedBlockCipher(cipher.getUnderlyingCipher());
        }
        else if (modeName.equals("CBC"))
        {
            ivLength = cipher.getUnderlyingCipher().getBlockSize();
            cipher = new PaddedBufferedBlockCipher(
                            new CBCBlockCipher(cipher.getUnderlyingCipher()));
        }
        else if (modeName.startsWith("OFB"))
        {
            ivLength = cipher.getUnderlyingCipher().getBlockSize();
            if (modeName.length() != 3)
            {
                int wordSize = Integer.parseInt(modeName.substring(3));

                cipher = new PaddedBufferedBlockCipher(
                                new OFBBlockCipher(cipher.getUnderlyingCipher(), wordSize));
            }
            else
            {
                cipher = new PaddedBufferedBlockCipher(
                        new OFBBlockCipher(cipher.getUnderlyingCipher(), 8 * cipher.getBlockSize()));
            }
        }
        else if (modeName.startsWith("CFB"))
        {
            ivLength = cipher.getUnderlyingCipher().getBlockSize();
            if (modeName.length() != 3)
            {
                int wordSize = Integer.parseInt(modeName.substring(3));

                cipher = new PaddedBufferedBlockCipher(
                                new CFBBlockCipher(cipher.getUnderlyingCipher(), wordSize));
            }
            else
            {
                cipher = new PaddedBufferedBlockCipher(
                        new CFBBlockCipher(cipher.getUnderlyingCipher(), 8 * cipher.getBlockSize()));
            }
        }
        else if (modeName.startsWith("PGP"))
        {
            if (modeName.equalsIgnoreCase("PGPCFBwithIV"))
            {
                ivLength = cipher.getUnderlyingCipher().getBlockSize();
                cipher = new PaddedBufferedBlockCipher(
                    new PGPCFBBlockCipher(cipher.getUnderlyingCipher(), true));
            }
            else
            {
                ivLength = cipher.getUnderlyingCipher().getBlockSize();
                cipher = new PaddedBufferedBlockCipher(
                    new PGPCFBBlockCipher(cipher.getUnderlyingCipher(), false));
            }
        }
        else if (modeName.startsWith("SIC"))
        {
            ivLength = cipher.getUnderlyingCipher().getBlockSize();
            if (ivLength < 16)
            {
                throw new IllegalArgumentException("Warning: SIC-Mode can become a twotime-pad if the blocksize of the cipher is too small. Use a cipher with a block size of at least 128 bits (e.g. AES)");
            }
            cipher = new PaddedBufferedBlockCipher(
                        new SICBlockCipher(cipher.getUnderlyingCipher()));
        }
        else
        {
            throw new IllegalArgumentException("can't support mode " + mode);
        }
    }

    protected void engineSetPadding(
        String  padding) 
    throws NoSuchPaddingException
    {
        String  paddingName = padding.toUpperCase();

        if (paddingName.equals("NOPADDING"))
        {
            padded = false;
            cipher = new BufferedBlockCipher(cipher.getUnderlyingCipher());
        }
        else if (paddingName.equals("PKCS5PADDING") || paddingName.equals("PKCS7PADDING"))
        {
            cipher = new PaddedBufferedBlockCipher(cipher.getUnderlyingCipher());
        }
        else if (paddingName.equals("ISO10126PADDING") || paddingName.equals("ISO10126-2PADDING"))
        {
            cipher = new PaddedBufferedBlockCipher(cipher.getUnderlyingCipher(), new ISO10126d2Padding());
        }
        else if (paddingName.equals("X9.23PADDING") || paddingName.equals("X923PADDING"))
        {
            cipher = new PaddedBufferedBlockCipher(cipher.getUnderlyingCipher(), new X923Padding());
        }
        else if (paddingName.equals("WITHCTS"))
        {
            padded = false;
            cipher = new CTSBlockCipher(cipher.getUnderlyingCipher());
        }
        else
        {
            throw new NoSuchPaddingException("Padding " + padding + " unknown.");
        }
    }

    protected void engineInit(
        int                     opmode,
        Key                     key,
        AlgorithmParameterSpec  params,
        SecureRandom            random) 
    throws InvalidKeyException, InvalidAlgorithmParameterException
    {
        CipherParameters        param;

        //
        // for RC5-64 we must have some default parameters
        //
        if (params == null && baseEngine.getAlgorithmName().startsWith("RC5-64"))
        {
            throw new InvalidAlgorithmParameterException("RC5 requires an RC5ParametersSpec to be passed in.");
        }

        //
        // a note on iv's - if ivLength is zero the IV gets ignored (we don't use it).
        //
        if (key instanceof JCEPBEKey)
        {
            param = PBE.Util.makePBEParameters((JCEPBEKey)key, params, pbeType, pbeHash,
                        cipher.getUnderlyingCipher().getAlgorithmName(), pbeKeySize, pbeIvSize);

            if (pbeIvSize != 0)
            {
                ivParam = (ParametersWithIV)param;
            }
        }
        else if (params == null)
        {
            param = new KeyParameter(key.getEncoded());
        }
        else if (params instanceof IvParameterSpec)
        {
            if (ivLength != 0)
            {
                IvParameterSpec p = (IvParameterSpec)params;

                if (p.getIV().length != ivLength)
                {
                    throw new InvalidAlgorithmParameterException("IV must be " + ivLength + " bytes long.");
                }

                param = new ParametersWithIV(new KeyParameter(key.getEncoded()), p.getIV());
                ivParam = (ParametersWithIV)param;
            }
            else
            {
                // ignore it...
                //
                param = new KeyParameter(key.getEncoded());
            }
        }
        else if (params instanceof RC2ParameterSpec)
        {
            RC2ParameterSpec    rc2Param = (RC2ParameterSpec)params;

            param = new RC2Parameters(key.getEncoded(), ((RC2ParameterSpec)params).getEffectiveKeyBits());

            if (rc2Param.getIV() != null && ivLength != 0)
            {
                param = new ParametersWithIV(param, rc2Param.getIV());
                ivParam = (ParametersWithIV)param;
            }
        }
        else if (params instanceof RC5ParameterSpec)
        {
            RC5ParameterSpec    rc5Param = (RC5ParameterSpec)params;

            param = new RC5Parameters(key.getEncoded(), ((RC5ParameterSpec)params).getRounds());
            if (baseEngine.getAlgorithmName().startsWith("RC5"))
            {
                if (baseEngine.getAlgorithmName().equals("RC5-32"))
                {
                    if (rc5Param.getWordSize() != 32)
                    {
                        throw new InvalidAlgorithmParameterException("RC5 already set up for a word size of 32 not " + rc5Param.getWordSize() + ".");
                    }
                }
                else if (baseEngine.getAlgorithmName().equals("RC5-64"))
                {
                    if (rc5Param.getWordSize() != 64)
                    {
                        throw new InvalidAlgorithmParameterException("RC5 already set up for a word size of 64 not " + rc5Param.getWordSize() + ".");
                    }
                }
            }
            else
            {
                throw new InvalidAlgorithmParameterException("RC5 parameters passed to a cipher that is not RC5.");
            }
            if ((rc5Param.getIV() != null) && (ivLength != 0))
            {
                param = new ParametersWithIV(param, rc5Param.getIV());
                ivParam = (ParametersWithIV)param;
            }
        }
        else
        {
            throw new InvalidAlgorithmParameterException("unknown parameter type.");
        }

        if ((ivLength != 0) && !(param instanceof ParametersWithIV))
        {
            SecureRandom    ivRandom = random;

            if (ivRandom == null)
            {
                ivRandom = new SecureRandom();
            }

            if ((opmode == Cipher.ENCRYPT_MODE) || (opmode == Cipher.WRAP_MODE))
            {
                byte[]  iv = new byte[ivLength];

                ivRandom.nextBytes(iv);
                param = new ParametersWithIV(param, iv);
                ivParam = (ParametersWithIV)param;
            }
            else if (cipher.getUnderlyingCipher().getAlgorithmName().indexOf("PGPCFB") < 0)
            {
                throw new InvalidAlgorithmParameterException("no IV set when one expected");
            }
        }

        if (random != null && padded)
        {
            param = new ParametersWithRandom(param, random);
        }

        switch (opmode)
        {
        case Cipher.ENCRYPT_MODE:
        case Cipher.WRAP_MODE:
            cipher.init(true, param);
            break;
        case Cipher.DECRYPT_MODE:
        case Cipher.UNWRAP_MODE:
            cipher.init(false, param);
            break;
        default:
            System.out.println("eeek!");
        }
    }

    protected void engineInit(
        int                 opmode,
        Key                 key,
        AlgorithmParameters params,
        SecureRandom        random) 
    throws InvalidKeyException, InvalidAlgorithmParameterException
    {
        AlgorithmParameterSpec  paramSpec = null;

        if (params != null)
        {
            for (int i = 0; i != availableSpecs.length; i++)
            {
                try
                {
                    paramSpec = params.getParameterSpec(availableSpecs[i]);
                    break;
                }
                catch (Exception e)
                {
                    continue;
                }
            }

            if (paramSpec == null)
            {
                throw new InvalidAlgorithmParameterException("can't handle parameter " + params.toString());
            }
        }

        engineParams = params;
        engineInit(opmode, key, paramSpec, random);
    }

    protected void engineInit(
        int                 opmode,
        Key                 key,
        SecureRandom        random) 
        throws InvalidKeyException
    {
        try
        {
            engineInit(opmode, key, (AlgorithmParameterSpec)null, random);
        }
        catch (InvalidAlgorithmParameterException e)
        {
            throw new IllegalArgumentException(e.getMessage());
        }
    }

    protected byte[] engineUpdate(
        byte[]  input,
        int     inputOffset,
        int     inputLen) 
    {
        int     length = cipher.getUpdateOutputSize(inputLen);

        if (length > 0)
        {
                byte[]  out = new byte[length];

                int len = cipher.processBytes(input, inputOffset, inputLen, out, 0);

                if (len == 0)
                {
                    return null;
                }
                else if (len != out.length)
                {
                    byte[]  tmp = new byte[len];

                    System.arraycopy(out, 0, tmp, 0, len);

                    return tmp;
                }

                return out;
        }

        cipher.processBytes(input, inputOffset, inputLen, null, 0);

        return null;
    }

    protected int engineUpdate(
        byte[]  input,
        int     inputOffset,
        int     inputLen,
        byte[]  output,
        int     outputOffset) 
    {
        return cipher.processBytes(input, inputOffset, inputLen, output, outputOffset);
    }

    protected byte[] engineDoFinal(
        byte[]  input,
        int     inputOffset,
        int     inputLen) 
        throws IllegalBlockSizeException, BadPaddingException
    {
        int     len = 0;
        byte[]  tmp = new byte[engineGetOutputSize(inputLen)];

        if (inputLen != 0)
        {
            len = cipher.processBytes(input, inputOffset, inputLen, tmp, 0);
        }

        try
        {
            len += cipher.doFinal(tmp, len);
        }
        catch (DataLengthException e)
        {
            throw new IllegalBlockSizeException(e.getMessage());
        }
        catch (InvalidCipherTextException e)
        {
            throw new BadPaddingException(e.getMessage());
        }

        byte[]  out = new byte[len];

        System.arraycopy(tmp, 0, out, 0, len);

        return out;
    }

    protected int engineDoFinal(
        byte[]  input,
        int     inputOffset,
        int     inputLen,
        byte[]  output,
        int     outputOffset) 
        throws IllegalBlockSizeException, BadPaddingException
    {
        int     len = 0;

        if (inputLen != 0)
        {
                len = cipher.processBytes(input, inputOffset, inputLen, output, outputOffset);
        }

        try
        {
            return (len + cipher.doFinal(output, outputOffset + len));
        }
        catch (DataLengthException e)
        {
            throw new IllegalBlockSizeException(e.getMessage());
        }
        catch (InvalidCipherTextException e)
        {
            throw new BadPaddingException(e.getMessage());
        }
    }

    /*
     * The ciphers that inherit from us.
     */

    /**
     * DES
     */
    static public class DES
        extends JCEBlockCipher
    {
        public DES()
        {
            super(new DESEngine());
        }
    }

    /**
     * DESCBC
     */
    static public class DESCBC
        extends JCEBlockCipher
    {
        public DESCBC()
        {
            super(new CBCBlockCipher(new DESEngine()), 64);
        }
    }

    /**
     * DESede
     */
    static public class DESede
        extends JCEBlockCipher
    {
        public DESede()
        {
            super(new DESedeEngine());
        }
    }

    /**
     * DESedeCBC
     */
    static public class DESedeCBC
        extends JCEBlockCipher
    {
        public DESedeCBC()
        {
            super(new CBCBlockCipher(new DESedeEngine()), 64);
        }
    }

    /**
     * SKIPJACK
     */
    static public class Skipjack
        extends JCEBlockCipher
    {
        public Skipjack()
        {
            super(new SkipjackEngine());
        }
    }

    /**
     * Blowfish
     */
    static public class Blowfish
        extends JCEBlockCipher
    {
        public Blowfish()
        {
            super(new BlowfishEngine());
        }
    }

    /**
     * Twofish
     */
    static public class Twofish
        extends JCEBlockCipher
    {
        public Twofish()
        {
            super(new TwofishEngine());
        }
    }

    /**
     * RC2
     */
    static public class RC2
        extends JCEBlockCipher
    {
        public RC2()
        {
            super(new RC2Engine());
        }
    }

    /**
     * RC2CBC
     */
    static public class RC2CBC
        extends JCEBlockCipher
    {
        public RC2CBC()
        {
            super(new CBCBlockCipher(new RC2Engine()), 64);
        }
    }

    /**
     * RC5
     */
    static public class RC5
        extends JCEBlockCipher
    {
        public RC5()
        {
            super(new RC532Engine());
        }
    }

    /**
     * RC564
     */
    static public class RC564
        extends JCEBlockCipher
    {
        public RC564()
        {
            super(new RC564Engine());
        }
    }

    /**
     * RC6
     */
    static public class RC6
        extends JCEBlockCipher
    {
        public RC6()
        {
            super(new RC6Engine());
        }
    }

    /**
     * AES
     */
    static public class AES
        extends JCEBlockCipher
    {
        public AES()
        {
            super(new AESFastEngine());
        }
    }

    /**
     * AES
     */
    static public class AESCBC
        extends JCEBlockCipher
    {
        public AESCBC()
        {
            super(new CBCBlockCipher(new AESFastEngine()), 128);
        }
    }

    /**
     * Rijndael
     */
    static public class Rijndael
        extends JCEBlockCipher
    {
        public Rijndael()
        {
            super(new RijndaelEngine());
        }
    }

    /**
     * Serpent
     */
    static public class Serpent
        extends JCEBlockCipher
    {
        public Serpent()
        {
            super(new SerpentEngine());
        }
    }

    /**
     * CAST5
     */
    static public class CAST5
        extends JCEBlockCipher
    {
        public CAST5()
        {
            super(new CAST5Engine());
        }
    }

    /**
     * CAST5 CBC
     */
    static public class CAST5CBC
        extends JCEBlockCipher
    {
        public CAST5CBC()
        {
            super(new CBCBlockCipher(new CAST5Engine()), 64);
        }
    }

    /**
     * CAST6
     */
    static public class CAST6
        extends JCEBlockCipher
    {
        public CAST6()
        {
            super(new CAST6Engine());
        }
    }

    /**
     * IDEA
     */
    static public class IDEA
        extends JCEBlockCipher
    {
        public IDEA()
        {
            super(new IDEAEngine());
        }
    }

    /**
     * IDEA CBC
     */
    static public class IDEACBC
        extends JCEBlockCipher
    {
        public IDEACBC()
        {
            super(new CBCBlockCipher(new IDEAEngine()), 64);
        }
    }

    /**
     * PBEWithMD5AndDES
     */
    static public class PBEWithMD5AndDES
        extends JCEBlockCipher
    {
        public PBEWithMD5AndDES()
        {
            super(new CBCBlockCipher(new DESEngine()), PKCS5S1, MD5, 64, 64);
        }
    }

    /**
     * PBEWithMD5AndRC2
     */
    static public class PBEWithMD5AndRC2
        extends JCEBlockCipher
    {
        public PBEWithMD5AndRC2()
        {
            super(new CBCBlockCipher(new RC2Engine()), PKCS5S1, MD5, 128, 64);
        }
    }

    /**
     * PBEWithSHA1AndDES
     */
    static public class PBEWithSHA1AndDES
        extends JCEBlockCipher
    {
        public PBEWithSHA1AndDES()
        {
            super(new CBCBlockCipher(new DESEngine()), PKCS5S1, SHA1, 64, 64);
        }
    }

    /**
     * PBEWithSHA1AndRC2
     */
    static public class PBEWithSHA1AndRC2
        extends JCEBlockCipher
    {
        public PBEWithSHA1AndRC2()
        {
            super(new CBCBlockCipher(new RC2Engine()), PKCS5S1, SHA1, 128, 64);
        }
    }

    /**
     * PBEWithSHAAnd3-KeyTripleDES-CBC
     */
    static public class PBEWithSHAAndDES3Key
        extends JCEBlockCipher
    {
        public PBEWithSHAAndDES3Key()
        {
            super(new CBCBlockCipher(new DESedeEngine()), PKCS12, SHA1, 192, 64);
        }
    }

    /**
     * PBEWithSHAAnd2-KeyTripleDES-CBC
     */
    static public class PBEWithSHAAndDES2Key
        extends JCEBlockCipher
    {
        public PBEWithSHAAndDES2Key()
        {
            super(new CBCBlockCipher(new DESedeEngine()), PKCS12, SHA1, 128, 64);
        }
    }

    /**
     * PBEWithSHAAnd128BitRC2-CBC
     */
    static public class PBEWithSHAAnd128BitRC2
        extends JCEBlockCipher
    {
        public PBEWithSHAAnd128BitRC2()
        {
            super(new CBCBlockCipher(new RC2Engine()), PKCS12, SHA1, 128, 64);
        }
    }

    /**
     * PBEWithSHAAnd40BitRC2-CBC
     */
    static public class PBEWithSHAAnd40BitRC2
        extends JCEBlockCipher
    {
        public PBEWithSHAAnd40BitRC2()
        {
            super(new CBCBlockCipher(new RC2Engine()), PKCS12, SHA1, 40, 64);
        }
    }

    /**
     * PBEWithSHAAndTwofish-CBC
     */
    static public class PBEWithSHAAndTwofish
        extends JCEBlockCipher
    {
        public PBEWithSHAAndTwofish()
        {
            super(new CBCBlockCipher(new TwofishEngine()), PKCS12, SHA1, 256, 128);
        }
    }

    /**
     * PBEWithSHAAndIDEA-CBC
     */
    static public class PBEWithSHAAndIDEA
        extends JCEBlockCipher
    {
        public PBEWithSHAAndIDEA()
        {
            super(new CBCBlockCipher(new IDEAEngine()), PKCS12, SHA1, 128, 64);
        }
    }
}
