package com.jscape.inet.ssh.protocol.v2.marshaling.keys;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;

/**
 * @author Alex Uzun
 */
public class EcSignatures {

    public static Signature signatureFor(PublicKey key, Object provider)
            throws Exception {
        String algorithm = signatureAlgorithmFor(key);
        Signature signature = Signatures.signatureFor(algorithm, provider);
        signature.initVerify(key);

        return signature;
    }

    public static Signature signatureFor(PrivateKey key, Object provider)
            throws Exception {
        String algorithm = signatureAlgorithmFor(key);
        Signature signature = Signatures.signatureFor(algorithm, provider);
        signature.initSign(key);

        return signature;
    }

    public static String signatureAlgorithmFor(PublicKey key) {
        return signatureAlgorithmFor(((ECPublicKey) key).getParams().getCurve().getField().getFieldSize());
    }

    public static String hashAlgorithmFor(PublicKey key) {
        return hashAlgorithmFor(((ECPublicKey) key).getParams().getCurve().getField().getFieldSize());
    }

    public static String signatureAlgorithmFor(PrivateKey key) {
        return signatureAlgorithmFor(((ECPrivateKey) key).getParams().getCurve().getField().getFieldSize());
    }

    private static String signatureAlgorithmFor(int keyLength) {
        String hashAlgorithm = hashAlgorithmFor(keyLength);
        return String.format("%sWithECDSA", hashAlgorithm);
    }

    private static String hashAlgorithmFor(int keyLength) {
        if (keyLength <= 256) {
            return "SHA256";
        } else if (keyLength <= 384) {
            return "SHA384";
        } else {
            return "SHA512";
        }
    }

    private EcSignatures() {
        // empty
    }
}
