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

import com.jscape.inet.ssh.protocol.v2.messages.Signature;

import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @author Alex Usun
 */
public class JceEcSigner
        implements Signer {

    private final Object provider;

    public JceEcSigner(Object provider) {
        this.provider = provider;
    }

    @Override
    public Signature sign(byte[] data, String publicKeyAlgorithm, PrivateKey key)
            throws Exception {
//        String identifier = KeyType.formatIdentifierFor(key);
        java.security.Signature signature = EcSignatures.signatureFor(key, this.provider);
        signature.update(data);
        byte[] blob = signature.sign();

//        return new Signature(identifier, blob);
        return new Signature(publicKeyAlgorithm, blob);
    }

    @Override
    @SuppressWarnings("unchecked")
    public void assertSignatureValid(byte[] data, PublicKey key, Signature signatureData)
            throws Exception {
        java.security.Signature signature = EcSignatures.signatureFor(key, this.provider);
        signature.update(data);

        if (!signature.verify(signatureData.blob)) {
            throw new InvalidSignatureException();
        }
    }

    @Override
    public String toString() {
        return "JceEcSigner {}";
    }

}
