Information

0
Story Points

Technologies

Decompiled Java File
package ee.sk.digidoc.factory;

import ee.sk.digidoc.Base64Util;
import ee.sk.digidoc.CertID;
import ee.sk.digidoc.DigiDocException;
import ee.sk.digidoc.Notary;
import ee.sk.digidoc.Signature;
import ee.sk.digidoc.SignedDoc;
import ee.sk.digidoc.factory.DigiDocFactory;
import ee.sk.digidoc.factory.NotaryFactory;
import ee.sk.digidoc.factory.TrustServiceFactory;
import ee.sk.utils.ConfigManager;
import ee.sk.utils.ConvertUtils;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.Enumeration;
import java.util.Vector;
import org.apache.log4j.Logger;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERTaggedObject;
import org.bouncycastle.asn1.ocsp.OCSPObjectIdentifiers;
import org.bouncycastle.asn1.ocsp.ResponderID;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.X509Extension;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.asn1.x509.X509Name;
import org.bouncycastle.jce.PrincipalUtil;
import org.bouncycastle.ocsp.BasicOCSPResp;
import org.bouncycastle.ocsp.CertificateID;
import org.bouncycastle.ocsp.OCSPReq;
import org.bouncycastle.ocsp.OCSPReqGenerator;
import org.bouncycastle.ocsp.OCSPResp;
import org.bouncycastle.ocsp.RevokedStatus;
import org.bouncycastle.ocsp.SingleResp;
import org.bouncycastle.ocsp.UnknownStatus;

public class BouncyCastleNotaryFactory implements NotaryFactory {
   public static final String nonceOid = "1.3.6.1.5.5.7.48.1.2";
   private X509Certificate m_signCert = null;
   private PrivateKey m_signKey = null;
   private boolean m_bSignRequests = false;
   private Logger m_logger = null;
   private static final int V_ASN1_OCTET_STRING = 4;

   public BouncyCastleNotaryFactory() {
      this.m_logger = Logger.getLogger(BouncyCastleNotaryFactory.class);
   }

   public X509Certificate getNotaryCert(String responderCN, String specificCertNr) {
      try {
         TrustServiceFactory ex = ConfigManager.instance().getTslFactory();
         boolean bUseLocal = ConfigManager.instance().getBooleanProperty("DIGIDOC_USE_LOCAL_TSL", false);
         return ex.findOcspByCN(responderCN, bUseLocal);
      } catch (Exception var5) {
         this.m_logger.error("Error searching responder cert for: " + responderCN + " - " + var5);
         return null;
      }
   }

   public X509Certificate[] getNotaryCerts(String responderCN, String specificCertNr) {
      try {
         TrustServiceFactory ex = ConfigManager.instance().getTslFactory();
         boolean bUseLocal = ConfigManager.instance().getBooleanProperty("DIGIDOC_USE_LOCAL_TSL", false);
         return ex.findOcspsByCNAndNr(responderCN, bUseLocal, specificCertNr);
      } catch (Exception var5) {
         this.m_logger.error("Error searching responder cert for: " + responderCN + " - " + var5);
         return null;
      }
   }

   public X509Certificate getCACert(String responderCN) {
      try {
         TrustServiceFactory ex = ConfigManager.instance().getTslFactory();
         boolean bUseLocal = ConfigManager.instance().getBooleanProperty("DIGIDOC_USE_LOCAL_TSL", false);
         X509Certificate cert = ex.findOcspByCN(responderCN, bUseLocal);
         if(cert != null) {
            return ex.findCaForCert(cert, bUseLocal, (Date)null);
         }
      } catch (Exception var5) {
         this.m_logger.error("Error searching responder ca cert for: " + responderCN + " - " + var5);
      }

      return null;
   }

   /** @deprecated */
   public Notary getConfirmation(byte[] nonce, X509Certificate signersCert, String notId, String httpFrom) throws DigiDocException {
      boolean bUseLocal = ConfigManager.instance().getBooleanProperty("DIGIDOC_USE_LOCAL_TSL", false);
      TrustServiceFactory tslFac = ConfigManager.instance().getTslFactory();
      X509Certificate caCert = tslFac.findCaForCert(signersCert, bUseLocal, (Date)null);
      X509Certificate ocspCert = tslFac.findOcspByCN(ConvertUtils.getCommonName(ConvertUtils.convX509Name(signersCert.getIssuerX500Principal())), bUseLocal);
      return this.getConfirmation(nonce, signersCert, caCert, ocspCert, notId, httpFrom);
   }

   public Notary getConfirmation(Signature sig, byte[] nonce, X509Certificate signersCert, X509Certificate caCert, X509Certificate notaryCert, String notId, String ocspUrl, String httpFrom, String format, String formatVer) throws DigiDocException {
      Notary not = null;
      OCSPReq req = null;
      OCSPResp resp = null;

      try {
         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("getConfirmation, nonce " + Base64Util.encode(nonce, 0) + " cert: " + (signersCert != null?signersCert.getSerialNumber().toString():"NULL") + " CA: " + (caCert != null?caCert.getSerialNumber().toString():"NULL") + " responder: " + (notaryCert != null?notaryCert.getSerialNumber().toString():"NULL") + " notId: " + notId + " signRequest: " + this.m_bSignRequests + " url: " + ocspUrl);
         }

         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("Check cert: " + (signersCert != null?signersCert.getSubjectDN().getName():"NULL"));
            this.m_logger.debug("Check CA cert: " + (caCert != null?caCert.getSubjectDN().getName():"NULL"));
         }

         req = this.createOCSPRequest(nonce, signersCert, caCert, this.m_bSignRequests, sig != null && sig.getSignedDoc().getFormat().equals("BDOC"));
         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("REQUEST:\n" + Base64Util.encode(req.getEncoded(), 0));
         }

         resp = this.sendRequestToUrl(req, ocspUrl, httpFrom, format, formatVer);
         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("RESPONSE:\n" + Base64Util.encode(resp.getEncoded(), 0));
         }

         this.verifyRespStatus(resp);
         not = this.parseAndVerifyResponse(sig, notId, signersCert, resp, nonce, notaryCert, caCert);
         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("Confirmation OK!");
         }
      } catch (DigiDocException var17) {
         this.m_logger.error("Error receiving OCSP confirmation: " + var17 + " nonce: " + ConvertUtils.bin2hex(nonce) + " len: " + nonce.length);

         try {
            byte[] ex2 = req.getEncoded();
            this.m_logger.error("OCSP req: " + ConvertUtils.bin2hex(ex2) + " len: " + ex2.length);
            ex2 = resp.getEncoded();
            this.m_logger.error("OCSP req: " + ConvertUtils.bin2hex(ex2) + " len: " + ex2.length);
         } catch (Exception var16) {
            this.m_logger.error("Error converting OCSP info: " + var16);
         }

         throw var17;
      } catch (Exception var18) {
         DigiDocException.handleException(var18, 66);
      }

      return not;
   }

   /** @deprecated */
   public Notary getConfirmation(byte[] nonce, X509Certificate signersCert, X509Certificate caCert, X509Certificate notaryCert, String notId, String httpFrom) throws DigiDocException {
      return this.getConfirmation((Signature)null, nonce, signersCert, caCert, notaryCert, notId, ConfigManager.instance().getProperty("DIGIDOC_OCSP_RESPONDER_URL"), httpFrom, (String)null, (String)null);
   }

   /** @deprecated */
   public Notary getConfirmation(Signature sig, X509Certificate signersCert, X509Certificate caCert) throws DigiDocException {
      Notary not = null;

      try {
         String ex = sig.getId().replace('S', 'N');
         byte[] nonce = SignedDoc.digestOfType(sig.getSignatureValue().getValue(), sig.getSignedDoc().getFormat().equals("BDOC")?"SHA-256":"SHA-1");
         X509Certificate notaryCert = null;
         if(sig.getUnsignedProperties() != null) {
            notaryCert = sig.getUnsignedProperties().getRespondersCertificate();
         }

         not = this.getConfirmation(sig, nonce, signersCert, caCert, notaryCert, ex, ConfigManager.instance().getProperty("DIGIDOC_OCSP_RESPONDER_URL"), sig.getHttpFrom(), sig.getSignedDoc().getFormat(), sig.getSignedDoc().getVersion());
         if(notaryCert == null && sig != null && sig.getUnsignedProperties() != null) {
            OCSPResp resp = new OCSPResp(not.getOcspResponseData());
            if(resp != null && resp.getResponseObject() != null) {
               String respId = this.responderIDtoString((BasicOCSPResp)resp.getResponseObject());
               TrustServiceFactory tslFac = ConfigManager.instance().getTslFactory();
               notaryCert = tslFac.findOcspByCN(SignedDoc.getCommonName(respId), true);
               if(notaryCert != null) {
                  sig.getUnsignedProperties().setRespondersCertificate(notaryCert);
               }

               CertID cid = new CertID(sig, notaryCert, 2);
               sig.addCertID(cid);
               cid.setUri("#" + sig.getId() + "-RESPONDER_CERT");
            }
         }
      } catch (DigiDocException var12) {
         throw var12;
      } catch (Exception var13) {
         DigiDocException.handleException(var13, 66);
      }

      return not;
   }

   public Notary getConfirmation(Signature sig, X509Certificate signersCert, X509Certificate caCert, X509Certificate notaryCert, String ocspUrl) throws DigiDocException {
      Notary not = null;

      try {
         String ex = sig.getId().replace('S', 'N');
         byte[] nonce = SignedDoc.digestOfType(sig.getSignatureValue().getValue(), sig.getSignedDoc().getFormat().equals("BDOC")?"SHA-256":"SHA-1");
         if(notaryCert == null && sig.getUnsignedProperties() != null) {
            notaryCert = sig.getUnsignedProperties().getRespondersCertificate();
         }

         not = this.getConfirmation(sig, nonce, signersCert, caCert, notaryCert, ex, ocspUrl, sig.getHttpFrom(), sig.getSignedDoc().getFormat(), sig.getSignedDoc().getVersion());
         if(sig != null && not != null && sig.getUnsignedProperties() != null) {
            sig.getUnsignedProperties().setNotary(not);
         }

         if(notaryCert == null && sig != null && sig.getUnsignedProperties() != null && sig.getUnsignedProperties().getNotary() != null) {
            OCSPResp resp = new OCSPResp(sig.getUnsignedProperties().getNotary().getOcspResponseData());
            if(resp != null && resp.getResponseObject() != null && notaryCert == null) {
               String respId = this.responderIDtoString((BasicOCSPResp)resp.getResponseObject());
               boolean bUseLocal = ConfigManager.instance().getBooleanProperty("DIGIDOC_USE_LOCAL_TSL", false);
               TrustServiceFactory tslFac = ConfigManager.instance().getTslFactory();
               notaryCert = tslFac.findOcspByCN(ConvertUtils.getCommonName(respId), bUseLocal);
               if(notaryCert != null) {
                  sig.getUnsignedProperties().setRespondersCertificate(notaryCert);
                  CertID cid = new CertID(sig, notaryCert, 2);
                  sig.addCertID(cid);
                  cid.setUri("#" + sig.getId() + "-RESPONDER_CERT");
               }
            }
         }
      } catch (DigiDocException var14) {
         throw var14;
      } catch (Exception var15) {
         DigiDocException.handleException(var15, 66);
      }

      return not;
   }

   /** @deprecated */
   public Notary getConfirmation(Signature sig, X509Certificate signersCert) throws DigiDocException {
      String notId = sig.getId().replace('S', 'N');
      byte[] nonce = SignedDoc.digestOfType(sig.getSignatureValue().getValue(), sig.getSignedDoc().getFormat().equals("BDOC")?"SHA-256":"SHA-1");
      boolean bUseLocal = ConfigManager.instance().getBooleanProperty("DIGIDOC_USE_LOCAL_TSL", false);
      TrustServiceFactory tslFac = ConfigManager.instance().getTslFactory();
      X509Certificate caCert = tslFac.findCaForCert(signersCert, bUseLocal, (Date)null);
      X509Certificate ocspCert = tslFac.findOcspByCN(ConvertUtils.getCommonName(ConvertUtils.convX509Name(signersCert.getIssuerX500Principal())), bUseLocal);
      return this.getConfirmation(nonce, signersCert, caCert, ocspCert, notId, sig.getHttpFrom());
   }

   private String composeHttpFrom() {
      String sFrom = null;

      try {
         NetworkInterface ex2 = null;
         Enumeration eNi = NetworkInterface.getNetworkInterfaces();
         if(eNi != null && eNi.hasMoreElements()) {
            ex2 = (NetworkInterface)eNi.nextElement();
         }

         if(ex2 != null) {
            InetAddress ia = null;
            Enumeration eA = ex2.getInetAddresses();
            if(eA != null && eA.hasMoreElements()) {
               ia = (InetAddress)eA.nextElement();
            }

            if(ia != null) {
               sFrom = ia.getHostAddress();
            }

            if(this.m_logger.isDebugEnabled()) {
               this.m_logger.debug("FROM: " + sFrom);
            }
         }
      } catch (Exception var6) {
         this.m_logger.error("Error finding ip-adr: " + var6);
      }

      return sFrom;
   }

   /** @deprecated */
   public OCSPResp checkCertificate(X509Certificate cert) throws DigiDocException {
      return this.checkCertificate(cert, this.composeHttpFrom());
   }

   /** @deprecated */
   public OCSPResp checkCertificate(X509Certificate cert, String httpFrom) throws DigiDocException {
      OCSPResp resp = null;

      try {
         DigiDocFactory ex = ConfigManager.instance().getDigiDocFactory();
         TrustServiceFactory tslFac = ConfigManager.instance().getTslFactory();
         boolean bUseLocal = ConfigManager.instance().getBooleanProperty("DIGIDOC_USE_LOCAL_TSL", false);
         X509Certificate caCert = tslFac.findCaForCert(cert, bUseLocal, (Date)null);
         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("Find CA for: " + SignedDoc.getCommonName(ConvertUtils.convX509Name(cert.getIssuerX500Principal())));
            this.m_logger.debug("Check cert: " + cert.getSubjectDN().getName());
            this.m_logger.debug("Check CA cert: " + caCert.getSubjectDN().getName());
         }

         String strTime = (new Date()).toString();
         byte[] nonce1 = SignedDoc.digest(strTime.getBytes());
         OCSPReq req = this.createOCSPRequest(nonce1, cert, caCert, this.m_bSignRequests, false);
         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("Sending ocsp request: " + req.getEncoded().length + " bytes");
            this.m_logger.debug("REQUEST:\n" + Base64Util.encode(req.getEncoded(), 0));
         }

         String ocspUrl = tslFac.findOcspUrlForCert(cert, 0, bUseLocal);
         resp = this.sendRequestToUrl(req, ocspUrl, httpFrom, (String)null, (String)null);
         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("Got ocsp response: " + resp.getEncoded().length + " bytes");
            this.m_logger.debug("RESPONSE:\n" + Base64Util.encode(resp.getEncoded(), 0));
         }

         this.verifyRespStatus(resp);
         BasicOCSPResp basResp = (BasicOCSPResp)resp.getResponseObject();
         byte[] nonce2 = this.getNonce(basResp, (SignedDoc)null);
         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("Nonce1: " + (nonce1 != null?ConvertUtils.bin2hex(nonce1) + " len: " + nonce1.length:"NULL") + " nonce2: " + (nonce2 != null?ConvertUtils.bin2hex(nonce2) + " len: " + nonce2.length:"NULL"));
         }

         if(!SignedDoc.compareDigests(nonce1, nonce2)) {
            throw new DigiDocException(69, "Invalid nonce value! Possible replay attack!", (Throwable)null);
         }

         try {
            String ex1 = this.responderIDtoString(basResp);
            X509Certificate notaryCert = this.getNotaryCert(ConvertUtils.getCommonName(ex1), (String)null);
            boolean bOk = false;
            if(notaryCert == null) {
               throw new DigiDocException(70, "Responder cert not found for: " + ex1, (Throwable)null);
            }

            bOk = basResp.verify(notaryCert.getPublicKey(), "BC");
            if(!bOk) {
               throw new DigiDocException(70, "OCSP verification error!", (Throwable)null);
            }
         } catch (Exception var17) {
            this.m_logger.error("OCSP Signature verification error!!!", var17);
            DigiDocException.handleException(var17, 70);
         }

         this.checkCertStatus(cert, basResp, caCert);
      } catch (DigiDocException var18) {
         throw var18;
      } catch (Exception var19) {
         DigiDocException.handleException(var19, 66);
      }

      return resp;
   }

   /** @deprecated */
   public OCSPResp sendCertOcsp(X509Certificate cert, X509Certificate caCert, String url, ByteArrayOutputStream bosNonce, StringBuffer sbRespId, ByteArrayOutputStream bosReq, String httpFrom) throws DigiDocException {
      try {
         OCSPResp ex = null;
         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("Find CA for: " + SignedDoc.getCommonName(ConvertUtils.convX509Name(cert.getIssuerX500Principal())));
            this.m_logger.debug("Check cert: " + cert.getSubjectDN().getName());
            this.m_logger.debug("Check CA cert: " + caCert.getSubjectDN().getName());
         }

         String strTime = (new Date()).toString();
         byte[] nonce1 = SignedDoc.digest(strTime.getBytes());
         bosNonce.write(nonce1);
         OCSPReq req = this.createOCSPRequest(nonce1, cert, caCert, false, false);
         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("Sending ocsp request: " + req.getEncoded().length + " bytes");
            this.m_logger.debug("REQUEST:\n" + Base64Util.encode(req.getEncoded(), 0));
         }

         if(req != null && bosReq != null) {
            bosReq.write(req.getEncoded());
         }

         ex = this.sendRequestToUrl(req, url, httpFrom, (String)null, (String)null);
         if(ex != null) {
            BasicOCSPResp basResp = (BasicOCSPResp)ex.getResponseObject();
            String sRespId = this.responderIDtoString(basResp);
            if(sRespId != null) {
               sbRespId.append(sRespId);
            }
         }

         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("Got ocsp response: " + (ex != null?ex.getEncoded().length:0) + " bytes");
            if(ex != null) {
               this.m_logger.debug("RESPONSE:\n" + Base64Util.encode(ex.getEncoded(), 0));
            }
         }

         return ex;
      } catch (DigiDocException var14) {
         throw var14;
      } catch (Exception var15) {
         DigiDocException.handleException(var15, 66);
         return null;
      }
   }

   /** @deprecated */
   public boolean checkCertOcsp(OCSPResp resp, X509Certificate cert, X509Certificate ocspCert, byte[] nonce1, X509Certificate caCert) throws DigiDocException {
      try {
         this.verifyRespStatus(resp);
         BasicOCSPResp ex = (BasicOCSPResp)resp.getResponseObject();
         byte[] nonce2 = this.getNonce(ex, (SignedDoc)null);
         if(!SignedDoc.compareDigests(nonce1, nonce2)) {
            throw new DigiDocException(69, "Invalid nonce value! Possible replay attack!", (Throwable)null);
         } else {
            boolean bOk = false;

            try {
               this.responderIDtoString(ex);
               bOk = ex.verify(ocspCert.getPublicKey(), "BC");
            } catch (Exception var10) {
               this.m_logger.error("OCSP Signature verification error!!!", var10);
               DigiDocException.handleException(var10, 70);
            }

            this.checkCertStatusWithCa(cert, ex, caCert);
            return bOk;
         }
      } catch (DigiDocException var11) {
         throw var11;
      } catch (Exception var12) {
         DigiDocException.handleException(var12, 66);
         return false;
      }
   }

   /** @deprecated */
   public void checkCertificateOcspOrCrl(X509Certificate cert, boolean bUseOcsp) throws DigiDocException {
      try {
         boolean ex = ConfigManager.instance().getBooleanProperty("DIGIDOC_USE_LOCAL_TSL", false);
         TrustServiceFactory tslFac = ConfigManager.instance().getTslFactory();
         X509Certificate caCert = tslFac.findCaForCert(cert, ex, (Date)null);
         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("Find CA for: " + SignedDoc.getCommonName(ConvertUtils.convX509Name(cert.getIssuerX500Principal())));
            this.m_logger.debug("Check cert: " + cert.getSubjectDN().getName());
            this.m_logger.debug("Check CA cert: " + caCert.getSubjectDN().getName());
         }

         String strTime = (new Date()).toString();
         byte[] nonce1 = SignedDoc.digest(strTime.getBytes());
         OCSPReq req = this.createOCSPRequest(nonce1, cert, caCert, this.m_bSignRequests, false);
         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("Sending ocsp request: " + req.getEncoded().length + " bytes");
            this.m_logger.debug("REQUEST:\n" + Base64Util.encode(req.getEncoded(), 0));
         }

         OCSPResp resp = this.sendRequest(req, (String)null, (String)null, (String)null);
         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("Got ocsp response: " + resp.getEncoded().length + " bytes");
            this.m_logger.debug("RESPONSE:\n" + Base64Util.encode(resp.getEncoded(), 0));
         }

         this.verifyRespStatus(resp);
         BasicOCSPResp basResp = (BasicOCSPResp)resp.getResponseObject();
         byte[] nonce2 = this.getNonce(basResp, (SignedDoc)null);
         if(!SignedDoc.compareDigests(nonce1, nonce2)) {
            throw new DigiDocException(69, "Invalid nonce value! Possible replay attack!", (Throwable)null);
         }

         try {
            String ex1 = this.responderIDtoString(basResp);
            X509Certificate notaryCert = this.getNotaryCert(SignedDoc.getCommonName(ex1), (String)null);
            boolean bOk = basResp.verify(notaryCert.getPublicKey(), "BC");
            if(!bOk) {
               this.m_logger.error("OCSP Signature verification error!!!");
               throw new DigiDocException(70, "OCSP Signature verification error!!!", (Throwable)null);
            }
         } catch (Exception var15) {
            this.m_logger.error("OCSP Signature verification error!!!", var15);
            DigiDocException.handleException(var15, 70);
         }

         this.checkCertStatus(cert, basResp, caCert);
      } catch (DigiDocException var16) {
         throw var16;
      } catch (Exception var17) {
         DigiDocException.handleException(var17, 66);
      }

   }

   private Notary parseAndVerifyResponse(Signature sig, OCSPResp resp, byte[] nonce1) throws DigiDocException {
      String notId = sig.getId().replace('S', 'N');
      X509Certificate sigCert = sig.getKeyInfo().getSignersCertificate();
      return this.parseAndVerifyResponse(sig, notId, sigCert, resp, nonce1, (X509Certificate)null, (X509Certificate)null);
   }

   private Notary parseAndVerifyResponse(Signature sig, String notId, X509Certificate signersCert, OCSPResp resp, byte[] nonce1, X509Certificate notaryCert, X509Certificate caCert) throws DigiDocException {
      Notary not = null;
      if(resp != null && resp.getStatus() == 0) {
         try {
            BasicOCSPResp ex = (BasicOCSPResp)resp.getResponseObject();
            String respId = this.responderIDtoString(ex);
            if(notaryCert == null) {
               String bOk = ConvertUtils.getCommonName(respId);
               notaryCert = this.getNotaryCert(bOk, (String)null);
               if(this.m_logger.isDebugEnabled()) {
                  this.m_logger.debug("Find notary cert: " + bOk + " found: " + (notaryCert != null?"OK":"NULL"));
               }
            }

            if(notaryCert == null) {
               throw new DigiDocException(70, "Notary cert not found for: " + respId, (Throwable)null);
            }

            boolean var18 = false;

            try {
               var18 = ex.verify(notaryCert.getPublicKey(), "BC");
            } catch (Exception var15) {
               this.m_logger.error("OCSP Signature verification error!!!", var15);
               DigiDocException.handleException(var15, 70);
            }

            if(!var18) {
               this.m_logger.error("OCSP Signature verification error!!!");
               throw new DigiDocException(70, "OCSP Signature verification error!!!", (Throwable)null);
            }

            if(this.m_logger.isDebugEnabled() && notaryCert != null) {
               this.m_logger.debug("Using responder cert: " + notaryCert.getSerialNumber().toString());
            }

            byte[] nonce2 = this.getNonce(ex, sig != null?sig.getSignedDoc():null);
            boolean ok = true;
            if(nonce1 == null || nonce2 == null || nonce1.length != nonce2.length) {
               ok = false;
            }

            for(int i = 0; nonce1 != null && nonce2 != null && i < nonce1.length; ++i) {
               if(nonce1[i] != nonce2[i]) {
                  ok = false;
               }
            }

            if(this.m_logger.isDebugEnabled() && notaryCert != null) {
               this.m_logger.debug("NONCE ddoc: " + (sig != null?sig.getSignedDoc().getFormat():"NULL") + " ok: " + ok);
            }

            if(!ok && sig != null) {
               this.m_logger.error("DDOC ver: " + sig.getSignedDoc().getVersion() + " SIG: " + sig.getId() + " Real nonce: " + Base64Util.encode(nonce2, 0) + " SigVal hash: " + Base64Util.encode(nonce1, 0) + " SigVal hash hex: " + ConvertUtils.bin2hex(nonce1));
               throw new DigiDocException(71, "OCSP response\'s nonce doesn\'t match the requests nonce!", (Throwable)null);
            }

            this.checkCertStatus(signersCert, ex, caCert);
            not = new Notary(notId, resp.getEncoded(), respId, ex.getResponseData().getProducedAt());
            if(notaryCert != null) {
               not.setCertNr(notaryCert.getSerialNumber().toString());
            }
         } catch (DigiDocException var16) {
            throw var16;
         } catch (Exception var17) {
            DigiDocException.handleException(var17, 72);
         }

         return not;
      } else if(resp.getStatus() == 6) {
         throw new DigiDocException(163, "OCSP response unauthorized! ", (Throwable)null);
      } else {
         throw new DigiDocException(69, "OCSP response unsuccessfull!", (Throwable)null);
      }
   }

   private void checkCertStatus(Signature sig, BasicOCSPResp basResp) throws DigiDocException {
      this.checkCertStatus(sig.getKeyInfo().getSignersCertificate(), basResp, (X509Certificate)null);
   }

   private void checkCertStatus(X509Certificate cert, BasicOCSPResp basResp, X509Certificate caCert) throws DigiDocException {
      try {
         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("Checking response status, CERT: " + (cert != null?cert.getSubjectDN().getName():"NULL") + " SEARCH: " + (cert != null?SignedDoc.getCommonName(ConvertUtils.convX509Name(cert.getIssuerX500Principal())):"NULL"));
         }

         if(cert == null) {
            throw new DigiDocException(92, "No certificate to check! Error reading certificate from file?", (Throwable)null);
         } else {
            TrustServiceFactory ex = ConfigManager.instance().getTslFactory();
            boolean bUseLocal = ConfigManager.instance().getBooleanProperty("DIGIDOC_USE_LOCAL_TSL", false);
            if(caCert == null) {
               caCert = ex.findCaForCert(cert, bUseLocal, (Date)null);
            }

            if(this.m_logger.isDebugEnabled()) {
               this.m_logger.debug("CA cert: " + (caCert != null?caCert.getSubjectDN().getName():"NULL"));
               this.m_logger.debug("RESP: " + basResp);
               this.m_logger.debug("CERT: " + (cert != null?cert.getSubjectDN().getName():"NULL") + " ISSUER: " + ConvertUtils.convX509Name(cert.getIssuerX500Principal()) + " nr: " + (caCert != null?ConvertUtils.bin2hex(caCert.getSerialNumber().toByteArray()):"NULL"));
            }

            if(caCert == null) {
               throw new DigiDocException(92, "Unknown CA cert: " + cert.getIssuerDN().getName(), (Throwable)null);
            } else {
               SingleResp[] sresp = basResp.getResponseData().getResponses();
               CertificateID rc = this.creatCertReq(cert, caCert);
               if(this.m_logger.isDebugEnabled()) {
                  this.m_logger.debug("Search alg: " + rc.getHashAlgOID() + " cert ser: " + cert.getSerialNumber().toString() + " serial: " + rc.getSerialNumber() + " issuer: " + Base64Util.encode(rc.getIssuerKeyHash()) + " subject: " + Base64Util.encode(rc.getIssuerNameHash()));
               }

               boolean ok = false;

               for(int i = 0; i < sresp.length; ++i) {
                  CertificateID id = sresp[i].getCertID();
                  if(id != null) {
                     if(this.m_logger.isDebugEnabled()) {
                        this.m_logger.debug("Got alg: " + id.getHashAlgOID() + " serial: " + id.getSerialNumber() + " issuer: " + Base64Util.encode(id.getIssuerKeyHash()) + " subject: " + Base64Util.encode(id.getIssuerNameHash()));
                     }

                     if(rc.getHashAlgOID().equals(id.getHashAlgOID()) && rc.getSerialNumber().equals(id.getSerialNumber()) && SignedDoc.compareDigests(rc.getIssuerKeyHash(), id.getIssuerKeyHash()) && SignedDoc.compareDigests(rc.getIssuerNameHash(), id.getIssuerNameHash())) {
                        if(this.m_logger.isDebugEnabled()) {
                           this.m_logger.debug("Found it!");
                        }

                        ok = true;
                        Object status = sresp[i].getCertStatus();
                        if(status != null) {
                           if(this.m_logger.isDebugEnabled()) {
                              this.m_logger.debug("CertStatus: " + status.getClass().getName());
                           }

                           if(status instanceof RevokedStatus) {
                              this.m_logger.error("Certificate has been revoked!");
                              throw new DigiDocException(91, "Certificate has been revoked!", (Throwable)null);
                           }

                           if(status instanceof UnknownStatus) {
                              this.m_logger.error("Certificate status is unknown!");
                              throw new DigiDocException(92, "Certificate status is unknown!", (Throwable)null);
                           }
                        }
                        break;
                     }
                  }
               }

               if(!ok) {
                  if(this.m_logger.isDebugEnabled()) {
                     this.m_logger.debug("Error checkCertStatus - not found ");
                  }

                  throw new DigiDocException(88, "Bad OCSP response status!", (Throwable)null);
               }
            }
         }
      } catch (DigiDocException var12) {
         throw var12;
      } catch (Exception var13) {
         this.m_logger.error("Error checkCertStatus: " + var13);
         var13.printStackTrace();
         throw new DigiDocException(88, "Error checking OCSP response status!", (Throwable)null);
      }
   }

   private void checkCertStatusWithCa(X509Certificate cert, BasicOCSPResp basResp, X509Certificate caCert) throws DigiDocException {
      try {
         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("Checking response status, CERT: " + cert.getSubjectDN().getName() + " SEARCH: " + SignedDoc.getCommonName(ConvertUtils.convX509Name(cert.getIssuerX500Principal())));
         }

         DigiDocFactory ex = ConfigManager.instance().getDigiDocFactory();
         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("CA cert: " + (caCert == null?"NULL":"OK"));
            this.m_logger.debug("RESP: " + basResp);
            this.m_logger.debug("CERT: " + cert.getSubjectDN().getName() + " ISSUER: " + ConvertUtils.convX509Name(cert.getIssuerX500Principal()));
            if(caCert != null) {
               this.m_logger.debug("CA CERT: " + caCert.getSubjectDN().getName());
            }
         }

         SingleResp[] sresp = basResp.getResponseData().getResponses();
         CertificateID rc = this.creatCertReq(cert, caCert);
         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("Search alg: " + rc.getHashAlgOID() + " serial: " + rc.getSerialNumber() + " issuer: " + Base64Util.encode(rc.getIssuerKeyHash()) + " subject: " + Base64Util.encode(rc.getIssuerNameHash()));
         }

         boolean ok = false;

         for(int i = 0; i < sresp.length; ++i) {
            CertificateID id = sresp[i].getCertID();
            if(id != null) {
               if(this.m_logger.isDebugEnabled()) {
                  this.m_logger.debug("Got alg: " + id.getHashAlgOID() + " serial: " + id.getSerialNumber() + " issuer: " + Base64Util.encode(id.getIssuerKeyHash()) + " subject: " + Base64Util.encode(id.getIssuerNameHash()));
               }

               if(rc.getHashAlgOID().equals(id.getHashAlgOID()) && rc.getSerialNumber().equals(id.getSerialNumber()) && SignedDoc.compareDigests(rc.getIssuerKeyHash(), id.getIssuerKeyHash()) && SignedDoc.compareDigests(rc.getIssuerNameHash(), id.getIssuerNameHash())) {
                  if(this.m_logger.isDebugEnabled()) {
                     this.m_logger.debug("Found it!");
                  }

                  ok = true;
                  Object status = sresp[i].getCertStatus();
                  if(status != null) {
                     if(this.m_logger.isDebugEnabled()) {
                        this.m_logger.debug("CertStatus: " + status.getClass().getName());
                     }

                     if(status instanceof RevokedStatus) {
                        this.m_logger.error("Certificate has been revoked!");
                        throw new DigiDocException(88, "Certificate has been revoked!", (Throwable)null);
                     }

                     if(status instanceof UnknownStatus) {
                        this.m_logger.error("Certificate status is unknown!");
                        throw new DigiDocException(88, "Certificate status is unknown!", (Throwable)null);
                     }
                  }
                  break;
               }
            }
         }

         if(!ok) {
            if(this.m_logger.isDebugEnabled()) {
               this.m_logger.debug("Error checkCertStatus - not found ");
            }

            throw new DigiDocException(88, "Bad OCSP response status!", (Throwable)null);
         }
      } catch (DigiDocException var11) {
         throw var11;
      } catch (Exception var12) {
         this.m_logger.error("Error checkCertStatus: " + var12);
         var12.printStackTrace();
         throw new DigiDocException(88, "Error checking OCSP response status!", (Throwable)null);
      }
   }

   public Notary parseAndVerifyResponse(Signature sig, Notary not) throws DigiDocException {
      try {
         OCSPResp ex = new OCSPResp(not.getOcspResponseData());
         BasicOCSPResp basResp = (BasicOCSPResp)ex.getResponseObject();
         X509Certificate[] lNotCerts = null;
         if(sig != null && sig.getUnsignedProperties() != null && sig.getUnsignedProperties().getRespondersCertificate() == null) {
            throw new DigiDocException(53, "OCSP responders certificate is required!", (Throwable)null);
         }

         int i;
         try {
            String ok = this.responderIDtoString(basResp);
            if(this.m_logger.isDebugEnabled()) {
               this.m_logger.debug("SIG: " + (sig == null?"NULL":sig.getId()));
               this.m_logger.debug("UP: " + (sig.getUnsignedProperties() == null?"NULL":"OK: " + sig.getUnsignedProperties().getNotary().getId()));
               this.m_logger.debug("RESP-CERT: " + (sig.getUnsignedProperties().getRespondersCertificate() == null?"NULL":"OK"));
               this.m_logger.debug("RESP-ID: " + ok);
               CertID nonce1 = sig.getCertID(2);
               if(nonce1 != null) {
                  this.m_logger.debug("CID: " + nonce1.getType() + " id: " + nonce1.getId() + ", " + nonce1.getSerial() + " issuer: " + nonce1.getIssuer());
               }

               this.m_logger.debug("RESP: " + Base64Util.encode(ex.getEncoded()));
            }

            if(lNotCerts == null && sig != null) {
               String var14 = sig.getUnsignedProperties().getRespondersCertificate().getSerialNumber().toString();
               String nonce2 = ok;
               if(ok.indexOf("CN") != -1) {
                  nonce2 = ConvertUtils.getCommonName(ok);
               }

               if(nonce2.startsWith("byKey: ")) {
                  nonce2 = nonce2.substring("byKey: ".length());
               }

               i = nonce2.indexOf(44);
               if(i > 0) {
                  nonce2 = nonce2.substring(0, i);
               }

               if(this.m_logger.isDebugEnabled()) {
                  this.m_logger.debug("Search not cert by: " + nonce2 + " nr: " + var14);
               }

               lNotCerts = this.getNotaryCerts(nonce2, (String)null);
            }

            if(lNotCerts == null || lNotCerts.length == 0) {
               throw new DigiDocException(117, "No certificate for responder: \'" + ok + "\' found in local certificate store!", (Throwable)null);
            }

            boolean var15 = false;

            for(int var18 = 0; lNotCerts != null && var18 < lNotCerts.length && !var15; ++var18) {
               Object var17 = lNotCerts[var18];
               if(this.m_logger.isDebugEnabled()) {
                  this.m_logger.debug("Verify using responders cert: " + (var17 != null?ConvertUtils.getCommonName(((X509Certificate)var17).getSubjectDN().getName()) + " nr: " + ((X509Certificate)var17).getSerialNumber().toString():"NULL"));
               }

               var15 = basResp.verify(((X509Certificate)var17).getPublicKey(), "BC");
               if(this.m_logger.isDebugEnabled()) {
                  this.m_logger.debug("OCSP resp: " + (basResp != null?this.responderIDtoString(basResp):"NULL") + " verify using: " + (var17 != null?ConvertUtils.getCommonName(((X509Certificate)var17).getSubjectDN().getName()):"NULL") + " verify: " + var15);
               }
            }

            if(!var15) {
               throw new DigiDocException(70, "OCSP verification error!", (Throwable)null);
            }
         } catch (Exception var10) {
            this.m_logger.error("Signature verification error: " + var10);
            var10.printStackTrace();
            DigiDocException.handleException(var10, 70);
         }

         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("Verif sig: " + sig.getId() + " format: " + sig.getSignedDoc().getFormat() + " nonce policy: " + sig.hasBdoc2NoncePolicy());
         }

         boolean var13 = true;
         if(sig.getSignedDoc().getFormat().equals("SK-XML") || sig.getSignedDoc().getFormat().equals("DIGIDOC-XML") || sig.getSignedDoc().getFormat().equals("BDOC") && sig.hasBdoc2NoncePolicy()) {
            byte[] var16 = SignedDoc.digestOfType(sig.getSignatureValue().getValue(), sig.getSignedDoc().getFormat().equals("BDOC")?"SHA-256":"SHA-1");
            byte[] var19 = this.getNonce(basResp, sig.getSignedDoc());
            if(var16 == null || var19 == null || var16.length != var19.length) {
               var13 = false;
            }

            for(i = 0; var16 != null && var19 != null && i < var16.length; ++i) {
               if(var16[i] != var19[i]) {
                  var13 = false;
               }
            }

            if(!var13 && sig.getSignedDoc() != null) {
               if(this.m_logger.isDebugEnabled()) {
                  this.m_logger.debug("SigVal\n---\n" + Base64Util.encode(sig.getSignatureValue().getValue()) + "\n---\nOCSP\n---\n" + Base64Util.encode(not.getOcspResponseData()) + "\n---\n");
                  this.m_logger.debug("DDOC ver: " + sig.getSignedDoc().getVersion() + " SIG: " + sig.getId() + " NOT: " + not.getId() + " Real nonce: " + (var19 != null?Base64Util.encode(var19, 0):"NULL") + " noncelen: " + (var19 != null?var19.length:0) + " SigVal hash: " + Base64Util.encode(var16, 0) + " SigVal hash hex: " + ConvertUtils.bin2hex(var16) + " svlen: " + (var16 != null?var16.length:0));
                  this.m_logger.debug("SIG:\n---\n" + sig.toString() + "\n--\n");
               }

               throw new DigiDocException(71, "OCSP response\'s nonce doesn\'t match the requests nonce!", (Throwable)null);
            }
         }

         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("Verify not: " + not.getId());
         }

         this.checkCertStatus(sig, basResp);
         not.setProducedAt(basResp.getResponseData().getProducedAt());
         not.setResponderId(this.responderIDtoString(basResp));
      } catch (DigiDocException var11) {
         throw var11;
      } catch (Exception var12) {
         DigiDocException.handleException(var12, 72);
      }

      return not;
   }

   private String responderIDtoString(BasicOCSPResp basResp) {
      if(basResp != null) {
         ResponderID respid = basResp.getResponseData().getResponderId().toASN1Object();
         ASN1Primitive o = ((DERTaggedObject)respid.toASN1Object()).getObject();
         if(o instanceof DEROctetString) {
            DEROctetString name1 = (DEROctetString)o;
            return "byKey: " + SignedDoc.bin2hex(name1.getOctets());
         } else {
            X509Name name = new X509Name((ASN1Sequence)o);
            return "byName: " + name.toString();
         }
      } else {
         return null;
      }
   }

   private byte[] getNonce(BasicOCSPResp basResp, SignedDoc sdoc) {
      if(basResp == null) {
         return null;
      } else {
         try {
            X509Extensions ex = basResp.getResponseData().getResponseExtensions();
            X509Extension ex1 = ex.getExtension(new DERObjectIdentifier("1.3.6.1.5.5.7.48.1.2"));
            byte[] nonce2 = null;
            if(ex1 != null && ex1.getValue() != null) {
               nonce2 = ex1.getValue().getOctets();
            }

            boolean bCheckOcspNonce = ConfigManager.instance().getBooleanProperty("CHECK_OCSP_NONCE", false);
            if(sdoc != null && sdoc.getFormat() != null && sdoc.getFormat().equals("BDOC")) {
               bCheckOcspNonce = true;
            }

            if(sdoc != null && sdoc.getFormat() != null && sdoc.getFormat().equals("SK-XML")) {
               bCheckOcspNonce = false;
            }

            if(this.m_logger.isDebugEnabled() && nonce2 != null) {
               this.m_logger.debug("Nonce hex: " + ConvertUtils.bin2hex(nonce2) + " b64: " + Base64Util.encode(nonce2) + " len: " + nonce2.length);
            }

            boolean bAsn1 = false;
            String sType = null;
            byte[] b;
            if((sdoc != null && sdoc.getFormat() != null && sdoc.getFormat().equals("DIGIDOC-XML") || sdoc == null) && nonce2 != null && nonce2.length == 22) {
               b = new byte[20];
               System.arraycopy(nonce2, nonce2.length - 20, b, 0, 20);
               nonce2 = b;
               bAsn1 = true;
               sType = "ASN1-NONCE";
            }

            if(sdoc != null && sdoc.getFormat() != null && sdoc.getFormat().equals("BDOC") && nonce2 != null) {
               sType = ConvertUtils.findDigType(nonce2);
               if(sType != null) {
                  b = ConvertUtils.removePrefix(nonce2);
                  nonce2 = b;
               }

               bAsn1 = sType != null;
            }

            if(this.m_logger.isDebugEnabled()) {
               this.m_logger.debug("Nonce hex: " + ConvertUtils.bin2hex(nonce2) + " b64: " + Base64Util.encode(nonce2) + " len: " + nonce2.length + " type: " + sType);
            }

            if(!bAsn1 && bCheckOcspNonce) {
               throw new DigiDocException(71, "Invalid nonce: " + (nonce2 != null?ConvertUtils.bin2hex(nonce2) + " length: " + nonce2.length:"NO-NONCE") + "!", (Throwable)null);
            } else {
               return nonce2;
            }
         } catch (Exception var10) {
            this.m_logger.error("Error reading ocsp nonce: " + var10);
            var10.printStackTrace();
            return null;
         }
      }
   }

   private void verifyRespStatus(OCSPResp resp) throws DigiDocException {
      int status = resp.getStatus();
      switch(status) {
      case 0:
         break;
      case 1:
         this.m_logger.error("Your request did not fit the RFC 2560 syntax!");
         break;
      case 2:
         this.m_logger.error("An internal error occured in the OCSP Server!");
         break;
      case 3:
         this.m_logger.error("The server was too busy to answer you!");
         break;
      case 4:
      default:
         this.m_logger.error("Unknown OCSPResponse status code! " + status);
         break;
      case 5:
         this.m_logger.error("Your request was not signed!");
         break;
      case 6:
         this.m_logger.error("The server could not authenticate you!");
      }

      if(resp == null || resp.getStatus() != 0) {
         throw new DigiDocException(69, "OCSP response unsuccessfull! ", (Throwable)null);
      }
   }

   private CertificateID creatCertReq(X509Certificate signersCert, X509Certificate caCert) throws NoSuchAlgorithmException, NoSuchProviderException, CertificateEncodingException, DigiDocException, Exception {
      return new CertificateID("1.3.14.3.2.26", caCert, signersCert.getSerialNumber());
   }

   private OCSPReq createOCSPRequest(byte[] nonce, X509Certificate signersCert, X509Certificate caCert, boolean bSigned, boolean bBdoc) throws DigiDocException {
      OCSPReq req = null;
      OCSPReqGenerator ocspRequest = new OCSPReqGenerator();

      try {
         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("Request for: " + (signersCert != null?ConvertUtils.getCommonName(ConvertUtils.convX509Name(signersCert.getSubjectX500Principal())):"NULL") + " CA: " + (caCert != null?ConvertUtils.getCommonName(ConvertUtils.convX509Name(caCert.getSubjectX500Principal())):"NULL"));
         }

         if(signersCert == null) {
            throw new DigiDocException(65, "Missing signers cert for ocsp request", (Throwable)null);
         }

         if(caCert == null) {
            throw new DigiDocException(65, "Missing CA cert for ocsp request", (Throwable)null);
         }

         CertificateID ex = this.creatCertReq(signersCert, caCert);
         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("Request for: " + ex.getHashAlgOID() + " serial: " + ex.getSerialNumber() + " issuer: " + ConvertUtils.bin2hex(ex.getIssuerKeyHash()) + " subject: " + ConvertUtils.bin2hex(ex.getIssuerNameHash()) + " nonce: " + ConvertUtils.bin2hex(nonce) + " len: " + nonce.length);
         }

         ocspRequest.addRequest(ex);
         byte[] name;
         if(nonce != null && nonce[0] != 4 && !bBdoc) {
            name = new byte[nonce.length + 2];
            name[0] = 4;
            name[1] = (byte)nonce.length;
            System.arraycopy(nonce, 0, name, 2, nonce.length);
            if(this.m_logger.isDebugEnabled()) {
               this.m_logger.debug("Nonce in: " + ConvertUtils.bin2hex(nonce) + " with-asn1: " + ConvertUtils.bin2hex(name));
            }

            nonce = name;
         }

         if(nonce != null && ConvertUtils.findDigType(nonce) == null && bBdoc) {
            name = ConvertUtils.addDigestAsn1Prefix(nonce);
            if(this.m_logger.isDebugEnabled()) {
               this.m_logger.debug("Nonce in: " + ConvertUtils.bin2hex(nonce) + " in-len: " + (nonce != null?nonce.length:0) + " with-asn1: " + ConvertUtils.bin2hex(name) + " out-len: " + (name != null?name.length:0) + " out-pref: " + ConvertUtils.findDigType(name));
            }

            nonce = name;
         }

         Vector name1;
         if(nonce != null) {
            name1 = new Vector();
            Vector chain = new Vector();
            name1.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
            chain.add(new X509Extension(false, new DEROctetString(nonce)));
            X509Extensions ret = new X509Extensions(name1, chain);
            ocspRequest.setRequestExtensions(ret);
         }

         name1 = null;
         GeneralName name2;
         if(bSigned) {
            if(this.m_logger.isDebugEnabled()) {
               this.m_logger.debug("SignCert: " + (this.m_signCert != null?this.m_signCert.toString():"NULL"));
            }

            if(this.m_signCert == null) {
               throw new DigiDocException(17, "Invalid config file! Attempting to sign ocsp request but PKCS#12 token not configured!", (Throwable)null);
            }

            name2 = new GeneralName(PrincipalUtil.getSubjectX509Principal(this.m_signCert));
         } else {
            if(signersCert == null) {
               throw new DigiDocException(68, "Signature owners certificate is NULL!", (Throwable)null);
            }

            name2 = new GeneralName(PrincipalUtil.getSubjectX509Principal(signersCert));
         }

         ocspRequest.setRequestorName(name2);
         if(bSigned) {
            X509Certificate[] chain1 = new X509Certificate[]{this.m_signCert};
            req = ocspRequest.generate("SHA1WITHRSA", this.m_signKey, chain1, "BC");
            if(!req.verify(this.m_signCert.getPublicKey(), "BC")) {
               this.m_logger.error("Verify failed");
            }
         } else {
            req = ocspRequest.generate();
         }
      } catch (Exception var12) {
         DigiDocException.handleException(var12, 65);
      }

      return req;
   }

   private OCSPResp sendRequest(OCSPReq req, String httpFrom, String format, String formatVer) throws DigiDocException {
      String responderUrl = ConfigManager.instance().getProperty("DIGIDOC_OCSP_RESPONDER_URL");
      return this.sendRequestToUrl(req, responderUrl, httpFrom, format, formatVer);
   }

   private String getUserInfo(String format, String formatVer) {
      StringBuffer sb = null;

      try {
         sb = new StringBuffer("LIB ");
         sb.append("JDigiDoc");
         sb.append("/");
         sb.append("3.9.0-726");
         if(format != null && formatVer != null) {
            sb.append(" format: ");
            sb.append(format);
            sb.append("/");
            sb.append(formatVer);
         }

         sb.append(" Java: ");
         sb.append(System.getProperty("java.version"));
         sb.append("/");
         sb.append(System.getProperty("java.vendor"));
         sb.append(" OS: ");
         sb.append(System.getProperty("os.name"));
         sb.append("/");
         sb.append(System.getProperty("os.arch"));
         sb.append("/");
         sb.append(System.getProperty("os.version"));
         sb.append(" JVM: ");
         sb.append(System.getProperty("java.vm.name"));
         sb.append("/");
         sb.append(System.getProperty("java.vm.vendor"));
         sb.append("/");
         sb.append(System.getProperty("java.vm.version"));
      } catch (Throwable var5) {
         this.m_logger.error("Error reading java system properties: " + var5);
      }

      return sb != null?sb.toString():null;
   }

   private OCSPResp sendRequestToUrl(OCSPReq req, String url, String httpFrom, String format, String formatVer) throws DigiDocException {
      OCSPResp resp = null;

      try {
         byte[] ex = req.getEncoded();
         URL uUrl = new URL(url);
         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("Connecting to ocsp url: " + url);
         }

         URLConnection con = uUrl.openConnection();
         int nTmout = con.getConnectTimeout();
         if(this.m_logger.isDebugEnabled()) {
            this.m_logger.debug("Default connection timeout: " + nTmout + " [ms]");
         }

         int nConfTm = ConfigManager.instance().getIntProperty("OCSP_TIMEOUT", -1);
         if(nConfTm >= 0) {
            if(this.m_logger.isDebugEnabled()) {
               this.m_logger.debug("Setting connection timeout to: " + nConfTm + " [ms]");
            }

            con.setConnectTimeout(nConfTm);
         }

         con.setAllowUserInteraction(false);
         con.setUseCaches(false);
         con.setDoOutput(true);
         con.setDoInput(true);
         con.setRequestProperty("Content-Type", "application/ocsp-request");
         String sUserInfo = this.getUserInfo(format, formatVer);
         if(sUserInfo != null) {
            if(this.m_logger.isDebugEnabled()) {
               this.m_logger.debug("User-Agent: " + sUserInfo);
            }

            con.setRequestProperty("User-Agent", sUserInfo);
         }

         if(httpFrom != null && httpFrom.trim().length() > 0) {
            if(this.m_logger.isDebugEnabled()) {
               this.m_logger.debug("X-Forwarded-For: " + httpFrom);
            }

            con.setRequestProperty("X-Forwarded-For", httpFrom);
         }

         OutputStream os = con.getOutputStream();
         os.write(ex);
         os.close();
         InputStream is = con.getInputStream();
         int cl = con.getContentLength();
         byte[] bresp = null;
         if(cl > 0) {
            boolean avail = false;

            do {
               int avail1 = is.available();
               byte[] data = new byte[avail1];
               int rc = is.read(data);
               if(bresp == null) {
                  bresp = new byte[rc];
                  System.arraycopy(data, 0, bresp, 0, rc);
               } else {
                  byte[] tmp = new byte[bresp.length + rc];
                  System.arraycopy(bresp, 0, tmp, 0, bresp.length);
                  System.arraycopy(data, 0, tmp, bresp.length, rc);
                  bresp = tmp;
               }

               cl -= rc;
            } while(cl > 0);
         }

         is.close();
         if(bresp != null) {
            resp = new OCSPResp(bresp);
         }
      } catch (Exception var21) {
         DigiDocException.handleException(var21, 65);
      }

      return resp;
   }

   public void init() throws DigiDocException {
      try {
         String ex = ConfigManager.instance().getProperty("DIGIDOC_PROXY_HOST");
         String proxyPort = ConfigManager.instance().getProperty("DIGIDOC_PROXY_PORT");
         if(ex != null && proxyPort != null) {
            System.setProperty("http.proxyHost", ex);
            System.setProperty("http.proxyPort", proxyPort);
         }

         String sigFlag = ConfigManager.instance().getProperty("SIGN_OCSP_REQUESTS");
         this.m_bSignRequests = sigFlag != null && sigFlag.equals("true");
         Provider prv = (Provider)Class.forName(ConfigManager.instance().getProperty("DIGIDOC_SECURITY_PROVIDER")).newInstance();
         Security.addProvider(prv);
         if(this.m_bSignRequests) {
            String p12file = ConfigManager.instance().getProperty("DIGIDOC_PKCS12_CONTAINER");
            String p12paswd = ConfigManager.instance().getProperty("DIGIDOC_PKCS12_PASSWD");
            String p12serial = ConfigManager.instance().getProperty("DIGIDOC_OCSP_SIGN_CERT_SERIAL");
            if(p12file != null && p12paswd != null) {
               FileInputStream fi = new FileInputStream(p12file);
               KeyStore store = KeyStore.getInstance("PKCS12", "BC");
               store.load(fi, p12paswd.toCharArray());
               Enumeration en = store.aliases();
               String pName = null;

               while(en.hasMoreElements()) {
                  String certs = (String)en.nextElement();
                  if(store.isKeyEntry(certs)) {
                     pName = certs;
                  }
               }

               this.m_signKey = (PrivateKey)store.getKey(pName, (char[])null);
               Certificate[] var16 = store.getCertificateChain(pName);

               for(int i = 0; var16 != null && i < var16.length; ++i) {
                  X509Certificate cert = (X509Certificate)var16[i];
                  if(this.m_logger.isInfoEnabled()) {
                     this.m_logger.info("Cert " + i + " subject: " + ConvertUtils.convX509Name(cert.getSubjectX500Principal()));
                     this.m_logger.info("Cert " + i + " issuer: " + ConvertUtils.convX509Name(cert.getIssuerX500Principal()));
                     this.m_logger.info("Cert " + i + " serial: " + cert.getSerialNumber());
                     this.m_logger.info("Cert " + i + " is-ca: " + ConvertUtils.isCACert(cert));
                  }

                  if(p12serial != null && cert != null && cert.getSerialNumber().equals(new BigInteger(p12serial))) {
                     this.m_signCert = (X509Certificate)var16[i];
                  }
               }
            }
         }
      } catch (Exception var15) {
         DigiDocException.handleException(var15, 67);
      }

   }
}
Page generated: Oct 19, 2017 2:35:07 PM