package org.bouncycastle.jce.provider.test;

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

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

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

/**
 * test vectors based on http://www1.ietf.org/internet-drafts/draft-ietf-avt-srtp-05.txt
 */
public class AESSICTest
    implements Test
{
    public String getName()
    {
        return "AESSIC";
    }

    private boolean sameAs(
        byte[]  a,
        byte[]  b)
    {
        if (a.length != b.length)
        {
            return false;
        }

        for (int i = 0; i != a.length; i++)
        {
            if (a[i] != b[i])
            {
                return false;
            }
        }

        return true;
    }

    public TestResult perform()
    {
        try
        {
            Cipher c = Cipher.getInstance("AES/SIC/NoPadding", "BC");

            Key sk = new SecretKeySpec(Hex.decode("2B7E151628AED2A6ABF7158809CF4F3C"), "AES");
            c.init(
                Cipher.ENCRYPT_MODE, sk,
                new IvParameterSpec(Hex.decode("F0F1F2F3F4F5F6F7F8F9FAFBFCFD0000")));

            byte[] crypt = c.doFinal(Hex.decode("00000000000000000000000000000000"));
            if (!sameAs(crypt, 
                        Hex.decode("E03EAD0935C95E80E166B16DD92B4EB4")))
            {
                return new SimpleTestResult(false, getName() + ": AESSIC failed test 1");
            }

            c.init(
                Cipher.ENCRYPT_MODE, sk,
                new IvParameterSpec(Hex.decode("F0F1F2F3F4F5F6F7F8F9FAFBFCFD0001")));

            crypt = c.doFinal(Hex.decode("00000000000000000000000000000000"));

            if (!sameAs(crypt, 
                        Hex.decode("D23513162B02D0F72A43A2FE4A5F97AB")))
            {
                return new SimpleTestResult(false, getName() + ": AESSIC failed test 2");
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return new SimpleTestResult(false, getName() + ": AESSIC failed " + e.toString());
        }

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

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

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

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