package org.bouncycastle.jce.provider.test;

import java.security.Key;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.test.SimpleTestResult;
import org.bouncycastle.util.test.Test;
import org.bouncycastle.util.test.TestResult;

/**
 * check that doFinal is properly reseting the cipher.
 */
public class DoFinalTest
    implements Test
{
    public DoFinalTest()
    {
    }

    public TestResult perform()
    {
        String lCode = "ABCDEFGHIJKLMNOPQRSTUVWXY0123456789";
        String cipherName = "Rijndael";

        try
        {
            KeyGenerator    kGen = KeyGenerator.getInstance(cipherName, "BC");
            Cipher          cipher = Cipher.getInstance(cipherName, "BC");
            Key             key = kGen.generateKey();

            cipher.init(Cipher.ENCRYPT_MODE, key);

            byte[] encrypted = cipher.doFinal(lCode.getBytes());

            if (encrypted.length != 48)
            {
                return new SimpleTestResult(false, getName() + ": Failed - expected length 48 got " + encrypted.length);
            }

            // 2nd try
            encrypted = cipher.doFinal(lCode.getBytes());
            if (encrypted.length != 48)
            {
                return new SimpleTestResult(false, getName() + ": Failed - expected length 48 got " + encrypted.length);
            }

            // 3rd try
            byte[]  enc1 = cipher.update(lCode.getBytes());
            byte[]  enc2 = cipher.doFinal();

            if ((enc1.length + enc2.length) != 48)
            {
                return new SimpleTestResult(false, getName() + ": Failed - expected length 48 got " + (enc1.length + enc2.length));
            }

            enc1 = cipher.update(lCode.getBytes());
            int len = cipher.doFinal(enc1, 0);
            if ((enc1.length + len) != 48)
            {
                return new SimpleTestResult(false, getName() + ": Failed - expected length 48 got " + (enc1.length + len));
            }
        }
        catch (Exception e)
        {
            return new SimpleTestResult(false, getName() + ": Failed - exception " + e.toString());
        }

        return new SimpleTestResult(true, getName() + ": Okay");
    }

    public String getName()
    {
        return "DoFinalTest";
    }

    public static void main(
        String[]    args)
    {
        Security.addProvider(new BouncyCastleProvider());

        Test            test = new DoFinalTest();
        TestResult      result = test.perform();

        System.out.println(result.toString());
    }
}
