/*
 * 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.config.tenant.service;

import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class KeyPairService {

    private final AsymmetricServiceAPI asymmetricServiceAPI;

    @Autowired
    public KeyPairService(AsymmetricServiceAPI asymmetricService) {
        asymmetricServiceAPI = asymmetricService;
    }

    /**
     * Generate a keypair for signing
     */
    public KeyPair generateKeyPairForSigning() {

        return asymmetricServiceAPI.getKeyPairForSigning();
    }

    /**
     * Validates if a pair of keys match
     *
     * @param publicKey
     * @param privateKey
     * @return
     * @throws GeneralCryptoLibException
     */
    public boolean validateKeyPair(final PublicKey publicKey, final PrivateKey privateKey)
            throws GeneralCryptoLibException {

        final String testString = "word to be tested in the generated key pair";
        final byte[] encryptedTestString =
            asymmetricServiceAPI.encrypt(publicKey, testString.getBytes(StandardCharsets.UTF_8));
        final byte[] decryptedTestString = asymmetricServiceAPI.decrypt(privateKey, encryptedTestString);
        final String decrypted = new String(decryptedTestString, StandardCharsets.UTF_8);
        return decrypted.equals(testString);
    }

}
