/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.commons.signature;

import static org.junit.Assert.assertTrue;

import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.Security;
import java.security.Signature;
import java.security.SignatureException;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import com.scytl.cryptolib.api.asymmetric.AsymmetricServiceAPI;
import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.asymmetric.service.AsymmetricService;

/**
 * Tests of {@link SignatureFactoryImpl}.
 */
public class SignatureFactoryImplTest {
    private static final byte[] DATA = {0, 1, 2 };

    private AsymmetricServiceAPI service;

    private KeyPair pair;

    @BeforeClass
    public static void init() {
        Security.addProvider(new BouncyCastleProvider());
    }

    @Before
    public void setUp() throws GeneralCryptoLibException {
        service = new AsymmetricService();
        pair = service.getKeyPairForSigning();
    }

    @Test
    public void testNewSignatureSign() throws InvalidKeyException, SignatureException, GeneralCryptoLibException {
        SignatureFactory factory = SignatureFactoryImpl.newInstance();
        Signature signature = factory.newSignature();
        signature.initSign(pair.getPrivate());

        signature.update(DATA);
        byte[] result = signature.sign();

        assertTrue(service.verifySignature(result, pair.getPublic(), DATA));
    }

    @Test
    public void testNewSignatureVerify() throws InvalidKeyException, SignatureException, GeneralCryptoLibException {
        SignatureFactory factory = SignatureFactoryImpl.newInstance();
        Signature signature = factory.newSignature();

        byte[] result = service.sign(pair.getPrivate(), DATA);

        signature.initVerify(pair.getPublic());
        signature.update(DATA);
        assertTrue(signature.verify(result));
    }
}
