List of usage examples for org.bouncycastle.cms SignerInformation verify
public boolean verify(SignerInformationVerifier verifier) throws CMSException
From source file:org.ejbca.batchenrollmentgui.BatchEnrollmentGUIView.java
License:Open Source License
@SuppressWarnings("unchecked") private static CMSValidationResult validateCMS(final CMSSignedData signedData, final Collection<Certificate> trustedCerts) { final CMSValidationResult result = new CMSValidationResult(); try {/*www.j a va2s. c o m*/ final ContentInfo ci = signedData.toASN1Structure(); if (LOG.isDebugEnabled()) { LOG.debug("ci.content: " + ci.getContent() + "\n" + "signedContent: " + signedData.getSignedContent()); } final Object content = signedData.getSignedContent().getContent(); if (content instanceof byte[]) { result.setContent((byte[]) content); } Store certs = signedData.getCertificates(); SignerInformationStore signers = signedData.getSignerInfos(); for (Object o : signers.getSigners()) { if (o instanceof SignerInformation) { SignerInformation si = (SignerInformation) o; if (LOG.isDebugEnabled()) { LOG.debug("*** SIGNATURE: " + "\n" + si.getSID()); } final Collection<X509CertificateHolder> signerCerts = (Collection<X509CertificateHolder>) certs .getMatches(si.getSID()); if (LOG.isDebugEnabled()) { LOG.debug("signerCerts: " + signerCerts); } JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter(); for (X509CertificateHolder signerCert : signerCerts) { final X509Certificate signerX509Cert = jcaX509CertificateConverter .getCertificate(signerCert); // Verify the signature JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME); JcaSignerInfoVerifierBuilder jcaSignerInfoVerifierBuilder = new JcaSignerInfoVerifierBuilder( calculatorProviderBuilder.build()).setProvider(BouncyCastleProvider.PROVIDER_NAME); boolean consistent = si .verify(jcaSignerInfoVerifierBuilder.build(signerX509Cert.getPublicKey())); if (consistent) { if (LOG.isDebugEnabled()) { LOG.debug((consistent ? "Consistent" : "Inconsistent") + " signature from " + signerX509Cert.getSubjectDN() + " issued by " + signerX509Cert.getIssuerDN()); } result.setValidSignature(consistent); try { final List<X509Certificate> signerChain = validateChain(signerX509Cert, certs, trustedCerts); result.setValidChain(true); result.setSignerChain(signerChain); JOptionPane.showMessageDialog(null, "Found valid signature from \"" + signerX509Cert.getSubjectDN() + "\"", "Signature check", JOptionPane.INFORMATION_MESSAGE); } catch (CertPathBuilderException ex) { result.setError(ex.getMessage()); JOptionPane.showMessageDialog(null, "Error: Certificate path:\n" + ex.getMessage(), "Signature check", JOptionPane.ERROR_MESSAGE); } catch (CertPathValidatorException ex) { result.setError(ex.getMessage()); JOptionPane.showMessageDialog(null, "Error: Certificate validation:\n" + ex.getMessage(), "Signature check", JOptionPane.ERROR_MESSAGE); } catch (InvalidAlgorithmParameterException ex) { result.setError(ex.getMessage()); JOptionPane.showMessageDialog(null, ex.getMessage(), "Signature check", JOptionPane.ERROR_MESSAGE); } catch (NoSuchAlgorithmException ex) { result.setError(ex.getMessage()); JOptionPane.showMessageDialog(null, ex.getMessage(), "Signature check", JOptionPane.ERROR_MESSAGE); } catch (GeneralSecurityException e) { //Crappy catch-all, but not much to do due to underlying BC-code result.setError(e.getMessage()); JOptionPane.showMessageDialog(null, e.getMessage(), "Error: Certificate validation:\n", JOptionPane.ERROR_MESSAGE); } } else { result.setError("Inconsistent signature!"); JOptionPane.showMessageDialog(null, "Error: Inconsisten signature!", "Signature check", JOptionPane.ERROR_MESSAGE); } } } } } catch (CMSException ex) { result.setError(ex.getMessage()); LOG.error("Parsing and validating CMS", ex); } catch (OperatorCreationException ex) { result.setError(ex.getMessage()); LOG.error("Parsing and validating CMS", ex); } catch (CertificateException ex) { result.setError(ex.getMessage()); LOG.error("Parsing and validating CMS", ex); } return result; }
From source file:org.ejbca.core.protocol.scep.ProtocolScepHttpTest.java
License:Open Source License
private void checkScepResponse(byte[] retMsg, String userDN, String _senderNonce, String _transId, boolean crlRep, String digestOid, boolean noca) throws CMSException, OperatorCreationException, NoSuchProviderException, CRLException, InvalidKeyException, NoSuchAlgorithmException, SignatureException, CertificateException { // Parse response message ///* w w w . j a v a2 s. c o m*/ CMSSignedData s = new CMSSignedData(retMsg); // The signer, i.e. the CA, check it's the right CA SignerInformationStore signers = s.getSignerInfos(); @SuppressWarnings("unchecked") Collection<SignerInformation> col = signers.getSigners(); assertTrue(col.size() > 0); Iterator<SignerInformation> iter = col.iterator(); SignerInformation signerInfo = iter.next(); // Check that the message is signed with the correct digest alg assertEquals(signerInfo.getDigestAlgOID(), digestOid); SignerId sinfo = signerInfo.getSID(); // Check that the signer is the expected CA assertEquals(CertTools.stringToBCDNString(cacert.getIssuerDN().getName()), CertTools.stringToBCDNString(sinfo.getIssuer().toString())); // Verify the signature JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME); JcaSignerInfoVerifierBuilder jcaSignerInfoVerifierBuilder = new JcaSignerInfoVerifierBuilder( calculatorProviderBuilder.build()).setProvider(BouncyCastleProvider.PROVIDER_NAME); boolean ret = signerInfo.verify(jcaSignerInfoVerifierBuilder.build(cacert.getPublicKey())); assertTrue(ret); // Get authenticated attributes AttributeTable tab = signerInfo.getSignedAttributes(); // --Fail info Attribute attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_failInfo)); // No failInfo on this success message assertNull(attr); // --Message type attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_messageType)); assertNotNull(attr); ASN1Set values = attr.getAttrValues(); assertEquals(values.size(), 1); ASN1String str = DERPrintableString.getInstance((values.getObjectAt(0))); String messageType = str.getString(); assertEquals("3", messageType); // --Success status attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_pkiStatus)); assertNotNull(attr); values = attr.getAttrValues(); assertEquals(values.size(), 1); str = DERPrintableString.getInstance((values.getObjectAt(0))); assertEquals(ResponseStatus.SUCCESS.getStringValue(), str.getString()); // --SenderNonce attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_senderNonce)); assertNotNull(attr); values = attr.getAttrValues(); assertEquals(values.size(), 1); ASN1OctetString octstr = ASN1OctetString.getInstance(values.getObjectAt(0)); // SenderNonce is something the server came up with, but it should be 16 // chars assertTrue(octstr.getOctets().length == 16); // --Recipient Nonce attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_recipientNonce)); assertNotNull(attr); values = attr.getAttrValues(); assertEquals(values.size(), 1); octstr = ASN1OctetString.getInstance(values.getObjectAt(0)); // recipient nonce should be the same as we sent away as sender nonce assertEquals(_senderNonce, new String(Base64.encode(octstr.getOctets()))); // --Transaction ID attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_transId)); assertNotNull(attr); values = attr.getAttrValues(); assertEquals(values.size(), 1); str = DERPrintableString.getInstance((values.getObjectAt(0))); // transid should be the same as the one we sent assertEquals(_transId, str.getString()); // // Check different message types // if (messageType.equals("3")) { // First we extract the encrypted data from the CMS enveloped data // contained // within the CMS signed data final CMSProcessable sp = s.getSignedContent(); final byte[] content = (byte[]) sp.getContent(); final CMSEnvelopedData ed = new CMSEnvelopedData(content); final RecipientInformationStore recipients = ed.getRecipientInfos(); Store certstore; @SuppressWarnings("unchecked") Collection<RecipientInformation> c = recipients.getRecipients(); assertEquals(c.size(), 1); Iterator<RecipientInformation> riIterator = c.iterator(); byte[] decBytes = null; RecipientInformation recipient = riIterator.next(); JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(key1.getPrivate()); rec.setContentProvider(BouncyCastleProvider.PROVIDER_NAME); decBytes = recipient.getContent(rec); // This is yet another CMS signed data CMSSignedData sd = new CMSSignedData(decBytes); // Get certificates from the signed data certstore = sd.getCertificates(); if (crlRep) { // We got a reply with a requested CRL @SuppressWarnings("unchecked") final Collection<X509CRLHolder> crls = (Collection<X509CRLHolder>) sd.getCRLs().getMatches(null); assertEquals(crls.size(), 1); final Iterator<X509CRLHolder> it = crls.iterator(); // CRL is first (and only) final X509CRL retCrl = new JcaX509CRLConverter().getCRL(it.next()); log.info("Got CRL with DN: " + retCrl.getIssuerDN().getName()); // check the returned CRL assertEquals(CertTools.getSubjectDN(cacert), CertTools.getIssuerDN(retCrl)); retCrl.verify(cacert.getPublicKey()); } else { // We got a reply with a requested certificate @SuppressWarnings("unchecked") final Collection<X509CertificateHolder> certs = (Collection<X509CertificateHolder>) certstore .getMatches(null); // EJBCA returns the issued cert and the CA cert (cisco vpn // client requires that the ca cert is included) if (noca) { assertEquals(certs.size(), 1); } else { assertEquals(certs.size(), 2); } final Iterator<X509CertificateHolder> it = certs.iterator(); // Issued certificate must be first boolean verified = false; boolean gotcacert = false; JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter(); while (it.hasNext()) { X509Certificate retcert = jcaX509CertificateConverter.getCertificate(it.next()); log.info("Got cert with DN: " + retcert.getSubjectDN().getName()); // check the returned certificate String subjectdn = CertTools.stringToBCDNString(retcert.getSubjectDN().getName()); if (CertTools.stringToBCDNString(userDN).equals(subjectdn)) { // issued certificate assertEquals(CertTools.stringToBCDNString(userDN), subjectdn); assertEquals(CertTools.getSubjectDN(cacert), CertTools.getIssuerDN(retcert)); retcert.verify(cacert.getPublicKey()); assertTrue(checkKeys(key1.getPrivate(), retcert.getPublicKey())); verified = true; } else { // ca certificate assertEquals(CertTools.getSubjectDN(cacert), CertTools.getSubjectDN(retcert)); gotcacert = true; } } assertTrue(verified); if (noca) { assertFalse(gotcacert); } else { assertTrue(gotcacert); } } } }
From source file:org.ejbca.util.CMS.java
License:Open Source License
/** * @param is signed data to be verified/*w w w. ja va 2 s .c om*/ * @param os signature removed from signed data * @param cert the certificate with the public key that should do the verification * @return true if the signing was to with the private key corresponding to the public key in the certificate. * @throws Exception */ public static VerifyResult verify(final InputStream is, OutputStream os, X509Certificate cert) throws Exception { final InputStream bis = new BufferedInputStream(is, bufferSize); final OutputStream bos = new BufferedOutputStream(os, bufferSize); final CMSSignedDataParser sp = new CMSSignedDataParser(new BcDigestCalculatorProvider(), bis); final CMSTypedStream sc = sp.getSignedContent(); final InputStream ris = sc.getContentStream(); fromInToOut(ris, bos); os.close(); sc.drain(); @SuppressWarnings("rawtypes") final Iterator it = sp.getSignerInfos().getSigners().iterator(); if (!it.hasNext()) { return null; } final SignerInformation signerInfo = (SignerInformation) it.next(); final Attribute attribute = (Attribute) signerInfo.getSignedAttributes().getAll(CMSAttributes.signingTime) .get(0); final Date date = Time.getInstance(attribute.getAttrValues().getObjectAt(0).toASN1Primitive()).getDate(); final SignerId id = signerInfo.getSID(); boolean result = false; try { JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME); JcaSignerInfoVerifierBuilder jcaSignerInfoVerifierBuilder = new JcaSignerInfoVerifierBuilder( calculatorProviderBuilder.build()).setProvider(BouncyCastleProvider.PROVIDER_NAME); result = signerInfo.verify(jcaSignerInfoVerifierBuilder.build(cert.getPublicKey())); } catch (Throwable t) { // NOPMD log.debug("Exception when verifying", t); } return new VerifyResult(date, result, id); }
From source file:org.jnotary.crypto.Verifier.java
License:Open Source License
@SuppressWarnings("rawtypes") public VerifyResult verifySignature(byte[] signedData, TrustedStore trustedUserCertificateStore) throws Exception { CMSSignedData sdata = new CMSSignedData(signedData); Store certStore = sdata.getCertificates(); SignerInformationStore signersStore = sdata.getSignerInfos(); Collection signers = signersStore.getSigners(); Iterator it = signers.iterator(); final Map<SignerId, java.security.cert.X509Certificate> certificates = new HashMap<SignerId, java.security.cert.X509Certificate>(); List<SignerInformation> signerInfoList = new ArrayList<SignerInformation>(); while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); signerInfoList.add(signer);/* w w w. j a v a 2 s . c o m*/ X509CertificateHolder cert = getCertificateHolder(trustedUserCertificateStore, certStore, signer); ByteArrayInputStream certBais = new ByteArrayInputStream(cert.getEncoded()); java.security.cert.X509Certificate x509cert = (java.security.cert.X509Certificate) CertificateFactory .getInstance("X.509").generateCertificate(certBais); certificates.put(signer.getSID(), x509cert); verifyDate(signer, x509cert); if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) throw new Exception("Signature verification failed for " + cert.getSubject().toString()); } CMSTypedData ctd = sdata.getSignedContent(); if (ctd == null) throw new Exception("Data not exists"); return new VerifyResult((byte[]) ctd.getContent(), signerInfoList, certificates); }
From source file:org.poreid.verify.sod.SOD.java
License:Open Source License
protected boolean verify() throws SODException { try {//from ww w .j a v a 2s. com /* verificar caminho de certificao sem ocsp/crl, aqui no local para essas consideraes */ X509CertificateHolder holder = (X509CertificateHolder) cms.getCertificates().getMatches(null).iterator() .next(); // apenas o primeiro certificado (s tem 1) X509Certificate cert = (X509Certificate) get(holder.getEncoded()); SignerInformationStore signerInformationStore = cms.getSignerInfos(); SignerInformation signerInformation = (SignerInformation) signerInformationStore.getSigners().iterator() .next(); // apenas 1 assinatura (s tem 1) if (!Util.isLeafCertificateValid(keystore, cert)) { return false; } /* verificar assinatura do cms */ ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder() .setProvider(new BouncyCastleProvider()).build(cert); DigestCalculatorProvider digestCalculatorProvider = new JcaDigestCalculatorProviderBuilder() .setProvider(new BouncyCastleProvider()).build(); SignatureAlgorithmIdentifierFinder signatureAlgorithmIdentifierFinder = new DefaultSignatureAlgorithmIdentifierFinder(); CMSSignatureAlgorithmNameGenerator signatureAlgorithmNameGenerator = new DefaultCMSSignatureAlgorithmNameGenerator(); SignerInformationVerifier signerInformationVerifier = new SignerInformationVerifier( signatureAlgorithmNameGenerator, signatureAlgorithmIdentifierFinder, contentVerifierProvider, digestCalculatorProvider); return signerInformation.verify(signerInformationVerifier); } catch (LeafCertificateValidationException | IOException | CertificateException | OperatorCreationException | CMSException ex) { throw new SODException("No foi possivel verificar o SOD (" + ex.getMessage() + ")", ex); } }
From source file:org.roda.common.certification.SignatureUtility.java
@SuppressWarnings("unchecked") private boolean verifySignatures(CMSSignedData s, byte[] contentDigest) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException, CertStoreException, CertificateException, OperatorCreationException { boolean valid = true; // CertStore certStore = s.getCertificatesAndCRLs("Collection", provider); Store<?> certStore = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); Collection<SignerInformation> c = signers.getSigners(); Iterator<SignerInformation> it = c.iterator(); while (it.hasNext()) { SignerInformation signer = it.next(); Collection<?> certCollection = certStore.getMatches(signer.getSID()); Iterator<?> certIt = certCollection.iterator(); X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next(); SignerInformationVerifier signerVerifierInformation = new BcRSASignerInfoVerifierBuilder( new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider()).build(certHolder); boolean certValid = signer.verify(signerVerifierInformation); valid &= certValid;//from ww w.j ava 2 s .c o m if (!certValid) { System.err.println("Invalid certificate " + certHolder); } if (contentDigest != null) { boolean digestValid = MessageDigest.isEqual(contentDigest, signer.getContentDigest()); valid &= digestValid; if (!digestValid) { System.err.println("Invalid digest " + contentDigest); } } } return valid; }
From source file:org.signserver.server.cryptotokens.P11SignTest.java
License:Open Source License
private void msauthTSSigner(final int workerId) throws Exception { // Generate CSR PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithRSA", "CN=Worker" + workerId, null); Base64SignerCertReqData reqData = (Base64SignerCertReqData) getWorkerSession() .getCertificateRequest(workerId, certReqInfo, false); // Issue certificate PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Base64.decode(reqData.getBase64CertReq())); KeyPair issuerKeyPair = CryptoUtils.generateRSA(512); X509CertificateHolder cert = new X509v3CertificateBuilder(new X500Name("CN=TestP11 Issuer"), BigInteger.ONE, new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)), csr.getSubject(), csr.getSubjectPublicKeyInfo()) .addExtension(org.bouncycastle.asn1.x509.X509Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping)) .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC") .build(issuerKeyPair.getPrivate())); // Install certificate and chain workerSession.uploadSignerCertificate(workerId, cert.getEncoded(), GlobalConfiguration.SCOPE_GLOBAL); workerSession.uploadSignerCertificateChain(workerId, Arrays.asList(cert.getEncoded()), GlobalConfiguration.SCOPE_GLOBAL); workerSession.reloadConfiguration(workerId); // Test active List<String> errors = workerSession.getStatus(workerId).getFatalErrors(); assertEquals("errors: " + errors, 0, errors.size()); // Test signing GenericSignRequest signRequest = new GenericSignRequest(678, MSAUTHCODE_REQUEST_DATA.getBytes()); final GenericSignResponse res = (GenericSignResponse) workerSession.process(workerId, signRequest, new RequestContext()); Certificate signercert = res.getSignerCertificate(); assertNotNull(signercert);/*w w w. j a v a 2 s .c om*/ byte[] buf = res.getProcessedData(); CMSSignedData s = new CMSSignedData(Base64.decode(buf)); int verified = 0; 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 signerCert = (X509CertificateHolder) certIt.next(); if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(signerCert))) { verified++; } } assertEquals("signer verified", 1, verified); }
From source file:org.votingsystem.signature.smime.SMIMESignedValidator.java
License:Open Source License
/** * verify that the sig is correct and that it was generated when the * certificate was current(assuming the cert is contained in the message). *///from www . ja v a 2 s . c om public static boolean isValidSignature(SMIMESigned smimeSigned) throws Exception { // certificates and crls passed in the signature Store certs = smimeSigned.getCertificates(); // SignerInfo blocks which contain the signatures SignerInformationStore signers = smimeSigned.getSignerInfos(); log.info("signers.size(): " + signers.size()); Collection c = signers.getSigners(); Iterator it = c.iterator(); boolean result = false; // check each signer while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); Collection certCollection = certs.getMatches(signer.getSID()); log.info("Collection matches: " + certCollection.size()); Iterator certIt = certCollection.iterator(); X509Certificate cert = new JcaX509CertificateConverter().setProvider(ContextVS.PROVIDER) .getCertificate((X509CertificateHolder) certIt.next()); log.info("SubjectDN: " + cert.getSubjectDN() + " - Not before: " + cert.getNotBefore() + " - Not after: " + cert.getNotAfter() + " - SigningTime: " + getSigningTime(signer)); if (signer .verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(ContextVS.PROVIDER).build(cert))) { log.info("signature verified"); result = true; } else { log.info("signature failed!"); result = false; } } return result; }
From source file:org.xipki.pki.scep.message.DecodedNextCaMessage.java
License:Open Source License
@SuppressWarnings("unchecked") public static DecodedNextCaMessage decode(final CMSSignedData pkiMessage, final CollectionStore<X509CertificateHolder> certStore) throws MessageDecodingException { ParamUtil.requireNonNull("pkiMessage", pkiMessage); SignerInformationStore signerStore = pkiMessage.getSignerInfos(); Collection<SignerInformation> signerInfos = signerStore.getSigners(); if (signerInfos.size() != 1) { throw new MessageDecodingException("number of signerInfos is not 1, but " + signerInfos.size()); }// www .j a v a2 s . co m SignerInformation signerInfo = signerInfos.iterator().next(); SignerId sid = signerInfo.getSID(); Collection<?> signedDataCerts = null; if (certStore != null) { signedDataCerts = certStore.getMatches(sid); } if (signedDataCerts == null || signedDataCerts.isEmpty()) { signedDataCerts = pkiMessage.getCertificates().getMatches(signerInfo.getSID()); } if (signedDataCerts == null || signedDataCerts.size() != 1) { throw new MessageDecodingException("could not find embedded certificate to verify the signature"); } AttributeTable signedAttrs = signerInfo.getSignedAttributes(); if (signedAttrs == null) { throw new MessageDecodingException("missing signed attributes"); } Date signingTime = null; // signingTime ASN1Encodable attrValue = ScepUtil.getFirstAttrValue(signedAttrs, CMSAttributes.signingTime); if (attrValue != null) { signingTime = Time.getInstance(attrValue).getDate(); } DecodedNextCaMessage ret = new DecodedNextCaMessage(); if (signingTime != null) { ret.setSigningTime(signingTime); } ASN1ObjectIdentifier digestAlgOid = signerInfo.getDigestAlgorithmID().getAlgorithm(); ret.setDigestAlgorithm(digestAlgOid); String sigAlgOid = signerInfo.getEncryptionAlgOID(); if (!PKCSObjectIdentifiers.rsaEncryption.getId().equals(sigAlgOid)) { ASN1ObjectIdentifier tmpDigestAlgOid; try { tmpDigestAlgOid = ScepUtil.extractDigesetAlgorithmIdentifier(signerInfo.getEncryptionAlgOID(), signerInfo.getEncryptionAlgParams()); } catch (Exception ex) { final String msg = "could not extract digest algorithm from signerInfo.signatureAlgorithm: " + ex.getMessage(); LOG.error(msg); LOG.debug(msg, ex); ret.setFailureMessage(msg); return ret; } if (!digestAlgOid.equals(tmpDigestAlgOid)) { ret.setFailureMessage( "digestAlgorithm and encryptionAlgorithm do not use" + " the same digestAlgorithm"); return ret; } } // end if X509CertificateHolder tmpSignerCert = (X509CertificateHolder) signedDataCerts.iterator().next(); X509Certificate signerCert; try { signerCert = ScepUtil.toX509Cert(tmpSignerCert.toASN1Structure()); } catch (CertificateException ex) { final String msg = "could not construct X509CertificateObject: " + ex.getMessage(); LOG.error(msg); LOG.debug(msg, ex); ret.setFailureMessage(msg); return ret; } ret.setSignatureCert(signerCert); // validate the signature SignerInformationVerifier verifier; try { verifier = new JcaSimpleSignerInfoVerifierBuilder().build(signerCert.getPublicKey()); } catch (OperatorCreationException ex) { final String msg = "could not build signature verifier: " + ex.getMessage(); LOG.error(msg); LOG.debug(msg, ex); ret.setFailureMessage(msg); return ret; } boolean signatureValid; try { signatureValid = signerInfo.verify(verifier); } catch (CMSException ex) { final String msg = "could not verify the signature: " + ex.getMessage(); LOG.error(msg); LOG.debug(msg, ex); ret.setFailureMessage(msg); return ret; } ret.setSignatureValid(signatureValid); if (!signatureValid) { return ret; } // MessageData CMSTypedData signedContent = pkiMessage.getSignedContent(); ASN1ObjectIdentifier signedContentType = signedContent.getContentType(); if (!CMSObjectIdentifiers.signedData.equals(signedContentType)) { // fall back: some SCEP client use id-data if (!CMSObjectIdentifiers.data.equals(signedContentType)) { ret.setFailureMessage( "either id-signedData or id-data is excepted, but not '" + signedContentType.getId()); return ret; } } ContentInfo contentInfo = ContentInfo.getInstance((byte[]) signedContent.getContent()); SignedData signedData = SignedData.getInstance(contentInfo.getContent()); List<X509Certificate> certs; try { certs = ScepUtil.getCertsFromSignedData(signedData); } catch (CertificateException ex) { final String msg = "could not extract Certificates from the message: " + ex.getMessage(); LOG.error(msg); LOG.debug(msg, ex); ret.setFailureMessage(msg); return ret; } final int n = certs.size(); X509Certificate caCert = null; List<X509Certificate> raCerts = new LinkedList<X509Certificate>(); for (int i = 0; i < n; i++) { X509Certificate cert = certs.get(i); if (cert.getBasicConstraints() > -1) { if (caCert != null) { final String msg = "multiple CA certificates is returned, but exactly 1 is expected"; LOG.error(msg); ret.setFailureMessage(msg); return ret; } caCert = cert; } else { raCerts.add(cert); } } // end for if (caCert == null) { final String msg = "no CA certificate is returned"; LOG.error(msg); ret.setFailureMessage(msg); return ret; } X509Certificate[] locaRaCerts; if (raCerts.isEmpty()) { locaRaCerts = null; } else { locaRaCerts = raCerts.toArray(new X509Certificate[0]); } AuthorityCertStore authorityCertStore = AuthorityCertStore.getInstance(caCert, locaRaCerts); ret.setAuthorityCertStore(authorityCertStore); return ret; }
From source file:org.xipki.pki.scep.message.DecodedPkiMessage.java
License:Open Source License
@SuppressWarnings("unchecked") public static DecodedPkiMessage decode(final CMSSignedData pkiMessage, final EnvelopedDataDecryptor recipient, final CollectionStore<X509CertificateHolder> certStore) throws MessageDecodingException { ParamUtil.requireNonNull("pkiMessage", pkiMessage); ParamUtil.requireNonNull("recipient", recipient); SignerInformationStore signerStore = pkiMessage.getSignerInfos(); Collection<SignerInformation> signerInfos = signerStore.getSigners(); if (signerInfos.size() != 1) { throw new MessageDecodingException("number of signerInfos is not 1, but " + signerInfos.size()); }//from w w w .j a v a2 s . c o m SignerInformation signerInfo = signerInfos.iterator().next(); SignerId sid = signerInfo.getSID(); Collection<?> signedDataCerts = null; if (certStore != null) { signedDataCerts = certStore.getMatches(sid); } if (signedDataCerts == null || signedDataCerts.isEmpty()) { signedDataCerts = pkiMessage.getCertificates().getMatches(signerInfo.getSID()); } if (signedDataCerts == null || signedDataCerts.size() != 1) { throw new MessageDecodingException("could not find embedded certificate to verify the signature"); } AttributeTable signedAttrs = signerInfo.getSignedAttributes(); if (signedAttrs == null) { throw new MessageDecodingException("missing SCEP attributes"); } Date signingTime = null; // signingTime ASN1Encodable attrValue = ScepUtil.getFirstAttrValue(signedAttrs, CMSAttributes.signingTime); if (attrValue != null) { signingTime = Time.getInstance(attrValue).getDate(); } // transactionId String str = getPrintableStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_TRANSACTION_ID); if (str == null || str.isEmpty()) { throw new MessageDecodingException("missing required SCEP attribute transactionId"); } TransactionId transactionId = new TransactionId(str); // messageType Integer intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_MESSAGE_TYPE); if (intValue == null) { throw new MessageDecodingException( "tid " + transactionId.getId() + ": missing required SCEP attribute messageType"); } MessageType messageType; try { messageType = MessageType.forValue(intValue); } catch (IllegalArgumentException ex) { throw new MessageDecodingException( "tid " + transactionId.getId() + ": invalid messageType '" + intValue + "'"); } // senderNonce Nonce senderNonce = getNonceAttrValue(signedAttrs, ScepObjectIdentifiers.ID_SENDER_NONCE); if (senderNonce == null) { throw new MessageDecodingException( "tid " + transactionId.getId() + ": missing required SCEP attribute senderNonce"); } DecodedPkiMessage ret = new DecodedPkiMessage(transactionId, messageType, senderNonce); if (signingTime != null) { ret.setSigningTime(signingTime); } Nonce recipientNonce = null; try { recipientNonce = getNonceAttrValue(signedAttrs, ScepObjectIdentifiers.ID_RECIPIENT_NONCE); } catch (MessageDecodingException ex) { ret.setFailureMessage("could not parse recipientNonce: " + ex.getMessage()); } if (recipientNonce != null) { ret.setRecipientNonce(recipientNonce); } PkiStatus pkiStatus = null; FailInfo failInfo = null; if (MessageType.CertRep == messageType) { // pkiStatus try { intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_PKI_STATUS); } catch (MessageDecodingException ex) { ret.setFailureMessage("could not parse pkiStatus: " + ex.getMessage()); return ret; } if (intValue == null) { ret.setFailureMessage("missing required SCEP attribute pkiStatus"); return ret; } try { pkiStatus = PkiStatus.forValue(intValue); } catch (IllegalArgumentException ex) { ret.setFailureMessage("invalid pkiStatus '" + intValue + "'"); return ret; } ret.setPkiStatus(pkiStatus); // failureInfo if (pkiStatus == PkiStatus.FAILURE) { try { intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_FAILINFO); } catch (MessageDecodingException ex) { ret.setFailureMessage("could not parse failInfo: " + ex.getMessage()); return ret; } if (intValue == null) { ret.setFailureMessage("missing required SCEP attribute failInfo"); return ret; } try { failInfo = FailInfo.forValue(intValue); } catch (IllegalArgumentException ex) { ret.setFailureMessage("invalid failInfo '" + intValue + "'"); return ret; } ret.setFailInfo(failInfo); } // end if(pkiStatus == PkiStatus.FAILURE) } // end if (MessageType.CertRep == messageType) // other signedAttributes Attribute[] attrs = signedAttrs.toASN1Structure().getAttributes(); for (Attribute attr : attrs) { ASN1ObjectIdentifier type = attr.getAttrType(); if (!SCEP_ATTR_TYPES.contains(type)) { ret.addSignendAttribute(type, attr.getAttrValues().getObjectAt(0)); } } // unsignedAttributes AttributeTable unsignedAttrs = signerInfo.getUnsignedAttributes(); attrs = (unsignedAttrs == null) ? null : unsignedAttrs.toASN1Structure().getAttributes(); if (attrs != null) { for (Attribute attr : attrs) { ASN1ObjectIdentifier type = attr.getAttrType(); ret.addUnsignendAttribute(type, attr.getAttrValues().getObjectAt(0)); } } ASN1ObjectIdentifier digestAlgOid = signerInfo.getDigestAlgorithmID().getAlgorithm(); ret.setDigestAlgorithm(digestAlgOid); String sigAlgOid = signerInfo.getEncryptionAlgOID(); if (!PKCSObjectIdentifiers.rsaEncryption.getId().equals(sigAlgOid)) { ASN1ObjectIdentifier tmpDigestAlgOid; try { tmpDigestAlgOid = ScepUtil.extractDigesetAlgorithmIdentifier(signerInfo.getEncryptionAlgOID(), signerInfo.getEncryptionAlgParams()); } catch (Exception ex) { final String msg = "could not extract digest algorithm from signerInfo.signatureAlgorithm: " + ex.getMessage(); LOG.error(msg); LOG.debug(msg, ex); ret.setFailureMessage(msg); return ret; } if (!digestAlgOid.equals(tmpDigestAlgOid)) { ret.setFailureMessage( "digestAlgorithm and encryptionAlgorithm do not use the" + " same digestAlgorithm"); return ret; } // end if } // end if X509CertificateHolder tmpSignerCert = (X509CertificateHolder) signedDataCerts.iterator().next(); X509Certificate signerCert; try { signerCert = ScepUtil.toX509Cert(tmpSignerCert.toASN1Structure()); } catch (CertificateException ex) { final String msg = "could not construct X509Certificate: " + ex.getMessage(); LOG.error(msg); LOG.debug(msg, ex); ret.setFailureMessage(msg); return ret; } ret.setSignatureCert(signerCert); // validate the signature SignerInformationVerifier verifier; try { verifier = new JcaSimpleSignerInfoVerifierBuilder().build(signerCert.getPublicKey()); } catch (OperatorCreationException ex) { final String msg = "could not build signature verifier: " + ex.getMessage(); LOG.error(msg); LOG.debug(msg, ex); ret.setFailureMessage(msg); return ret; } boolean signatureValid; try { signatureValid = signerInfo.verify(verifier); } catch (CMSException ex) { final String msg = "could not verify the signature: " + ex.getMessage(); LOG.error(msg); LOG.debug(msg, ex); ret.setFailureMessage(msg); return ret; } ret.setSignatureValid(signatureValid); if (!signatureValid) { return ret; } if (MessageType.CertRep == messageType && (pkiStatus == PkiStatus.FAILURE | pkiStatus == PkiStatus.PENDING)) { return ret; } // MessageData CMSTypedData signedContent = pkiMessage.getSignedContent(); ASN1ObjectIdentifier signedContentType = signedContent.getContentType(); if (!CMSObjectIdentifiers.envelopedData.equals(signedContentType)) { // fall back: some SCEP client, such as JSCEP use id-data if (!CMSObjectIdentifiers.data.equals(signedContentType)) { ret.setFailureMessage( "either id-envelopedData or id-data is excepted, but not '" + signedContentType.getId()); return ret; } } CMSEnvelopedData envData; try { envData = new CMSEnvelopedData((byte[]) signedContent.getContent()); } catch (CMSException ex) { final String msg = "could not create the CMSEnvelopedData: " + ex.getMessage(); LOG.error(msg); LOG.debug(msg, ex); ret.setFailureMessage(msg); return ret; } ret.setContentEncryptionAlgorithm(envData.getContentEncryptionAlgorithm().getAlgorithm()); byte[] encodedMessageData; try { encodedMessageData = recipient.decrypt(envData); } catch (MessageDecodingException ex) { final String msg = "could not create the CMSEnvelopedData: " + ex.getMessage(); LOG.error(msg); LOG.debug(msg, ex); ret.setFailureMessage(msg); ret.setDecryptionSuccessful(false); return ret; } ret.setDecryptionSuccessful(true); try { if (MessageType.PKCSReq == messageType || MessageType.RenewalReq == messageType || MessageType.UpdateReq == messageType) { CertificationRequest messageData = CertificationRequest.getInstance(encodedMessageData); ret.setMessageData(messageData); } else if (MessageType.CertPoll == messageType) { IssuerAndSubject messageData = IssuerAndSubject.getInstance(encodedMessageData); ret.setMessageData(messageData); } else if (MessageType.GetCert == messageType || MessageType.GetCRL == messageType) { IssuerAndSerialNumber messageData = IssuerAndSerialNumber.getInstance(encodedMessageData); ret.setMessageData(messageData); ret.setMessageData(messageData); } else if (MessageType.CertRep == messageType) { ContentInfo ci = ContentInfo.getInstance(encodedMessageData); ret.setMessageData(ci); } else { throw new RuntimeException("should not reach here, unknown messageType " + messageType); } } catch (Exception ex) { final String msg = "could not parse the messageData: " + ex.getMessage(); LOG.error(msg); LOG.debug(msg, ex); ret.setFailureMessage(msg); return ret; } return ret; }