Ejemplo n.º 1
0
  private X509Certificate[] doBuild(X509Certificate[] chain, Collection otherCerts)
      throws CertificateException {
    try {
      PKIXBuilderParameters params = (PKIXBuilderParameters) parameterTemplate.clone();
      setDate(params);

      // setup target constraints
      X509CertSelector selector = new X509CertSelector();
      selector.setCertificate(chain[0]);
      params.setTargetCertConstraints(selector);

      // setup CertStores
      Collection certs = new ArrayList();
      certs.addAll(Arrays.asList(chain));
      if (otherCerts != null) {
        certs.addAll(otherCerts);
      }
      CertStore store =
          CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs));
      params.addCertStore(store);

      // do the build
      CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
      PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult) builder.build(params);

      return toArray(result.getCertPath(), result.getTrustAnchor());
    } catch (GeneralSecurityException e) {
      throw new ValidatorException("PKIX path building failed: " + e.toString(), e);
    }
  }
Ejemplo n.º 2
0
  private void testExceptions() throws Exception {
    byte[] enc = {(byte) 0, (byte) 2, (byte) 3, (byte) 4, (byte) 5};
    MyCertPath mc = new MyCertPath(enc);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ByteArrayInputStream is;
    byte[] arr;

    ObjectOutputStream oOut = new ObjectOutputStream(os);
    oOut.writeObject(mc);
    oOut.flush();
    oOut.close();

    try {
      CertificateFactory cFac = CertificateFactory.getInstance("X.509", "BC");
      arr = os.toByteArray();
      is = new ByteArrayInputStream(arr);
      cFac.generateCertPath(is);
    } catch (CertificateException e) {
      // ignore okay
    }

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    List certCol = new ArrayList();

    certCol.add(cf.generateCertificate(new ByteArrayInputStream(certA)));
    certCol.add(cf.generateCertificate(new ByteArrayInputStream(certB)));
    certCol.add(cf.generateCertificate(new ByteArrayInputStream(certC)));
    certCol.add(cf.generateCertificate(new ByteArrayInputStream(certD)));

    CertPathBuilder pathBuilder = CertPathBuilder.getInstance("PKIX", "BC");
    X509CertSelector select = new X509CertSelector();
    select.setSubject(((X509Certificate) certCol.get(0)).getSubjectX500Principal().getEncoded());

    Set trustanchors = new HashSet();
    trustanchors.add(
        new TrustAnchor(
            (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(rootCertBin)), null));

    CertStore certStore =
        CertStore.getInstance("Collection", new CollectionCertStoreParameters(certCol));

    PKIXBuilderParameters params = new PKIXBuilderParameters(trustanchors, select);
    params.addCertStore(certStore);

    try {
      CertPathBuilderResult result = pathBuilder.build(params);
      CertPath path = result.getCertPath();
      fail("found cert path in circular set");
    } catch (CertPathBuilderException e) {
      // expected
    }
  }
Ejemplo n.º 3
0
  /**
   * Build a path using the given root as the trust anchor, and the passed in end constraints and
   * certificate store.
   *
   * <p>Note: the path is built with revocation checking turned off.
   */
  public static PKIXCertPathBuilderResult buildPath(
      X509Certificate rootCert, X509CertSelector endConstraints, CertStore certsAndCRLs)
      throws Exception {
    CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
    PKIXBuilderParameters buildParams =
        new PKIXBuilderParameters(
            Collections.singleton(new TrustAnchor(rootCert, null)), endConstraints);

    buildParams.addCertStore(certsAndCRLs);
    buildParams.setRevocationEnabled(false);

    return (PKIXCertPathBuilderResult) builder.build(buildParams);
  }
Ejemplo n.º 4
0
  private void validateChain(List<Certificate> chain, Certificate cert) {

    List<Certificate> certs = new ArrayList<Certificate>();
    List<Certificate> root = new ArrayList<Certificate>();

    Set<TrustAnchor> anchors = new HashSet<TrustAnchor>();

    certs.add(cert); // adding for self signed certs
    certs.addAll(chain);

    for (Certificate c : certs) {
      if (!(c instanceof X509Certificate))
        throw new IllegalArgumentException("Invalid chain format. Expected X509 certificate");

      X509Certificate xCert = (X509Certificate) c;

      Principal subject = xCert.getSubjectDN();
      Principal issuer = xCert.getIssuerDN();

      if (issuer != null && subject.equals(issuer)) {
        root.add(c);
        anchors.add(new TrustAnchor(xCert, null));
      }
    }

    if (root.size() == 0)
      throw new IllegalArgumentException("No root certificates found for certificate chain", null);

    X509CertSelector target = new X509CertSelector();
    target.setCertificate((X509Certificate) cert);

    PKIXBuilderParameters params = null;
    try {
      params = new PKIXBuilderParameters(anchors, target);
      params.setRevocationEnabled(false);
      params.addCertStore(
          CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs)));
      CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
      builder.build(params);

    } catch (InvalidAlgorithmParameterException e) {
      throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (CertPathBuilderException e) {
      throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (NoSuchAlgorithmException e) {
      throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (NoSuchProviderException e) {
      throw new CloudRuntimeException("No provider for certificate validation", e);
    }
  }
 /**
  * Searches for a holder public key certificate and verifies its certification path.
  *
  * @param attrCert the attribute certificate.
  * @param pkixParams The PKIX parameters.
  * @return The certificate path of the holder certificate.
  * @throws AnnotatedException if
  *     <ul>
  *       <li>no public key certificate can be found although holder information is given by an
  *           entity name or a base certificate ID
  *       <li>support classes cannot be created
  *       <li>no certification path for the public key certificate can be built
  *     </ul>
  */
 protected static CertPath processAttrCert1(
     X509AttributeCertificate attrCert, ExtendedPKIXParameters pkixParams)
     throws CertPathValidatorException {
   CertPathBuilderResult result = null;
   // find holder PKCs
   Set holderPKCs = new HashSet();
   if (attrCert.getHolder().getIssuer() != null) {
     X509CertStoreSelector selector = new X509CertStoreSelector();
     selector.setSerialNumber(attrCert.getHolder().getSerialNumber());
     Principal[] principals = attrCert.getHolder().getIssuer();
     for (int i = 0; i < principals.length; i++) {
       try {
         if (principals[i] instanceof X500Principal) {
           selector.setIssuer(((X500Principal) principals[i]).getEncoded());
         }
         holderPKCs.addAll(
             CertPathValidatorUtilities.findCertificates(selector, pkixParams.getStores()));
       } catch (AnnotatedException e) {
         throw new ExtCertPathValidatorException(
             "Public key certificate for attribute certificate cannot be searched.", e);
       } catch (IOException e) {
         throw new ExtCertPathValidatorException("Unable to encode X500 principal.", e);
       }
     }
     if (holderPKCs.isEmpty()) {
       throw new CertPathValidatorException(
           "Public key certificate specified in base certificate ID for attribute certificate cannot be found.");
     }
   }
   if (attrCert.getHolder().getEntityNames() != null) {
     X509CertStoreSelector selector = new X509CertStoreSelector();
     Principal[] principals = attrCert.getHolder().getEntityNames();
     for (int i = 0; i < principals.length; i++) {
       try {
         if (principals[i] instanceof X500Principal) {
           selector.setIssuer(((X500Principal) principals[i]).getEncoded());
         }
         holderPKCs.addAll(
             CertPathValidatorUtilities.findCertificates(selector, pkixParams.getStores()));
       } catch (AnnotatedException e) {
         throw new ExtCertPathValidatorException(
             "Public key certificate for attribute certificate cannot be searched.", e);
       } catch (IOException e) {
         throw new ExtCertPathValidatorException("Unable to encode X500 principal.", e);
       }
     }
     if (holderPKCs.isEmpty()) {
       throw new CertPathValidatorException(
           "Public key certificate specified in entity name for attribute certificate cannot be found.");
     }
   }
   // verify cert paths for PKCs
   ExtendedPKIXBuilderParameters params =
       (ExtendedPKIXBuilderParameters) ExtendedPKIXBuilderParameters.getInstance(pkixParams);
   CertPathValidatorException lastException = null;
   for (Iterator it = holderPKCs.iterator(); it.hasNext(); ) {
     X509CertStoreSelector selector = new X509CertStoreSelector();
     selector.setCertificate((X509Certificate) it.next());
     params.setTargetConstraints(selector);
     CertPathBuilder builder = null;
     try {
       builder = CertPathBuilder.getInstance("PKIX", "BC");
     } catch (NoSuchProviderException e) {
       throw new ExtCertPathValidatorException("Support class could not be created.", e);
     } catch (NoSuchAlgorithmException e) {
       throw new ExtCertPathValidatorException("Support class could not be created.", e);
     }
     try {
       result = builder.build(ExtendedPKIXBuilderParameters.getInstance(params));
     } catch (CertPathBuilderException e) {
       lastException =
           new ExtCertPathValidatorException(
               "Certification path for public key certificate of attribute certificate could not be build.",
               e);
     } catch (InvalidAlgorithmParameterException e) {
       // must be a programming error
       throw new RuntimeException(e.getMessage());
     }
   }
   if (lastException != null) {
     throw lastException;
   }
   return result.getCertPath();
 }
  // controlla che il certificato del firmatario sia affidabile controllando la sua catena di
  // certificati
  // valida il certificato X509 del firmatario usando il built-in PKIX support messo a disposizione
  // da java
  // caricando il keystore contenente i certificati degli enti certificatori autorizzati dallo stato
  // italiano
  private PKIXCertPathBuilderResult isTrustedSigner(SignerInformation signer)
      throws FirmapiuException {
    // genera la lista di certificati da controllare  per generare la catena dei certificati del
    // firmatario
    // TODO quali certificati carica esattamente?
    Collection<?> certCollection = certStore.getMatches(signer.getSID());
    Iterator<?> certIt = certCollection.iterator();
    X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
    List<X509Certificate> chain = new LinkedList<X509Certificate>();
    JcaX509CertificateConverter certConverter =
        new JcaX509CertificateConverter().setProvider(this.bcProvName);
    try {
      X509Certificate x509cert = certConverter.getCertificate(cert);
      chain.add(x509cert);
      while (certIt.hasNext()) {
        x509cert = certConverter.getCertificate((X509CertificateHolder) certIt.next());
        chain.add(x509cert);
      }
    } catch (CertificateException e) {
      new FirmapiuException(CERT_DEFAULT_ERROR, e);
    }

    // carica i certificati presenti nel token crittografico passato come parametro
    KeyStore anchors = this.token.loadKeyStore(null);
    X509CertSelector target = new X509CertSelector();
    target.setCertificate(chain.get(0));
    PKIXBuilderParameters params;
    CertPathBuilder builder;
    try {
      params = new PKIXBuilderParameters(anchors, target);
      // disabilita il controllo delle CRL
      params.setRevocationEnabled(false);
      // se il certificato è scaduto cerca di generare lo stesso la catena dei certificati
      try {
        X509Certificate x509cert = certConverter.getCertificate(cert);
        // long before=x509cert.getNotBefore().getTime();
        long after = x509cert.getNotAfter().getTime();
        after -= 10;
        params.setDate(new Date(after));
      } catch (CertificateException e) {
        throw new FirmapiuException(CERT_KEYSTORE_DEFAULT_ERROR, e);
      }
      CertStoreParameters intermediates = new CollectionCertStoreParameters(chain);
      params.addCertStore(CertStore.getInstance("Collection", intermediates));
      params.setSigProvider(this.bcProvName);
      builder = CertPathBuilder.getInstance("PKIX", this.bcProvName);
    } catch (KeyStoreException | InvalidAlgorithmParameterException e) {
      throw new FirmapiuException(CERT_KEYSTORE_DEFAULT_ERROR, e);
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
      throw new FirmapiuException(DEFAULT_ERROR, e);
    }
    /*
     * If build() returns successfully, the certificate is valid. More details
     * about the valid path can be obtained through the PKIXBuilderResult.
     * If no valid path can be found, a CertPathBuilderException is thrown.
     */
    try {
      return (PKIXCertPathBuilderResult) builder.build(params);
    } catch (CertPathBuilderException e) {
      throw new FirmapiuException(VERIFY_SIGNER_CERTPATH_ERROR, e);
    } catch (InvalidAlgorithmParameterException e) {
      throw new FirmapiuException(DEFAULT_ERROR, e);
    }
  } // fine metodo