/*
 * Copyright 2002-2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * imitations under the License.
 */

package test;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.InvalidKeyException;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * Unit tests to test the various HMAC veriants.
 * 
 * The class generates MACs with the openSSL functions and compares these
 * results with MACs generated by the BouncyCastle implementation.
 * 
 * Created on 2006-02-26
 * 
 * @author Werner Dittmann (werner@apache.org)
 * 
 */

public class OpenSSLTestCMacs extends TestCase {

    Mac mdJuice = null;

    Mac mdBC = null;

    byte[] plainData = null;

    byte[] hashJuice = null;

    byte[] hashBC = null;

    SecretKey key = null;

    String keyString = "hashmaccamhsahhashmaccamhsahhashmaccamhsah";

    int dataLength;

    public OpenSSLTestCMacs(String name) {
        super(name);
        try {
            Class<?> c = Class
                    .forName("org.apache.security.juice.provider.JuiCEProviderOpenSSL");
            java.security.Security.addProvider((java.security.Provider) c
                    .newInstance());
            c = Class
                    .forName("org.bouncycastle.jce.provider.BouncyCastleProvider");
            java.security.Security.addProvider((java.security.Provider) c
                    .newInstance());
        } catch (Throwable t) {
        }
    }

    public void setUp() {
    }

    private void setMac(String cipherName, int keyLength) {

        String keyInput = new String(keyString.substring(0, keyLength));
        key = (SecretKey) new SecretKeySpec(keyInput.getBytes(), "HMAC");

        try {
            /*
             * initialize ciphers: use the openSSL implementation and the
             * standard BC implementation (as reference)
             */
            mdJuice = Mac.getInstance(cipherName, "JuiCE");
            assertNotNull(" JuiCE HMac not found: " + cipherName, mdJuice);
            mdBC = Mac.getInstance(cipherName, "BC");
            /*
             * Check if cipher providers are correct, i.e the correct provider
             * was chosen.
             */
            assertEquals("Wrong class of JuiCE provider", mdJuice.getProvider()
                    .getClass().getName(),
                    "org.apache.security.juice.provider.JuiCEProviderOpenSSL");

            assertEquals("Wrong class of BC provider", mdBC.getProvider()
                    .getClass().getName(),
                    "org.bouncycastle.jce.provider.BouncyCastleProvider");

        } catch (NoSuchAlgorithmException e) {
            System.out.println(e.getMessage());
        } catch (NoSuchProviderException e) {
            System.out.println(e.getMessage());
        }
        try {
            mdJuice.init(key);
            mdBC.init(key);
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    void digest() {
        try {
            hashJuice = mdJuice.doFinal(plainData);
            hashBC = mdBC.doFinal(plainData);
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    void performTest() {
        digest();
        assertTrue("Mac data mismatch", Arrays.equals(hashJuice, hashBC));
    }

    public void testDESMAC() {
        setMac("DESMAC", 8);
        plainData = new byte[1024];
        for (int i = 0; i < plainData.length; i++) {
            plainData[i] = (byte) (i + 1);
        }
        performTest();
        plainData = new byte[1023];
        for (int i = 0; i < plainData.length; i++) {
            plainData[i] = (byte) (i + 1);
        }
        performTest();
    }

    public void testDESEDEMAC() {
        setMac("DESEDEMAC", 24);
        plainData = new byte[1024];
        for (int i = 0; i < plainData.length; i++) {
            plainData[i] = (byte) (i + 1);
        }
        performTest();
        plainData = new byte[1023];
        for (int i = 0; i < plainData.length; i++) {
            plainData[i] = (byte) (i + 1);
        }
        performTest();
    }

    public void testRC2MAC() {
        setMac("RC2MAC", 8);
        plainData = new byte[1024];
        for (int i = 0; i < plainData.length; i++) {
            plainData[i] = (byte) (i + 1);
        }
        performTest();
        plainData = new byte[1023];
        for (int i = 0; i < plainData.length; i++) {
            plainData[i] = (byte) (i + 1);
        }
        performTest();
    }
    /**
     * JUnit suite 
     * 
     * <p/>
     * 
     * @return a junit test suite
     */
    public static Test suite() {
        return new TestSuite(OpenSSLTestCMacs.class);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        junit.textui.TestRunner.run(suite());
    }
}
