/*
 * 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.cryptolib.asymmetric.keypair.openssl;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

import org.junit.Test;

import com.scytl.cryptolib.api.exceptions.CryptoLibException;

/**
 * Tests of {@link PEMEncodedKeySpec}.
 */
public class PEMEncodedKeySpecTest {
    private static final String PEM = "-----BEGIN PRIVATE KEY-----\n"
        + "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAK76mIp/uSiPZQNP"
        + "5rxXKpWU7rNzy+qof73vZIFLMl2IaOwxjJswMon26rr7zzbLOBOkApgEBF5P5z/j"
        + "+jfpAYQel3KnjNsPcG7hiW1pCVdOg042D8lyJPKGC6a/LMwFcwTj8XaMiu6gTFJv"
        + "Iu5a5JJljZ21+tLLKDU9VXwXm+wJAgMBAAECgYEAj4WWtwtaWU18wkG4dUVd9YFK"
        + "ZUEWwmvhE26XVoHSVuu7e/iMZwIaghVYpXRDm6MGZP3C7uNkneMWP86D/3YMOfFB"
        + "eidi13iy9V3OiybqXainxvqH4tLInpQJeVGK1DK3flKp9r84Vlqx71hHyK5k3Zo5"
        + "kbed/xPkXDwfZkgeX7ECQQDizQ5R8hsrUgnKq5Fv6F1lH62zk94Qi8C1/Ir+xEkk"
        + "0VRggY1eX0hr6yKChJWgHRP8FT5PCAmEKmZwQeEY6o09AkEAxYGUFRRXrv9ZTIKZ"
        + "Pa9jAJbZCFSaxntcjAJ0AeFbZ49V0YsFXPDtP8i5p7YmJKJWharQ03qYdrokzokd"
        + "TL6evQJAEIAaqpuSnnQ5giU5T4r4QIMtgAMiBNImExdshVyCdctE+EB0qIkGG9Pf"
        + "jt9Wg2+aJJznC5jqGFN9YG1qkwV9gQJBAMVD29SGAeHudpF9a3L55uciw1iXsBMI"
        + "CXJpzNZH8JRpzCxDLzMaC8yGPjAtNMGoRsSwzGw86WTEHJkQx+vsA/0CQAPQ5Tnz"
        + "CmXUfUSCAeDaunjF252fl2h2WO1psS/ucfTiEbN4B6+77bvFDeMrfDfDTJWbXZK8"
        + "HB935zyvEMIiBcE=" + "-----END PRIVATE KEY-----\n";

    @Test
    public void testDestroy() {
        byte[] encodedKey = new byte[] {1, 2, 3 };
        PEMEncodedKeySpec spec = new PEMEncodedKeySpec(encodedKey);
        spec.destroy();
        for (byte b : encodedKey) {
            assertEquals(0, b);
        }
    }

    @Test
    public void testNewInstance() {
        PEMEncodedKeySpec spec = PEMEncodedKeySpec
            .newInstance(PEM.getBytes(StandardCharsets.UTF_8));
        assertTrue(
            PEM.contains(Base64.getEncoder().encodeToString(spec.getEncoded())));
    }

    @Test(expected = CryptoLibException.class)
    public void testNewInstanceInvalidFooter() {
        PEMEncodedKeySpec.newInstance(
            "-----BEGIN PRIVATE KEY-----\n-----END PRIVATE KEY-----\nInvalid"
                .getBytes(StandardCharsets.UTF_8));
    }

    @Test(expected = CryptoLibException.class)
    public void testNewInstanceInvalidHeader() {
        PEMEncodedKeySpec.newInstance(
            "Invalid-----BEGIN PRIVATE KEY-----\n-----END PRIVATE KEY-----\n"
                .getBytes(StandardCharsets.UTF_8));
    }

    @Test(expected = CryptoLibException.class)
    public void testNewInstanceInvalidLength() {
        PEMEncodedKeySpec.newInstance(new byte[0]);
    }
}
