List of usage examples for org.bouncycastle.cms SignerInformation getSID
public SignerId getSID()
From source file:org.mailster.gui.dialogs.CertificateDialog.java
License:Open Source License
private void parseCertificateChains(TreeItem root) { if (message != null) { root.setText(Messages.getString("MailsterSWT.dialog.certificate.signers")); //$NON-NLS-1$ try {/*from ww w . j a v a 2 s . c o m*/ SMIMESigned signed = new SMIMESigned((MimeMultipart) message.getContent()); Iterator<?> it = signed.getSignerInfos().getSigners().iterator(); CertStore certsAndCRLs = signed.getCertificatesAndCRLs("Collection", "BC"); while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); Collection<? extends Certificate> l = certsAndCRLs.getCertificates(signer.getSID()); generateCertificateChainTree(root, l.toArray(new X509Certificate[l.size()])); } } catch (Exception e) { e.printStackTrace(); } } else { root.setText(Messages.getString("MailsterSWT.dialog.certificate.peer")); //$NON-NLS-1$ X509Certificate[] c = new X509Certificate[chain.length]; for (int i = 0, max = chain.length; i < max; i++) c[i] = (X509Certificate) chain[i]; generateCertificateChainTree(root, (X509Certificate[]) reverseArray(c)); } }
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 w ww . ja va 2s. com 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.roda.core.plugins.plugins.characterization.SignatureUtility.java
private boolean verifySignatures(CMSSignedData s, byte[] contentDigest) throws CertificateException, NoSuchAlgorithmException, NoSuchProviderException, CMSException { boolean valid = true; 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(); X509Certificate cert = new JcaX509CertificateConverter().setProvider(provider) .getCertificate(certHolder); boolean certValid = signer.verify(cert, provider); valid &= certValid;/*from www. j a va 2 s . com*/ if (!certValid) { LOGGER.error("Invalid certificate '{}'", cert); } if (contentDigest != null) { boolean digestValid = MessageDigest.isEqual(contentDigest, signer.getContentDigest()); valid &= digestValid; if (!digestValid) { LOGGER.error("Invalid digest '{}'", contentDigest); } } } return valid; }
From source file:org.signserver.module.cmssigner.CMSSignerTest.java
License:Open Source License
private void helperBasicCMSSign(final int workerId, final String sigAlg, final String expectedDigAlgOID, final String expectedEncAlgOID, final String includedCertificateLevelsProperty, final int expectedIncludedCertificateLevels) throws Exception { final int reqid = 37; final String testDocument = "Something to sign...123"; final GenericSignRequest signRequest = new GenericSignRequest(reqid, testDocument.getBytes()); // override signature algorithm if set if (sigAlg != null) { workerSession.setWorkerProperty(workerId, CMSSigner.SIGNATUREALGORITHM_PROPERTY, sigAlg); } else {// w w w. j av a 2s .c o m workerSession.removeWorkerProperty(workerId, CMSSigner.SIGNATUREALGORITHM_PROPERTY); } if (includedCertificateLevelsProperty != null) { workerSession.setWorkerProperty(workerId, WorkerConfig.PROPERTY_INCLUDE_CERTIFICATE_LEVELS, includedCertificateLevelsProperty); } else { workerSession.removeWorkerProperty(workerId, WorkerConfig.PROPERTY_INCLUDE_CERTIFICATE_LEVELS); } workerSession.reloadConfiguration(workerId); final GenericSignResponse res = (GenericSignResponse) workerSession.process(workerId, signRequest, new RequestContext()); final byte[] data = res.getProcessedData(); // Answer to right question assertSame("Request ID", reqid, res.getRequestID()); // Output for manual inspection final FileOutputStream fos = new FileOutputStream( new File(getSignServerHome(), "tmp" + File.separator + "signedcms_" + sigAlg + ".p7s")); fos.write((byte[]) data); fos.close(); // Check certificate returned final Certificate signercert = res.getSignerCertificate(); assertNotNull("Signer certificate", signercert); // Check that the signed data contains the document (i.e. not detached) final CMSSignedData signedData = new CMSSignedData(data); final byte[] content = (byte[]) signedData.getSignedContent().getContent(); assertEquals("Signed document", testDocument, new String(content)); // Get signers final Collection signers = signedData.getSignerInfos().getSigners(); final SignerInformation signer = (SignerInformation) signers.iterator().next(); // Verify using the signer's certificate assertTrue("Verification using signer certificate", signer.verify(signercert.getPublicKey(), "BC")); // Check that the signer's certificate is included CertStore certs = signedData.getCertificatesAndCRLs("Collection", "BC"); X509Principal issuer = new X509Principal(signer.getSID().getIssuer()); CertSelector cs = new AttributeCertificateHolder(issuer, signer.getSID().getSerialNumber()); Collection<? extends Certificate> signerCerts = certs.getCertificates(cs); assertEquals("Certificate included", expectedIncludedCertificateLevels, signerCerts.size()); if (!signerCerts.isEmpty()) { assertEquals(signercert, signerCerts.iterator().next()); } // check the signature algorithm assertEquals("Digest algorithm", expectedDigAlgOID, signer.getDigestAlgorithmID().getAlgorithm().getId()); assertEquals("Encryption algorithm", expectedEncAlgOID, signer.getEncryptionAlgOID()); }
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);/*from w ww .ja v a2 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). *///w w w . jav a2 s .com 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()); }/* w w w. ja va 2s.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 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. ja va 2 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; }
From source file:org.xwiki.crypto.signer.internal.cms.BcStoreUtils.java
License:Open Source License
/** * Retrieve the certificate matching the given signer from the certificate provider. * * @param provider a certificate provider. * @param signer the signer for which you want to retrieve the certificate. * @param factory a certificate factory to convert the certificate. * @return a certified public key.//from w w w . ja v a 2 s. com */ public static CertifiedPublicKey getCertificate(CertificateProvider provider, SignerInformation signer, CertificateFactory factory) { SignerId id = signer.getSID(); if (provider instanceof BcStoreX509CertificateProvider) { X509CertificateHolder cert = ((BcStoreX509CertificateProvider) provider).getCertificate(id); return (cert != null) ? BcUtils.convertCertificate(factory, cert) : null; } X500Name bcIssuer = id.getIssuer(); BigInteger serial = id.getSerialNumber(); byte[] keyId = id.getSubjectKeyIdentifier(); if (bcIssuer != null) { PrincipalIndentifier issuer = new DistinguishedName(bcIssuer); if (keyId != null) { return provider.getCertificate(issuer, serial, keyId); } return provider.getCertificate(issuer, serial); } if (keyId != null) { return provider.getCertificate(keyId); } return null; }
From source file:org.xwiki.crypto.x509.internal.X509SignatureService.java
License:Open Source License
/** * {@inheritDoc}//from ww w . j ava 2 s. c o m * * @see org.xwiki.crypto.CryptoService#verifyText(java.lang.String, java.lang.String) */ public XWikiX509Certificate verifyText(String signedText, String base64Signature) throws GeneralSecurityException { try { byte[] data = signedText.getBytes(); byte[] signature = Convert.fromBase64String(base64Signature); CMSSignedData cmsData = new CMSSignedData(new CMSProcessableByteArray(data), signature); CertStore certStore = cmsData.getCertificatesAndCRLs(CERT_STORE_TYPE, PROVIDER); SignerInformationStore signers = cmsData.getSignerInfos(); int numSigners = signers.getSigners().size(); if (numSigners != 1) { throw new GeneralSecurityException("Only one signature is supported, found " + numSigners); } XWikiX509Certificate result = null; for (Iterator<?> it = signers.getSigners().iterator(); it.hasNext();) { if (result != null) { throw new GeneralSecurityException("Only one certificate is supported"); } SignerInformation signer = (SignerInformation) it.next(); Collection<? extends Certificate> certs = certStore.getCertificates(signer.getSID()); for (Iterator<? extends Certificate> cit = certs.iterator(); cit.hasNext();) { Certificate certificate = cit.next(); if (!signer.verify(certificate.getPublicKey(), PROVIDER)) { return null; } if (certificate instanceof X509Certificate) { result = new XWikiX509Certificate((X509Certificate) certificate, null); } } } return result; } catch (CMSException exception) { // This means the text is invalid, our contract says we return null. // This message is hardcoded in org.bouncycastle.cms.SignerInformation if ("message-digest attribute value does not match calculated value".equals(exception.getMessage())) { return null; } throw new GeneralSecurityException(exception); } catch (Exception exception) { throw new GeneralSecurityException(exception); } }