package examples.localserver;

import kz.gov.pki.kalkan.jce.provider.KalkanProvider;
import kz.gov.pki.kalkan.xmldsig.KncaXS;
import kz.gov.pki.provider.exception.ProviderUtilException;
import kz.gov.pki.provider.utils.XMLUtil;
import kz.gov.pki.provider.utils.model.SigningEntity;
import ru.ussgroup.security.trusty.TrustyUtils;

import javax.security.auth.x500.X500PrivateCredential;
import java.security.Security;
import java.security.SignatureException;
import java.util.Collections;

/**
 * @author Yedil M.
 *
 * Подпись xml-документов
 */
public class DocumentSigner {

    static {
        KncaXS.loadXMLSecurity();
    }

    public static DocumentSignatureResponse signatureResponse(String data, String certificatePath, String certificatePin) {
        try {
            X500PrivateCredential credential = credential(certificatePath, certificatePin);
            String signature = signature(data, credential);

            return new DocumentSignatureResponse(data, signature, TrustyUtils.toBase64(credential.getCertificate()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static DocumentXmlSignatureResponse signatureXmlResponse(String xmlData, String certificatePath, String certificatePin) {
        try {
            X500PrivateCredential credential = credential(certificatePath, certificatePin);
            SigningEntity signingEntity = new SigningEntity(credential.getPrivateKey(), Collections.singletonList(credential.getCertificate()));
            return new DocumentXmlSignatureResponse(XMLUtil.createXmlSignature(signingEntity, xmlData, Security.getProvider(KalkanProvider.PROVIDER_NAME)));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String signature(String documentBody, X500PrivateCredential credential) throws SignatureException {
        return TrustyUtils.sign(documentBody, credential);
    }

    private static X500PrivateCredential credential(String path, String pin) {
        return TrustyUtils.loadCredentialFromFile(path, pin);
    }
}
