package com.jscape.inet.ssh.util;

import com.jscape.inet.ssh.protocol.v2.transport.keyexchange.HostKeyVerificationService;

import java.net.InetAddress;
import java.security.PublicKey;

import static com.jscape.util.Parameters.assertNotNull;

/**
 * Host key verifier implementation based
 * on the <code>SshHostKeys</code> usage.
 * <p/>
 * Methods of this class are not thread-safe.
 * <p/>
 * All methods throw <code>NullPointerException</code> if some object
 * parameter is <code>null</code> and <code>IllegalArgumentException</code>
 * if some parameter doesn't correspond to the method contract.
 *
 * @author Alex
 */
public class HostKeyFingerprintVerifier
        implements HostKeyVerificationService {

    private final SshHostKeys knownKeys;

    /**
     * Creates a new verifier instance.
     *
     * @param knownKeys allowed host keys
     */
    public HostKeyFingerprintVerifier(SshHostKeys knownKeys) {
        assertNotNull(knownKeys);
        this.knownKeys = knownKeys;
    }

    /**
     * Returns allowed host keys.
     *
     * @return allowed host keys
     */
    public SshHostKeys getKnownKeys() {
        return this.knownKeys;
    }

    @Override
    public void assertKeyValid(InetAddress host, PublicKey key)
            throws OperationException {
        try {
            if (!this.knownKeys.contains(host, key)) {
                throw new InvalidHostKeyException(host, key);
            }
        } catch (Exception e) {
            throw OperationException.wrap(e);
        }
    }

    @Override
    public String toString() {
        return "HostKeyFingerprintVerifier {"
               + "knownKeys=" + this.knownKeys
               + '}';
    }
}
