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

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

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

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

    private final Object provider;

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

    @Override
    public Signature sign(byte[] data, String publicKeyAlgorithm, PrivateKey key)
            throws Exception {
        java.security.Signature signature = signatureFor(publicKeyAlgorithm);
        signature.initSign(key);
        signature.update(data);
        byte[] blob = signature.sign();

        return new Signature(PublicKeyAlgorithm.DSA.identifier, blob);
    }

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

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

    private java.security.Signature signatureFor(String publicKeyAlgorithm)
            throws Exception {
        String signatureAlgorithm = String.format("%sWithDSA", PublicKeyAlgorithm.signatureAlgorithmFor(publicKeyAlgorithm));
        return Signatures.signatureFor(signatureAlgorithm, this.provider);
    }
}
