Ejemplo n.º 1
0
  private int verify(String signatureb64) {
    int verified = 0;
    try {
      CMSSignedData signature = new CMSSignedData(Base64.decode(signatureb64));

      // batch verification
      Store certs = signature.getCertificates();
      SignerInformationStore signers = signature.getSignerInfos();
      Collection c = signers.getSigners();
      Iterator it = c.iterator();

      while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = certs.getMatches(signer.getSID());

        Iterator certIt = certCollection.iterator();
        X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next();
        System.out.println(verified);

        if (signer.verify(
            new JcaSimpleSignerInfoVerifierBuilder()
                .setProvider(new BouncyCastleProvider())
                .build(certHolder))) {
          verified++;
        }
      }
      System.out.println(verified);
    } catch (CMSException | StoreException | CertificateException | OperatorCreationException ex) {
      System.err.println("error : " + ex.getMessage());
    }
    return verified;
  }
Ejemplo n.º 2
0
  private void verifyRSASignatures(CMSSignedData s, byte[] contentDigest) throws Exception {
    Store certStore = s.getCertificates();
    SignerInformationStore signers = s.getSignerInfos();

    Collection c = signers.getSigners();
    Iterator it = c.iterator();

    while (it.hasNext()) {
      SignerInformation signer = (SignerInformation) it.next();
      Collection certCollection = certStore.getMatches(signer.getSID());

      Iterator certIt = certCollection.iterator();
      X509CertificateHolder cert = (X509CertificateHolder) certIt.next();

      if (!signer.verify(
          new BcRSASignerInfoVerifierBuilder(
                  new DefaultCMSSignatureAlgorithmNameGenerator(),
                  new DefaultSignatureAlgorithmIdentifierFinder(),
                  new DefaultDigestAlgorithmIdentifierFinder(),
                  new BcDigestCalculatorProvider())
              .build(cert))) {
        fail("signature verification failed");
      }

      if (contentDigest != null) {
        if (!Arrays.areEqual(contentDigest, signer.getContentDigest())) {
          fail("digest verification failed");
        }
      }
    }
  }
 /**
  * Verify the email is signed by the given certificate.
  *
  * @param signedData
  * @param mailMsg
  * @return
  * @throws CMSException
  * @throws OperatorCreationException
  * @throws CertificateException
  */
 @SuppressWarnings({"rawtypes"})
 protected boolean isValid(CMSSignedData signedData, MailMessage mailMsg)
     throws OperatorCreationException, CMSException, CertificateException {
   boolean verify = false;
   SignerInformationStore signerStore = signedData.getSignerInfos();
   Iterator<SignerInformation> it = signerStore.getSigners().iterator();
   while (it.hasNext()) {
     SignerInformation signer = it.next();
     org.bouncycastle.util.Store store = signedData.getCertificates();
     @SuppressWarnings("unchecked")
     Collection certCollection = store.getMatches(signer.getSID());
     Iterator certIt = certCollection.iterator();
     X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next();
     X509Certificate certificate =
         new JcaX509CertificateConverter().setProvider(PROVIDER_NAME).getCertificate(certHolder);
     verify =
         signer.verify(
             new JcaSimpleSignerInfoVerifierBuilder()
                 .setProvider(PROVIDER_NAME)
                 .build(certificate));
     mailMsg.setHasSignature(true);
     mailMsg.setSignaturePassed(verify);
     mailMsg.setNameOfPrincipal(certificate.getSubjectDN().getName());
   }
   return verify;
 }
 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;
 }
Ejemplo n.º 5
0
  /** verify the signature (assuming the cert is contained in the message) */
  private static void verify(SMIMESigned s) throws Exception {
    //
    // extract the information to verify the signatures.
    //

    //
    // certificates and crls passed in the signature
    //
    Store certs = s.getCertificates();

    //
    // SignerInfo blocks which contain the signatures
    //
    SignerInformationStore signers = s.getSignerInfos();

    Collection c = signers.getSigners();
    Iterator it = c.iterator();

    //
    // check each signer
    //
    while (it.hasNext()) {
      SignerInformation signer = (SignerInformation) it.next();
      Collection certCollection = certs.getMatches(signer.getSID());

      Iterator certIt = certCollection.iterator();
      X509Certificate cert =
          new JcaX509CertificateConverter()
              .setProvider(BC)
              .getCertificate((X509CertificateHolder) certIt.next());

      //
      // verify that the sig is correct and that it was generated
      // when the certificate was current
      //
      if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(cert))) {
        System.out.println("signature verified");
      } else {
        System.out.println("signature failed!");
      }
    }
  }
Ejemplo n.º 6
0
  public void testCertificateManagement() throws Exception {
    List certList = new ArrayList();

    certList.add(_signCert);
    certList.add(_origCert);

    Store certs = new JcaCertStore(certList);

    SMIMESignedGenerator gen = new SMIMESignedGenerator();

    gen.addCertificates(certs);

    MimeBodyPart smm = gen.generateCertificateManagement();

    SMIMESigned s = new SMIMESigned(smm);

    certs = s.getCertificates();

    assertEquals(2, certs.getMatches(null).size());
  }
Ejemplo n.º 7
0
  public void testWithAttributeCertificate() throws Exception {
    List certList = new ArrayList();

    certList.add(_signCert);
    certList.add(_origCert);

    Store certs = new JcaCertStore(certList);

    ASN1EncodableVector signedAttrs = generateSignedAttributes();

    SMIMESignedGenerator gen = new SMIMESignedGenerator();

    gen.addSignerInfoGenerator(
        new JcaSimpleSignerInfoGeneratorBuilder()
            .setProvider(BC)
            .setSignedAttributeGenerator(
                new DefaultSignedAttributeTableGenerator(new AttributeTable(signedAttrs)))
            .build("SHA256withRSA", _signKP.getPrivate(), _signCert));

    gen.addCertificates(certs);

    X509AttributeCertificateHolder attrCert = CMSTestUtil.getAttributeCertificate();

    List attrCertList = new ArrayList();

    attrCertList.add(attrCert);

    Store store = new CollectionStore(attrCertList);

    gen.addAttributeCertificates(store);

    SMIMESigned s = new SMIMESigned(gen.generateEncapsulated(msg));

    verifyMessageBytes(msg, s.getContent());

    verifySigners(s.getCertificates(), s.getSignerInfos());

    Store attrCerts = s.getAttributeCertificates();

    assertTrue(attrCerts.getMatches(null).contains(attrCert));
  }
Ejemplo n.º 8
0
  private void verifySigners(Store certs, SignerInformationStore signers) throws Exception {
    Collection c = signers.getSigners();
    Iterator it = c.iterator();

    while (it.hasNext()) {
      SignerInformation signer = (SignerInformation) it.next();
      Collection certCollection = certs.getMatches(signer.getSID());

      Iterator certIt = certCollection.iterator();
      X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next();

      assertEquals(
          true,
          signer.verify(
              new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certHolder)));
    }
  }
 /** @param attrStore a Store containing X509AttributeCertificate objects. */
 public void addAttributeCertificates(Store attrStore) {
   attrCerts.addAll(attrStore.getMatches(null));
 }
 /** @param crlStore a Store containing X509CRLHolder objects. */
 public void addCRLs(Store crlStore) {
   crls.addAll(crlStore.getMatches(null));
 }
 /**
  * Add the store of X509 Certificates to the generator.
  *
  * @param certStore a Store containing X509CertificateHolder objects
  */
 public void addCertificates(Store certStore) {
   certs.addAll(certStore.getMatches(null));
 }
  // 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
  /**
   * Verifica la correttezza della firma elettronica <b>di uno dei firmatari</b> della busta
   * crittografica controllando i campi di verifica richiesti come parametro
   *
   * @param signer il firmatario di cui bisogna verificare la firma
   * @param fields Una Set contenente i nomi dei campi che si vogliono verificare in fase di
   *     operazione di verifica sul singolo firmatario
   * @return Una Map contenete il record dell'operazione di verifica sul firmatario con i campi
   *     richiesti dal parametro fields
   * @see it.libersoft.firmapiu.consts.FirmapiuRecordConstants
   */
  Map<String, Object> verifySigner(SignerInformation signer, Set<String> fields) {
    // genera la map contenente le informazioni di verifica per il singolo firmatario
    Map<String, Object> record = new TreeMap<String, Object>();
    // FIXME informazione replicata nei metodi di Cades-Bes Verifier che già offrono la possbilità
    // di ottenere la SignerInformation
    // inserisce la signerinfo
    if (fields.contains(SIGNERINFO)) record.put(SIGNERINFO, signer);

    Collection<?> certCollection = certStore.getMatches(signer.getSID());
    Iterator<?> certIt = certCollection.iterator();
    X509CertificateHolder cert = (X509CertificateHolder) certIt.next();

    // inserisce il certificato del firmatario
    if (fields.contains(SIGNERCERT)) {
      try {
        X509Certificate x509cert = new JcaX509CertificateConverter().getCertificate(cert);
        record.put(SIGNERCERT, x509cert);
      } catch (CertificateException e) {
        record.put(SIGNERCERT, new FirmapiuException(CERT_DEFAULT_ERROR, e));
      }
    }

    // inserisce la verifica della firma del firmatatio
    if (fields.contains(OKSIGNED)) {
      try {
        Boolean result =
            signer.verify(
                new JcaSimpleSignerInfoVerifierBuilder().setProvider(this.bcProvName).build(cert));
        record.put(OKSIGNED, result);
      } catch (OperatorCreationException e) {
        record.put(OKSIGNED, new FirmapiuException(VERIFY_SIGNER_DEFAULT_ERROR, e));
      } catch (CertificateException e) {
        record.put(OKSIGNED, new FirmapiuException(CERT_DEFAULT_ERROR, e));
      } catch (CMSException e) {
        record.put(OKSIGNED, new FirmapiuException(VERIFY_SIGNER_DEFAULT_ERROR, e));
      } // fine try-catch
    }

    // inserisce la verifica del controllo legale della firma di un firmatario
    if (fields.contains(LEGALLYSIGNED)) {
      try {
        record.put(LEGALLYSIGNED, new Boolean(isLegallySigned(signer, cert)));
      } catch (NoSuchAlgorithmException e) {
        record.put(LEGALLYSIGNED, new FirmapiuException(CERT_DEFAULT_ERROR, e));
      } catch (FirmapiuException e) {
        record.put(LEGALLYSIGNED, e);
      } catch (IOException e) {
        record.put(LEGALLYSIGNED, new FirmapiuException(CERT_DEFAULT_ERROR, e));
      }
    }

    // inserisce la verifica del controllo dell'affidabilità del certificato del firmatario
    PKIXCertPathBuilderResult signerCerthPathResult = null;
    if (fields.contains(TRUSTEDSIGNER)) {
      try {
        signerCerthPathResult = isTrustedSigner(signer);
        // se è arrivato a questo ramo di codice vuol dire che il certificato è affidbile
        record.put(TRUSTEDSIGNER, new Boolean(true));
      } catch (FirmapiuException e) {
        record.put(TRUSTEDSIGNER, e);
      }
    }

    // inserisce la "trust anchor" del certificato del firmatario, ossia il certificato della CA che
    // lo ha emesso
    if (fields.contains(TRUSTANCHOR)) {
      try {
        if (signerCerthPathResult == null) signerCerthPathResult = isTrustedSigner(signer);
        X509Certificate trustanchor = signerCerthPathResult.getTrustAnchor().getTrustedCert();
        record.put(TRUSTANCHOR, trustanchor);
      } catch (FirmapiuException e) {
        record.put(TRUSTANCHOR, e);
      }
    }

    // inserisce la catena di certificazione
    if (fields.contains(CERTCHAIN)) {
      try {
        if (signerCerthPathResult == null) signerCerthPathResult = isTrustedSigner(signer);
        List<? extends Certificate> certchain =
            signerCerthPathResult.getCertPath().getCertificates();
        record.put(CERTCHAIN, certchain);
      } catch (FirmapiuException e) {
        record.put(CERTCHAIN, e);
      }
    }

    // verifica che il certificato relativo il firmatario non sia stato revocato
    // e che era valido al momento in cui i dati sono stati firmati
    Object certStatus = null;
    Date rvkdCertTime = null;
    if (fields.contains(SIGNERCERTSTATUS) || fields.contains(SIGNERCERTREVOKED)) {
      // controllo lo status del certificato utente con OSCP. Se il controllo fallisce o lo status
      // del certificato è "UNKNOWN"
      // esegue il controllo con le CRL
      X509Certificate userCertificate = null;
      try {
        userCertificate = new JcaX509CertificateConverter().getCertificate(cert);
      } catch (CertificateException e1) {
        if (fields.contains(SIGNERCERTSTATUS)) record.put(SIGNERCERTSTATUS, e1);
        if (fields.contains(SIGNERCERTREVOKED)) record.put(SIGNERCERTREVOKED, e1);
      }
      // se non è in grado di determinare lo user certificate di cui controllare lo status non deve
      // proseguire oltre
      if (userCertificate != null) {
        try {
          if (signerCerthPathResult == null) signerCerthPathResult = isTrustedSigner(signer);
          // TODO nota: non è detto che il trustanchor sia anche l'issuercertificate. Bisogna fare
          // un controllo mogliore
          X509Certificate issuerCertificate =
              signerCerthPathResult.getTrustAnchor().getTrustedCert();
          certStatus = getCertificateStatus(userCertificate, issuerCertificate);
          // se certstatus è null il certificato è considerato valido
          if (certStatus == null) {
            if (fields.contains(SIGNERCERTSTATUS)) record.put(SIGNERCERTSTATUS, CertStatus.GOOD);
            if (fields.contains(SIGNERCERTREVOKED))
              record.put(SIGNERCERTREVOKED, new Boolean(false));
          } else {
            // se certStatus è una risposta ocsp
            if (certStatus instanceof CertificateStatus) {
              CertificateStatus c1 = (CertificateStatus) certStatus;
              if (c1 == CertificateStatus.GOOD) {
                if (fields.contains(SIGNERCERTSTATUS))
                  record.put(SIGNERCERTSTATUS, CertStatus.GOOD);
                if (fields.contains(SIGNERCERTREVOKED))
                  record.put(SIGNERCERTREVOKED, new Boolean(false));
              } else
              // certificato revocato
              if (c1 instanceof RevokedStatus) {
                rvkdCertTime = ((RevokedStatus) c1).getRevocationTime();
                if (fields.contains(SIGNERCERTSTATUS))
                  record.put(SIGNERCERTSTATUS, CertStatus.REVOKED);
                if (fields.contains(SIGNERCERTREVOKED)) {
                  // controlla se il certificato era già revocato al signing time
                  try {
                    if (isRevokedAtSigningTime(signer, rvkdCertTime))
                      record.put(SIGNERCERTREVOKED, new Boolean(true));
                    else record.put(SIGNERCERTREVOKED, new Boolean(false));
                  } catch (FirmapiuException e) {
                    record.put(SIGNERCERTREVOKED, e);
                  }
                } // fine if (fields.contains(SIGNERCERTREVOKED)
              } // fine if (c1 instanceof RevokedStatus)
            }
            // se il certStatus è una risposta CRL vuol dire che il certificato è revocato,
            // altrimenti avrebbe restituito null
            else if (certStatus instanceof X509CRLEntry) {
              rvkdCertTime = ((X509CRLEntry) certStatus).getRevocationDate();
              if (fields.contains(SIGNERCERTSTATUS))
                record.put(SIGNERCERTSTATUS, CertStatus.REVOKED);
              if (fields.contains(SIGNERCERTREVOKED)) {
                // controlla se il certificato era già revocato al signing time
                try {
                  if (isRevokedAtSigningTime(signer, rvkdCertTime))
                    record.put(SIGNERCERTREVOKED, new Boolean(true));
                  else record.put(SIGNERCERTREVOKED, new Boolean(false));
                } catch (FirmapiuException e) {
                  record.put(SIGNERCERTREVOKED, e);
                }
              } // fine if (fields.contains(SIGNERCERTREVOKED))
            } // fine else if (certStatus instanceof X509CRLEntry)
          } // fine else
        } catch (FirmapiuException e) {
          record.put(SIGNERCERTSTATUS, e);
        }
      } // fine if (userCertificate!=null)
    } // fine if(fields.contains(SIGNERCERTSTATUS) | fields.contains(SIGNERCERTREVOKED))

    // ritorna il record generato al chiamante
    return record;

    // OCSPVerify ocspVerifier=null;
    //		if(fields.contains(SIGNERCERTSTATUS)){
    //			//controllo lo status del certificato utente con OSCP. Se il controllo fallisce o lo status
    // del certificato è "UNKNOWN"
    //			//esegue il controllo con le CRL
    //			X509Certificate userCertificate=null;
    //			try {
    //				userCertificate = new JcaX509CertificateConverter().getCertificate(cert);
    //			} catch (CertificateException e1) {
    //				record.put(SIGNERCERTSTATUS, e1);
    //			}
    //			//se non è in grado di determinare lo user certificate di cui controllare lo status non
    // deve proseguire oltre
    //			if (userCertificate!=null) {
    //				try {
    //					if (signerCerthPathResult == null)
    //						signerCerthPathResult = isTrustedSigner(signer);
    //					//TODO nota: non è detto che il trustanchor sia anche l'issuercertificate. Bisogna fare
    // un controllo mogliore
    //					X509Certificate issuerCertificate = signerCerthPathResult
    //							.getTrustAnchor().getTrustedCert();
    //					ocspVerifier = new OCSPVerify(issuerCertificate,
    //							userCertificate, this.bcProvName);
    //					CertificateStatus certStatus = ocspVerifier
    //							.getStatusCertificate();
    //					// certificato valido
    //					if (certStatus == CertificateStatus.GOOD) {
    //						record.put(SIGNERCERTSTATUS, CertStatus.GOOD);
    //					} else
    //					// certificato revocato
    //					if (certStatus instanceof RevokedStatus) {
    //						record.put(SIGNERCERTSTATUS, CertStatus.REVOKED);
    //					} else
    //					// stato del certificato sconosciuto
    //					if (certStatus instanceof UnknownStatus) {
    //						//			System.out.println("certificato sconosciuto!");
    //						//			System.err.println("OCSPVerify.getStatusResponse() "
    //						//					+ "UnknowStatus");
    //						//return CertStatus.UNKNOWN;
    //						//se lo stato del certificato è sconosciuto controlla anche le crl
    //						CRLVerify crlVerifier = new CRLVerify(userCertificate);
    //						try {
    //							//TODO bisognerebbe controllare la firma delle risposte ricevute
    //							if (crlVerifier.verifyCertificateCRLs())
    //								record.put(SIGNERCERTSTATUS, CertStatus.GOOD);
    //							else
    //								record.put(SIGNERCERTSTATUS, CertStatus.REVOKED);
    //						} catch (FirmapiuException e) {
    //							record.put(SIGNERCERTSTATUS, e);
    //						}
    //					}//fine if (certStatus instanceof UnknownStatus)
    //				} catch (FirmapiuException e) {
    //					//se il controllo tramite ocsp è fallito a causa di un errore, controlla anche le CRL
    //					CRLVerify crlVerifier = new CRLVerify(userCertificate);
    //					try {
    //						//TODO bisognerebbe controllare la firma delle risposte ricevute
    //						if (crlVerifier.verifyCertificateCRLs())
    //							record.put(SIGNERCERTSTATUS, CertStatus.GOOD);
    //						else
    //							record.put(SIGNERCERTSTATUS, CertStatus.REVOKED);
    //					} catch (FirmapiuException e1) {
    //						//TODO quale eccezione restituire? quella di OCSP o Quella di CRL?
    //						record.put(SIGNERCERTSTATUS, e1);
    //					}
    //				}//fine try-catch
    //			}//fine if (userCertificate!=null)
    //		}//fine if(fields.contains(SIGNERCERTSTATUS))
  }
Ejemplo n.º 14
0
 /**
  * Add a Store of otherRevocationData to the CRL set to be included with the generated
  * TimeStampToken.
  *
  * @param otherRevocationInfoFormat the OID specifying the format of the otherRevocationInfo data.
  * @param otherRevocationInfos a Store of otherRevocationInfo data to add.
  */
 public void addOtherRevocationInfo(
     ASN1ObjectIdentifier otherRevocationInfoFormat, Store otherRevocationInfos) {
   otherRevoc.put(otherRevocationInfoFormat, otherRevocationInfos.getMatches(null));
 }
Ejemplo n.º 15
0
  /*
   * test compressing and uncompressing of a multipart-signed message.
   */
  public void testCompressedSHA1WithRSA() throws Exception {
    List certList = new ArrayList();

    certList.add(origCert);
    certList.add(signCert);

    Store certs = new JcaCertStore(certList);

    ASN1EncodableVector signedAttrs = new ASN1EncodableVector();
    SMIMECapabilityVector caps = new SMIMECapabilityVector();

    caps.addCapability(SMIMECapability.dES_EDE3_CBC);
    caps.addCapability(SMIMECapability.rC2_CBC, 128);
    caps.addCapability(SMIMECapability.dES_CBC);

    signedAttrs.add(new SMIMECapabilitiesAttribute(caps));

    SMIMESignedGenerator gen = new SMIMESignedGenerator();

    gen.addSignerInfoGenerator(
        new JcaSimpleSignerInfoGeneratorBuilder()
            .setProvider("BC")
            .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
            .build("SHA1withRSA", origKP.getPrivate(), origCert));

    gen.addCertificates(certs);

    MimeMultipart smp = gen.generate(msg);

    MimeMessage bp2 = new MimeMessage((Session) null);

    bp2.setContent(smp);

    bp2.saveChanges();

    SMIMECompressedGenerator cgen = new SMIMECompressedGenerator();

    MimeBodyPart cbp = cgen.generate(bp2, new ZlibCompressor());

    SMIMECompressed cm = new SMIMECompressed(cbp);

    MimeMultipart mm =
        (MimeMultipart)
            SMIMEUtil.toMimeBodyPart(cm.getContent(new ZlibExpanderProvider())).getContent();

    SMIMESigned s = new SMIMESigned(mm);

    ByteArrayOutputStream _baos = new ByteArrayOutputStream();
    msg.writeTo(_baos);
    _baos.close();
    byte[] _msgBytes = _baos.toByteArray();
    _baos = new ByteArrayOutputStream();
    s.getContent().writeTo(_baos);
    _baos.close();
    byte[] _resBytes = _baos.toByteArray();

    assertEquals(true, Arrays.areEqual(_msgBytes, _resBytes));

    certs = s.getCertificates();

    SignerInformationStore signers = s.getSignerInfos();
    Collection c = signers.getSigners();
    Iterator it = c.iterator();

    while (it.hasNext()) {
      SignerInformation signer = (SignerInformation) it.next();
      Collection certCollection = certs.getMatches(signer.getSID());

      Iterator certIt = certCollection.iterator();
      X509CertificateHolder cert = (X509CertificateHolder) certIt.next();

      assertEquals(
          true,
          signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)));
    }
  }