import kz.gamma.asn1.cms.EnvelopedData;
import kz.gamma.cms.CMSGammaEnvelopedData;
import kz.gamma.jce.provider.GammaTechProvider;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

public class pkcs7_crypt {

    public static void main(String[] args) {
        Security.addProvider(new GammaTechProvider());
        try {
            X509Certificate certS = loadCert("/testCert/db1/db1_client1.cer");
            X509Certificate certR = loadCert("/testCert/db1/db1_client2.cer");

            byte[] buf = "Query-Answer123".getBytes(StandardCharsets.UTF_8);


//            data.addUnprotectedAttrs(new Attribute((new DERObjectIdentifier("1.2.840.113549.1.9.3")), new DERSet(new DERObjectIdentifier("1.2.840.113549.1.7.3"))));
//            data.addUnprotectedAttrs(new Attribute(new DERObjectIdentifier(LibraryWrapper.OID_PKCS9_SIGNINGTIME), new DERSet(new DERGeneralizedTime(new Date()))));
//            data.addUnprotectedAttrs(new Attribute((new DERObjectIdentifier("1.2.840.113549.1.9.13")), new DERSet(new DERPrintableString("DESCRIPTOR"))));
            EnvelopedData env = null;
            byte[] out = null;
            long time = System.currentTimeMillis();
            for (int i = 0; i < 1; i++) {
                CMSGammaEnvelopedData data = new CMSGammaEnvelopedData();
                data.cryptTextELGAM(buf);
                data.addKeyRecipient(certR);
                env = data.generateEnvelopedData(certS);
                out = env.getDEREncoded();
                data.close();

                if (i > 0 && i % 10 == 0) {
                    System.out.println("last pack time: " + (System.currentTimeMillis() - time) + "ms  iteration:" + i);
                    time = System.currentTimeMillis();
                }

            }

            FileOutputStream f0 = new FileOutputStream("/test/cmsJava.bin");
            f0.write(out);
            f0.close();
            System.out.println("OK");

        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(1);
        }

    }

    static X509Certificate loadCert(String filename) {
        File file = new File(filename);
        FileInputStream fi = null;
        try {
            fi = new FileInputStream(file);
            CertificateFactory cf = CertificateFactory.getInstance("X.509", "GAMMA");

            return (X509Certificate) cf.generateCertificate(fi);

        } catch (Exception ex1) {
            ex1.printStackTrace();
        } finally {
            try {
                if (fi != null)
                    fi.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        return null;
    }

}
