package org.jivesoftware.smackx.ikey;

import org.apache.xml.security.c14n.CanonicalizationException;
import org.apache.xml.security.parser.XMLParserException;
import org.bouncycastle.util.encoders.Base64;
import org.jivesoftware.smackx.ikey.element.ProofElement;
import org.jivesoftware.smackx.ikey.element.SubordinateListElement;
import org.jivesoftware.smackx.ikey.mechanism.IkeySignatureCreationMechanism;
import org.jivesoftware.smackx.ikey.util.canonicalization.XmlSecElementCanonicalizer;

import java.io.IOException;

public class IkeySignatureCreator {

    private final IkeySignatureCreationMechanism signatureCreationMechanism;
    private final XmlSecElementCanonicalizer elementCanonicalizer;

    public IkeySignatureCreator(IkeySignatureCreationMechanism signingMechanism, XmlSecElementCanonicalizer elementCanonicalizer) {
        this.signatureCreationMechanism = signingMechanism;
        this.elementCanonicalizer = elementCanonicalizer;
    }

    public ProofElement createProofFor(SubordinateListElement subordinateListElement) throws XMLParserException, IOException, CanonicalizationException {
        byte[] canonicalized = elementCanonicalizer.canonicalize(subordinateListElement);
        byte[] signature = signatureCreationMechanism.createSignature(canonicalized);

        return new ProofElement(Base64.toBase64String(signature));
    }
}
