Package com.CryptoAlgorithms

Source Code of com.CryptoAlgorithms.DHAlgorithmTest

package com.CryptoAlgorithms;

import com.CryptoAlgorithms.DiffieHellman.DHAgreementModel;
import com.CryptoAlgorithms.DiffieHellman.DHAlgorithm;
import com.exceptions.CreatingDHAgreementException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import static org.hamcrest.core.IsEqual.equalTo;

public class DHAlgorithmTest {

    private DHAlgorithm dhAlgorithm;
    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    @Before
    public void setup() {
        this.dhAlgorithm = new DHAlgorithm();
    }

    @Test
    public void shouldGenerateInitialNumbers() throws CreatingDHAgreementException {
        DHAgreementModel dhAgreementModel = dhAlgorithm.generateInitialNumbers();
        int certainty = Integer.MAX_VALUE;
        boolean isPrime = dhAgreementModel.getP().isProbablePrime(certainty);
        Assert.assertThat(isPrime, equalTo(true));
    }

    @Test
    public void shouldGenerateSameSecretForBoth() throws CreatingDHAgreementException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException {
        DHAgreementModel A = dhAlgorithm.generateInitialNumbers();
        DHAgreementModel B = dhAlgorithm.generateInitialNumbers(A.getP(), A.getG());

        byte[] server = dhAlgorithm.generateSecret(A.get_a(), B.getPublicA());
        byte[] client = dhAlgorithm.generateSecret(B.get_a(), A.getPublicA());

        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        byte[] digestServer = messageDigest.digest(server);
        byte[] digestClient = messageDigest.digest(client);

        Assert.assertThat(digestClient, equalTo(digestServer));
    }

    @Test
    public void shouldFailGeneratingKeyWithWrongKey() throws CreatingDHAgreementException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException {
        DHAgreementModel A = dhAlgorithm.generateInitialNumbers();
        DHAgreementModel B = dhAlgorithm.generateInitialNumbers();

        expectedException.expect(CreatingDHAgreementException.class);
        byte[] server = dhAlgorithm.generateSecret(A.get_a(), B.getPublicA());
    }
}
TOP

Related Classes of com.CryptoAlgorithms.DHAlgorithmTest

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.