package kz.gamma;

import kz.gamma.asn1.ASN1InputStream;
import kz.gamma.asn1.ASN1OctetString;
import kz.gamma.asn1.DERObject;
import kz.gamma.asn1.DERObjectIdentifier;
import kz.gamma.asn1.cms.Attribute;
import kz.gamma.asn1.cms.AttributeTable;
import kz.gamma.cms.Pkcs7Data;
import kz.gamma.core.UtilCM;
import kz.gamma.jce.provider.GammaTechProvider;
import kz.gamma.jce.provider.JDKMessageDigest;
import kz.gamma.tumarcsp.TumarCspFunctions;

import java.io.FileInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.util.Enumeration;

public class SimpleParsePkcs7 {
    public static void main(String[] args) throws Exception {
        TumarCspFunctions.initialize(null);
        Security.addProvider(new GammaTechProvider());

        byte[] pkcs7 = readFromFile("c:/test/certex.p7b");

        byte[] hashFromPkcs = getHashFromPkcs7(pkcs7);
        System.out.println("hashFromPkcs7:" + UtilCM.array2hex(hashFromPkcs));
        int a = 1;
    }


    public static byte[] getHashFromPkcs7(byte[] pkcs7) throws Exception {
        Pkcs7Data pkcs7Data = new Pkcs7Data(pkcs7);
        AttributeTable attributeTable = pkcs7Data.getSignerInformation().getSignedAttributes();
        byte[] hashFromPkcs = null;
        if (attributeTable != null) {
            Attribute attribute = attributeTable.get(new DERObjectIdentifier("1.2.840.113549.1.9.4"));
            if (attribute != null) {
                Enumeration e = attribute.getAttrValues().getObjects();
                while (e.hasMoreElements()) {
                    DERObject o = (DERObject) e.nextElement();
                    ASN1InputStream aIn = new ASN1InputStream(o.getEncoded());
                    ASN1OctetString key = (ASN1OctetString) aIn.readObject();
                    hashFromPkcs = key.getOctets();
                }
            }
        }
        return hashFromPkcs;
    }

    public static byte[] readFromFile(String fileName) throws Exception {
        FileInputStream f = new FileInputStream(fileName);
        byte[] buf = new byte[f.available()];
        f.read(buf, 0, f.available());
        f.close();
        return buf;
    }


}


