// controlla che nel firmatario sia presente l'attributo ESSCertIDv2 e che esso sia valido
 // in questo caso la busta crittografica è espressa correttamente nel formato CADES-BES secondo
 // la  DELIBERAZIONE ministeriale del N . 45 DEL 21 MAGGIO 2009
 private boolean isLegallySigned(SignerInformation signer, X509CertificateHolder cert)
     throws FirmapiuException, NoSuchAlgorithmException, IOException {
   AttributeTable signAttr = signer.getSignedAttributes();
   if (signAttr == null) throw new FirmapiuException(VERIFY_SIGNER_SIGNINGATTRIBUTE_NOTFOUND);
   Attribute attr = signAttr.get(PKCSObjectIdentifiers.id_aa_signingCertificateV2);
   if (attr == null) throw new FirmapiuException(VERIFY_SIGNER_SIGNINGATTRIBUTE_NOTFOUND);
   ASN1Sequence sequence = ASN1Sequence.getInstance(attr.getAttrValues().getObjectAt(0));
   SigningCertificateV2 scv2 = SigningCertificateV2.getInstance(sequence);
   ESSCertIDv2[] essCert = scv2.getCerts();
   if (essCert == null || essCert.length < 1)
     throw new FirmapiuException(VERIFY_SIGNER_SIGNINGATTRIBUTE_NOTFOUND);
   // controlla l'hash del certificato se si restituisce true se no restituisce no
   // aggiungere hash del certificato di sottoscrizione
   String digestAlgorithm = "SHA-256";
   MessageDigest sha = null;
   sha = MessageDigest.getInstance(digestAlgorithm);
   byte[] digestedCert = sha.digest(cert.getEncoded());
   byte[] essCertHash = essCert[0].getCertHash();
   // affinché la firma sia valida digestCert e essCertHash devono essere uguali
   if (digestedCert.length != essCertHash.length) return false;
   else {
     for (int i = 0; i < digestedCert.length; i++)
       if (digestedCert[i] != essCertHash[i]) {
         return false;
       }
     return true;
   } // fine if
 } // fine metodo
示例#2
0
  /**
   * This method returns DER encoded array of bytes representing {@code X509Certificate} for given
   * {@code X509CertificateHolder}. The {@code IOException} is transformed in {@code DSSException}.
   *
   * @param certificateHolder {@code X509CertificateHolder}
   * @return DER encoded array of bytes representing {@code X509Certificate}.
   * @throws DSSException
   */
  public static byte[] getCertificateDEREncoded(final X509CertificateHolder certificateHolder)
      throws DSSException {

    try {

      final byte[] bytes = certificateHolder.getEncoded();
      return bytes;
    } catch (IOException e) {
      throw new DSSException(e);
    }
  }
 public Certificate getSignerCertificate() {
   try {
     Collection certificateCollection =
         cmsSignedData.getCertificates().getMatches(firstSignerInfo.getSID());
     Iterator iterator = certificateCollection.iterator();
     X509CertificateHolder certHolder = (X509CertificateHolder) iterator.next();
     return CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME)
         .generateCertificate(new ByteArrayInputStream(certHolder.getEncoded()));
   } catch (Exception e) {
     log.error(Channel.TECH, "Could not extract signer certificate from CMS signature : %1$s", e);
   }
   return null;
 }
  public X509Certificate convertCertificate(X509CertificateHolder certHolder)
      throws CertificateException {

    try {
      CertificateFactory certFact = helper.createCertificateFactory("X.509");

      return (X509Certificate)
          certFact.generateCertificate(new ByteArrayInputStream(certHolder.getEncoded()));
    } catch (IOException e) {
      throw new OpCertificateException(
          "cannot get encoded form of certificate: " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
      throw new OpCertificateException("cannot create certificate factory: " + e.getMessage(), e);
    } catch (NoSuchProviderException e) {
      throw new OpCertificateException("cannot find factory provider: " + e.getMessage(), e);
    }
  }
 public List<Certificate> getSignatureCertificateInfo() {
   try {
     Store certificateStore = cmsSignedData.getCertificates();
     Collection<X509CertificateHolder> certificateCollection = certificateStore.getMatches(null);
     List<Certificate> x509CertsCollection =
         new ArrayList<Certificate>(certificateCollection.size());
     for (X509CertificateHolder certHolder : certificateCollection) {
       x509CertsCollection.add(
           CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME)
               .generateCertificate(new ByteArrayInputStream(certHolder.getEncoded())));
     }
     return x509CertsCollection;
   } catch (Exception e) {
     ExceptionHandlerTyped.<SPISignatureException>handle(SPISignatureException.class, e);
   }
   return null;
 }
  /**
   * Basic Constructor - set up a calculator based on signerInfoGen with a ESSCertID calculated from
   * the signer's associated certificate using the sha1DigestCalculator. If alternate values are
   * required for id-aa-signingCertificate they should be added to the signerInfoGen object before
   * it is passed in, otherwise a standard digest based value will be added.
   *
   * @param signerInfoGen the generator for the signer we are using.
   * @param digestCalculator calculator for to use for digest of certificate.
   * @param tsaPolicy tasPolicy to send.
   * @param isIssuerSerialIncluded should issuerSerial be included in the ESSCertIDs, true if yes,
   *     by default false.
   * @throws IllegalArgumentException if calculator is not SHA-1 or there is no associated
   *     certificate for the signer,
   * @throws TSPException if the signer certificate cannot be processed.
   */
  public TimeStampTokenGenerator(
      final SignerInfoGenerator signerInfoGen,
      DigestCalculator digestCalculator,
      ASN1ObjectIdentifier tsaPolicy,
      boolean isIssuerSerialIncluded)
      throws IllegalArgumentException, TSPException {
    this.signerInfoGen = signerInfoGen;
    this.tsaPolicyOID = tsaPolicy;

    if (!signerInfoGen.hasAssociatedCertificate()) {
      throw new IllegalArgumentException("SignerInfoGenerator must have an associated certificate");
    }

    X509CertificateHolder assocCert = signerInfoGen.getAssociatedCertificate();
    TSPUtil.validateCertificate(assocCert);

    try {
      OutputStream dOut = digestCalculator.getOutputStream();

      dOut.write(assocCert.getEncoded());

      dOut.close();

      if (digestCalculator
          .getAlgorithmIdentifier()
          .getAlgorithm()
          .equals(OIWObjectIdentifiers.idSHA1)) {
        final ESSCertID essCertid =
            new ESSCertID(
                digestCalculator.getDigest(),
                isIssuerSerialIncluded
                    ? new IssuerSerial(
                        new GeneralNames(new GeneralName(assocCert.getIssuer())),
                        assocCert.getSerialNumber())
                    : null);

        this.signerInfoGen =
            new SignerInfoGenerator(
                signerInfoGen,
                new CMSAttributeTableGenerator() {
                  public AttributeTable getAttributes(Map parameters)
                      throws CMSAttributeTableGenerationException {
                    AttributeTable table =
                        signerInfoGen.getSignedAttributeTableGenerator().getAttributes(parameters);

                    if (table.get(PKCSObjectIdentifiers.id_aa_signingCertificate) == null) {
                      return table.add(
                          PKCSObjectIdentifiers.id_aa_signingCertificate,
                          new SigningCertificate(essCertid));
                    }

                    return table;
                  }
                },
                signerInfoGen.getUnsignedAttributeTableGenerator());
      } else {
        AlgorithmIdentifier digAlgID =
            new AlgorithmIdentifier(digestCalculator.getAlgorithmIdentifier().getAlgorithm());
        final ESSCertIDv2 essCertid =
            new ESSCertIDv2(
                digAlgID,
                digestCalculator.getDigest(),
                isIssuerSerialIncluded
                    ? new IssuerSerial(
                        new GeneralNames(new GeneralName(assocCert.getIssuer())),
                        new ASN1Integer(assocCert.getSerialNumber()))
                    : null);

        this.signerInfoGen =
            new SignerInfoGenerator(
                signerInfoGen,
                new CMSAttributeTableGenerator() {
                  public AttributeTable getAttributes(Map parameters)
                      throws CMSAttributeTableGenerationException {
                    AttributeTable table =
                        signerInfoGen.getSignedAttributeTableGenerator().getAttributes(parameters);

                    if (table.get(PKCSObjectIdentifiers.id_aa_signingCertificateV2) == null) {
                      return table.add(
                          PKCSObjectIdentifiers.id_aa_signingCertificateV2,
                          new SigningCertificateV2(essCertid));
                    }

                    return table;
                  }
                },
                signerInfoGen.getUnsignedAttributeTableGenerator());
      }
    } catch (IOException e) {
      throw new TSPException("Exception processing certificate.", e);
    }
  }