Example #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;
  }
Example #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;
 }
Example #4
0
  @Test
  public void testCMD() throws Exception {
    Authentication auth =
        new SkeletonKeyClientBuilder()
            .username("wburke")
            .password("geheim")
            .authentication("Skeleton Key");
    ResteasyClient client = new ResteasyClient();
    WebTarget target = client.target(generateBaseUrl());
    String tiny = target.path("tokens").path("url").request().post(Entity.json(auth), String.class);
    System.out.println(tiny);
    System.out.println("tiny.size: " + tiny.length());
    Security.addProvider(new BouncyCastleProvider());

    KeyPair keyPair = KeyPairGenerator.getInstance("RSA", "BC").generateKeyPair();
    PrivateKey privateKey = keyPair.getPrivate();
    X509Certificate cert = KeyTools.generateTestCertificate(keyPair);

    byte[] signed = p7s(privateKey, cert, null, tiny.getBytes());

    CMSSignedData data = new CMSSignedData(signed);
    byte[] bytes = (byte[]) data.getSignedContent().getContent();
    System.out.println("BYTES: " + new String(bytes));
    System.out.println("size:" + signed.length);
    System.out.println("Base64.size: " + Base64.encodeBytes(signed).length());

    SignerInformation signer =
        (SignerInformation) data.getSignerInfos().getSigners().iterator().next();
    System.out.println("valid: " + signer.verify(cert, "BC"));
  }
  /**
   * Validates that a signed entity has a valid message and signature. The signer's certificate is
   * validated to ensure authenticity of the message. Message tampering is also checked with the
   * message's digest and the signed digest in the message signature.
   *
   * @param signedEntity The entity containing the original signed part and the message signature.
   * @param signerCertificate The certificate used to sign the message.
   * @param anchors A collection of certificate anchors used to determine if the certificates used
   *     in the signature can be validated as trusted certificates.
   */
  public void checkSignature(
      SignedEntity signedEntity,
      X509Certificate signerCertificate,
      Collection<X509Certificate> anchors)
      throws SignatureValidationException {
    CMSSignedData signatureEnvelope = deserializeSignatureEnvelope(signedEntity);

    try {
      // there may be multiple signatures in the signed part... iterate through all the signing
      // certificates until one
      // is verified with the signerCertificate
      for (SignerInformation sigInfo :
          (Collection<SignerInformation>) signatureEnvelope.getSignerInfos().getSigners())
        if (sigInfo.verify(signerCertificate, CryptoExtensions.getJCEProviderName()))
          return; // verified... return

      // at this point the signerCertificate cannot be verified with one of the signing
      // certificates....
      throw new SignatureValidationException("Signature validation failure.");
    } catch (SignatureValidationException sve) {
      throw sve;
    } catch (Exception e) {
      throw new SignatureValidationException("Signature validation failure.", e);
    }
  }
  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)));
    }
  }
  public static boolean isValidSignature(CMSSignedData signedData, X509Certificate rootCert)
      throws Exception {

    boolean[] bArr = new boolean[2];
    bArr[0] = true;
    CertStore certsAndCRLs = signedData.getCertificatesAndCRLs("Collection", "BC");
    SignerInformationStore signers = signedData.getSignerInfos();
    Iterator it = signers.getSigners().iterator();

    if (it.hasNext()) {
      SignerInformation signer = (SignerInformation) it.next();
      SignerId signerConstraints = signer.getSID();
      signerConstraints.setKeyUsage(bArr);
      PKIXCertPathBuilderResult result = buildPath(rootCert, signer.getSID(), certsAndCRLs);
      return signer.verify(result.getPublicKey(), "BC");
    }

    return false;
  }
Example #8
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!");
      }
    }
  }
Example #9
0
  public boolean verifyEstrai(String pathBase, File pathFilesSignedd) {

    boolean esito = false;

    byte[] buffer = new byte[(int) pathFilesSignedd.length()];
    DataInputStream in;
    try {
      in = new DataInputStream(new FileInputStream(pathFilesSignedd));

      in.readFully(buffer);
      in.close();

      Security.addProvider(new BouncyCastleProvider());
      CMSSignedData signature = new CMSSignedData(buffer);
      SignerInformation signer =
          (SignerInformation) signature.getSignerInfos().getSigners().iterator().next();
      CertStore cs = signature.getCertificatesAndCRLs("Collection", "BC");

      Iterator iter = cs.getCertificates(signer.getSID()).iterator();
      X509Certificate certificate = (X509Certificate) iter.next();
      CMSProcessable sc = signature.getSignedContent();
      byte[] data = (byte[]) sc.getContent();

      // Verifie la signature
      // System.out.println(signer.verify(certificate, "BC"));
      esito = signer.verify(certificate.getPublicKey(), "BC");
      System.out.println("Verifica FILE: " + esito);

      String fatturapaName =
          pathFilesSignedd.getName().substring(0, pathFilesSignedd.getName().length() - 4).trim();
      System.out.println(" test:" + fatturapaName);
      FileOutputStream envfos = new FileOutputStream(new File(pathBase, fatturapaName));
      envfos.write(data);
      envfos.close();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return esito;
  }
  public void testDoubleNlCanonical() throws Exception {
    MimeMessage message = loadMessage("3nnn_smime.eml");

    SMIMESigned s = new SMIMESigned((MimeMultipart) message.getContent());

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

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

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

      // in this case the sig is invalid, but it's the lack of an exception from the content digest
      // we're looking for
      Assert.assertFalse(
          signer.verify(
              new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certHolder)));
    }
  }
  /**
   * 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))
  }
Example #12
0
  public boolean doJob() {
    String strMethod = "doJob()";

    try {
      // _validateCmsSignature();
      CMSSignedData cms = _getSignPkcs7();

      SignerInformationStore sis = cms.getSignerInfos();
      Collection colSignerInfo = sis.getSigners();
      Iterator itrSignerInfo = colSignerInfo.iterator();
      SignerInformation sin = (SignerInformation) itrSignerInfo.next();

      // r�cup�ration du certificat du signataire
      CertStore cse = cms.getCertificatesAndCRLs("Collection", CmsVerif._STR_KST_PROVIDER_BC);
      Iterator itrCert = cse.getCertificates(sin.getSID()).iterator();
      X509Certificate crt = (X509Certificate) itrCert.next();

      // Verifie la signature
      boolean blnCoreValidity = sin.verify(crt, CmsVerif._STR_KST_PROVIDER_BC);

      if (blnCoreValidity) {
        MySystem.s_printOutTrace(this, strMethod, "blnCoreValidity=true");

        String strBody = "CMS Detached signature is OK!";

        strBody += "\n\n" + ". CMS signature file location:";
        strBody += "\n  " + super._strPathAbsFileSig_;

        strBody += "\n\n" + ". Data file location:";
        strBody += "\n  " + super._strPathAbsFileData_;

        OPAbstract.s_showDialogInfo(super._frmOwner_, strBody);

        // SignerInfo sio = sin.toSignerInfo();

        SignerId sid = sin.getSID();

        if (sid != null) {
          System.out.println("sid.getSerialNumber()=" + sid.getSerialNumber());
          System.out.println("sid.getIssuerAsString()=" + sid.getIssuerAsString());
          System.out.println("sid.getSubjectAsString()=" + sid.getSubjectAsString());
        }

        /*System.out.println("sin.getDigestAlgOID()=" + sin.getDigestAlgOID());
        System.out.println("sin.getEncryptionAlgOID()=" + sin.getEncryptionAlgOID());
        System.out.println("sin.toString()=" + sin.toString());
        System.out.println("sin.getVersion()=" + sin.getVersion());*/
      } else {
        MySystem.s_printOutWarning(this, strMethod, "blnCoreValidity=true");

        String strBody = "CMS Detached signature is WRONG!";

        strBody += "\n\n" + ". CMS signature file location:";
        strBody += "\n  " + super._strPathAbsFileSig_;

        strBody += "\n\n" + ". Data file location:";
        strBody += "\n  " + super._strPathAbsFileData_;

        OPAbstract.s_showDialogWarning(super._frmOwner_, strBody);
      }

    } catch (Exception exc) {
      exc.printStackTrace();
      MySystem.s_printOutError(this, strMethod, "exc caught");

      String strBody = "Failed to verify CMS detached signature.";

      strBody += "\n\n" + "Possible reason: wrong data file";

      strBody += "\n\n" + "got exception.";
      strBody += "\n" + exc.getMessage();
      strBody += "\n\n" + "More: see your session.log";

      OPAbstract.s_showDialogError(super._frmOwner_, strBody);

      return false;
    }

    // TODO
    return true;
  }
  @Test
  public void testCMSSignature() throws Exception {
    // setup
    byte[] toBeSigned = "hello world".getBytes();
    String signatureDescription = "Test CMS Signature";
    CMSTestSignatureService signatureService =
        new CMSTestSignatureService(toBeSigned, signatureDescription);

    KeyPair keyPair = PkiTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    X509Certificate certificate =
        PkiTestUtils.generateCertificate(
            keyPair.getPublic(),
            "CN=Test",
            notBefore,
            notAfter,
            null,
            keyPair.getPrivate(),
            true,
            0,
            null,
            null,
            new KeyUsage(KeyUsage.nonRepudiation));
    List<X509Certificate> signingCertificateChain = new LinkedList<X509Certificate>();
    signingCertificateChain.add(certificate);

    // operate
    DigestInfo digestInfo =
        signatureService.preSign(null, signingCertificateChain, null, null, null);

    // verify
    assertNotNull(digestInfo);
    byte[] digestValue = digestInfo.digestValue;
    LOG.debug("digest value: " + Hex.encodeHexString(digestValue));
    assertNotNull(digestValue);
    assertEquals(signatureDescription, digestInfo.description);
    assertEquals("SHA1", digestInfo.digestAlgo);

    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate());
    byte[] digestInfoValue = ArrayUtils.addAll(PkiTestUtils.SHA1_DIGEST_INFO_PREFIX, digestValue);
    byte[] signatureValue = cipher.doFinal(digestInfoValue);
    LOG.debug("signature value: " + Hex.encodeHexString(signatureValue));

    // operate
    signatureService.postSign(signatureValue, signingCertificateChain);

    // verify
    byte[] cmsSignature = signatureService.getCMSSignature();
    CMSSignedData signedData = new CMSSignedData(cmsSignature);
    SignerInformationStore signers = signedData.getSignerInfos();
    Iterator<SignerInformation> iter = signers.getSigners().iterator();
    while (iter.hasNext()) {
      SignerInformation signer = iter.next();
      SignerId signerId = signer.getSID();
      assertTrue(signerId.match(certificate));
      assertTrue(signer.verify(keyPair.getPublic(), BouncyCastleProvider.PROVIDER_NAME));
    }
    byte[] data = (byte[]) signedData.getSignedContent().getContent();
    assertArrayEquals(toBeSigned, data);
  }
Example #14
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)));
    }
  }