package kz.gamma;

import kz.gamma.jce.provider.GammaTechProvider;
import kz.gamma.tumarcsp.LibraryWrapper;
import kz.gamma.tumarcsp.TumarCspFunctions;

import java.io.ByteArrayInputStream;
import java.security.Security;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

/**
 * Пример получения сертификата из профайла TumarCSP
 */
public class TestLoadCert {
    public static void main(String[] args) throws Exception {
        TumarCspFunctions.initialize(null);
        Security.addProvider(new GammaTechProvider());

        Number hProv = TumarCspFunctions.cpAcquireContext("Profile://remote_user10", 0, 0);
        byte[] certBytes = getCert(hProv);
        X509Certificate cert = getCertFromByteArray(certBytes);
    }

    public static byte[] getCert(Number hProv) {
        Number hKey = TumarCspFunctions.cpGetUserKey(hProv, LibraryWrapper.AT_KEYEXCHANGE);
        byte[] serverCert = TumarCspFunctions.cpGetKeyParamData(hProv, hKey, LibraryWrapper.KP_CERTIFICATE, LibraryWrapper.ZERO);
        return serverCert;
    }

    public static X509Certificate getCertFromByteArray(byte[] cert) throws Exception {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate x509cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(cert));
        return x509cert;
    }
}


