/**
 * Пример, демонстрирующий проверку сертификата
 */
 
package kz.gamma;

import kz.gamma.jce.provider.GammaTechProvider;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.security.Provider;
import java.security.PublicKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.Base64;

public class SampleVerifyCert {

    public static void main(String[] args) {
        String fileNameCa = "d:\\Temp\\0\\4\\2\\2\\ca.cer";
        String fileNameCert ="d:\\Temp\\0\\4\\2\\2\\cert2.cer";
        Provider provider = new GammaTechProvider();
        Security.addProvider(provider);
        try {
            byte[] rootBytes = readData(fileNameCa);
            PublicKey rootPublicKey = CertificateFactory.getInstance("X.509", GammaTechProvider.PROVIDER_NAME)
                    .generateCertificate(new ByteArrayInputStream(rootBytes))
                    .getPublicKey();

            byte[] certBytes = readData(fileNameCert);
            Certificate cert = CertificateFactory.getInstance("X.509", GammaTechProvider.PROVIDER_NAME)
                    .generateCertificate(new ByteArrayInputStream(Base64.getDecoder().decode(certBytes)));

            System.out.println(rootPublicKey.getAlgorithm());
            cert.verify(rootPublicKey);

        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    private static byte[] readData(final String fileName) throws Exception {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(fileName);
            int size = fis.available();
            byte[] result = new byte[size];
            fis.read(result, 0, size);
            return result;
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
