List of usage examples for org.bouncycastle.cms CMSSignedData CMSSignedData
public CMSSignedData(ContentInfo sigData) throws CMSException
From source file:org.xipki.pki.scep.client.Client.java
License:Open Source License
private AuthorityCertStore retrieveNextCaAuthorityCertStore(final ScepHttpResponse httpResp) throws ScepClientException { String ct = httpResp.getContentType(); if (!ScepConstants.CT_X509_NEXT_CA_CERT.equalsIgnoreCase(ct)) { throw new ScepClientException("invalid Content-Type '" + ct + "'"); }//w ww .j a v a 2 s. co m CMSSignedData cmsSignedData; try { cmsSignedData = new CMSSignedData(httpResp.getContentBytes()); } catch (CMSException ex) { throw new ScepClientException("invalid SignedData message: " + ex.getMessage(), ex); } catch (IllegalArgumentException ex) { throw new ScepClientException("invalid SignedData message: " + ex.getMessage(), ex); } DecodedNextCaMessage resp; try { resp = DecodedNextCaMessage.decode(cmsSignedData, responseSignerCerts); } catch (MessageDecodingException ex) { throw new ScepClientException("could not decode response: " + ex.getMessage(), ex); } if (resp.getFailureMessage() != null) { throw new ScepClientException("Error: " + resp.getFailureMessage()); } Boolean bo = resp.isSignatureValid(); if (bo != null && !bo.booleanValue()) { throw new ScepClientException("Signature is invalid"); } Date signingTime = resp.getSigningTime(); long maxSigningTimeBias = getMaxSigningTimeBiasInMs(); if (maxSigningTimeBias > 0) { if (signingTime == null) { throw new ScepClientException("CMS signingTime attribute is not present"); } long now = System.currentTimeMillis(); long diff = now - signingTime.getTime(); if (diff < 0) { diff = -1 * diff; } if (diff > maxSigningTimeBias) { throw new ScepClientException("CMS signingTime is out of permitted period"); } } if (!resp.getSignatureCert().equals(authorityCertStore.getSignatureCert())) { throw new ScepClientException("the signature certificate must not be trusted"); } return resp.getAuthorityCertStore(); }
From source file:org.xipki.pki.scep.client.Client.java
License:Open Source License
private static CMSSignedData parsePkiMessage(final byte[] messageBytes) throws ScepClientException { try {/*from w w w .ja v a 2 s .c om*/ return new CMSSignedData(messageBytes); } catch (CMSException ex) { throw new ScepClientException(ex); } }
From source file:org.xipki.pki.scep.serveremulator.ScepServlet.java
License:Open Source License
private void service(final HttpServletRequest request, final HttpServletResponse response, final boolean post) throws ServletException, IOException { String servletPath = request.getServletPath(); AuditEvent event = new AuditEvent(new Date()); event.setApplicationName(ScepAuditConstants.APPNAME); event.setName(ScepAuditConstants.NAME_PERF); event.addEventData(ScepAuditConstants.NAME_servletPath, servletPath); AuditLevel auditLevel = AuditLevel.INFO; AuditStatus auditStatus = AuditStatus.SUCCESSFUL; String auditMessage = null;//from w w w . j a v a2 s . c o m OutputStream respStream = response.getOutputStream(); try { CaCaps caCaps = responder.getCaCaps(); if (post && !caCaps.containsCapability(CaCapability.POSTPKIOperation)) { final String message = "HTTP POST is not supported"; LOG.error(message); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.setContentLength(0); auditMessage = message; auditStatus = AuditStatus.FAILED; return; } String operation = request.getParameter("operation"); event.addEventData(ScepAuditConstants.NAME_operation, operation); if ("PKIOperation".equalsIgnoreCase(operation)) { CMSSignedData reqMessage; // parse the request try { byte[] content; if (post) { content = ScepUtil.read(request.getInputStream()); } else { String b64 = request.getParameter("message"); content = Base64.decode(b64); } reqMessage = new CMSSignedData(content); } catch (Exception ex) { final String message = "invalid request"; LogUtil.error(LOG, ex, message); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.setContentLength(0); auditMessage = message; auditStatus = AuditStatus.FAILED; return; } ContentInfo ci; try { ci = responder.servicePkiOperation(reqMessage, event); } catch (MessageDecodingException ex) { final String message = "could not decrypt and/or verify the request"; LogUtil.error(LOG, ex, message); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.setContentLength(0); auditMessage = message; auditStatus = AuditStatus.FAILED; return; } catch (CaException ex) { final String message = "system internal error"; LogUtil.error(LOG, ex, message); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentLength(0); auditMessage = message; auditStatus = AuditStatus.FAILED; return; } byte[] respBytes = ci.getEncoded(); response.setContentType(CT_RESPONSE); response.setContentLength(respBytes.length); respStream.write(respBytes); } else if (Operation.GetCACaps.getCode().equalsIgnoreCase(operation)) { // CA-Ident is ignored response.setContentType(ScepConstants.CT_TEXT_PLAIN); byte[] caCapsBytes = responder.getCaCaps().getBytes(); respStream.write(caCapsBytes); response.setContentLength(caCapsBytes.length); } else if (Operation.GetCACert.getCode().equalsIgnoreCase(operation)) { // CA-Ident is ignored byte[] respBytes; String ct; if (responder.getRaEmulator() == null) { ct = ScepConstants.CT_X509_CA_CERT; respBytes = responder.getCaEmulator().getCaCertBytes(); } else { ct = ScepConstants.CT_X509_CA_RA_CERT; CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator(); try { cmsSignedDataGen .addCertificate(new X509CertificateHolder(responder.getCaEmulator().getCaCert())); ct = ScepConstants.CT_X509_CA_RA_CERT; cmsSignedDataGen .addCertificate(new X509CertificateHolder(responder.getRaEmulator().getRaCert())); CMSSignedData degenerateSignedData = cmsSignedDataGen.generate(new CMSAbsentContent()); respBytes = degenerateSignedData.getEncoded(); } catch (CMSException ex) { final String message = "system internal error"; LogUtil.error(LOG, ex, message); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentLength(0); auditMessage = message; auditStatus = AuditStatus.FAILED; return; } } // end if (responder.getRAEmulator() == null) { response.setContentType(ct); response.setContentLength(respBytes.length); respStream.write(respBytes); } else if (Operation.GetNextCACert.getCode().equalsIgnoreCase(operation)) { if (responder.getNextCaAndRa() == null) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.setContentLength(0); auditMessage = "SCEP operation '" + operation + "' is not permitted"; auditStatus = AuditStatus.FAILED; return; } try { NextCaMessage nextCaMsg = new NextCaMessage(); nextCaMsg.setCaCert(X509Util.toX509Cert(responder.getNextCaAndRa().getCaCert())); if (responder.getNextCaAndRa().getRaCert() != null) { X509Certificate raCert = X509Util.toX509Cert(responder.getNextCaAndRa().getRaCert()); nextCaMsg.setRaCerts(Arrays.asList(raCert)); } ContentInfo signedData = responder.encode(nextCaMsg); byte[] respBytes = signedData.getEncoded(); response.setContentType(ScepConstants.CT_X509_NEXT_CA_CERT); response.setContentLength(respBytes.length); response.getOutputStream().write(respBytes); } catch (Exception ex) { final String message = "system internal error"; LogUtil.error(LOG, ex, message); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentLength(0); auditMessage = message; auditStatus = AuditStatus.FAILED; } } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.setContentLength(0); auditMessage = "unknown SCEP operation '" + operation + "'"; auditStatus = AuditStatus.FAILED; } // end if ("PKIOperation".equalsIgnoreCase(operation)) } catch (EOFException ex) { final String message = "connection reset by peer"; LogUtil.warn(LOG, ex, message); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentLength(0); } catch (Throwable th) { final String message = "Throwable thrown, this should not happen!"; LogUtil.error(LOG, th, message); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentLength(0); auditLevel = AuditLevel.ERROR; auditStatus = AuditStatus.FAILED; auditMessage = "internal error"; } finally { try { response.flushBuffer(); } finally { audit(auditService, event, auditLevel, auditStatus, auditMessage); } } // end try }
From source file:org.yawlfoundation.yawl.digitalSignature.DigitalSignature.java
License:Open Source License
public boolean checkSignature(byte[] Document) { try {//www. ja va2 s. com System.out.println("Beginning of Checking XmlSignature:"); System.out.println(Document); Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); // extract the Signed Fingerprint data CMSSignedData signature = new CMSSignedData(Document); System.out.println("Beginning of Checking XmlSignature:"); SignerInformation signer = (SignerInformation) signature.getSignerInfos().getSigners().iterator() .next(); System.out.println("Beginning of Checking XmlSignature:"); // Get from the collection the appropriate registered certificate CertStore cs = signature.getCertificatesAndCRLs("Collection", "BC"); Iterator iter = cs.getCertificates(signer.getSID()).iterator(); System.out.println("Beginning of Checking XmlSignature:"); X509Certificate certificate = (X509Certificate) iter.next(); System.out.println("Beginning of Checking XmlSignature:"); // get the contents of the document CMSProcessable sg = signature.getSignedContent(); byte[] data = (byte[]) sg.getContent(); String content = new String(data); //convert the document content to a valid xml document for YAWL org.w3c.dom.Document XMLNode = ConvertStringToDocument(content); org.jdom2.input.DOMBuilder builder = new org.jdom2.input.DOMBuilder(); Doc = builder.build(XMLNode); //Check the document System.out.println("xml to Sign:"); System.out.println(JDOMUtil.documentToString(Doc)); // get the name of the signer _Name = certificate.getSubjectDN().getName().split("(=|, )", -1).toString(); //return the result of the signature checking return signer.verify(certificate, "BC"); } catch (Exception e) { System.out.println("Test error"); e.printStackTrace(); return false; } }
From source file:test.integ.be.e_contract.mycarenet.etee.SealTest.java
License:Open Source License
private byte[] getVerifiedContent(byte[] cmsData) throws CertificateException, CMSException, IOException, OperatorCreationException { CMSSignedData cmsSignedData = new CMSSignedData(cmsData); SignerInformationStore signers = cmsSignedData.getSignerInfos(); SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next(); SignerId signerId = signer.getSID(); Store certificateStore = cmsSignedData.getCertificates(); Collection<X509CertificateHolder> certificateCollection = certificateStore.getMatches(signerId); if (false == certificateCollection.isEmpty()) { X509CertificateHolder certificateHolder = certificateCollection.iterator().next(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded())); SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder() .build(certificate);/* w ww. j av a 2 s. c o m*/ boolean signatureResult = signer.verify(signerInformationVerifier); assertTrue(signatureResult); LOG.debug("signer certificate: " + certificate); } else { LOG.warn("no signer matched"); } CMSTypedData signedContent = cmsSignedData.getSignedContent(); byte[] data = (byte[]) signedContent.getContent(); return data; }
From source file:test.unit.be.e_contract.mycarenet.etee.EncryptionTokenTest.java
License:Open Source License
@Test public void testReadEncryptionToken() throws Exception { InputStream etkInputStream = EncryptionTokenTest.class.getResourceAsStream("/etk-fcorneli.der"); assertNotNull(etkInputStream);/*from w w w . j av a 2 s. com*/ CMSSignedData cmsSignedData = new CMSSignedData(etkInputStream); LOG.debug("SignedData version: " + cmsSignedData.getVersion()); SignerInformationStore signers = cmsSignedData.getSignerInfos(); LOG.debug("signers: " + signers.size()); SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next(); SignerId signerId = signer.getSID(); LOG.debug("signer Id: " + signerId.getIssuer()); Store certificateStore = cmsSignedData.getCertificates(); @SuppressWarnings("unchecked") Collection<X509CertificateHolder> certificateCollection = certificateStore.getMatches(signerId); X509CertificateHolder certificateHolder = certificateCollection.iterator().next(); LOG.debug("certificate collection size: " + certificateCollection.size()); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded())); LOG.debug("signer certificate: " + certificate); CMSTypedData signedContent = cmsSignedData.getSignedContent(); byte[] data = (byte[]) signedContent.getContent(); X509Certificate encryptionCertificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(data)); LOG.debug("encryption certificate: " + encryptionCertificate); }
From source file:test.unit.be.e_contract.mycarenet.etee.SealTest.java
License:Open Source License
@Test public void testSeal() throws Exception { InputStream sealInputStream = SealTest.class.getResourceAsStream("/seal-fcorneli.der"); assertNotNull(sealInputStream);/*from w w w.j a v a 2 s . c o m*/ // check outer signature CMSSignedData cmsSignedData = new CMSSignedData(sealInputStream); SignerInformationStore signers = cmsSignedData.getSignerInfos(); SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next(); SignerId signerId = signer.getSID(); Store certificateStore = cmsSignedData.getCertificates(); @SuppressWarnings("unchecked") Collection<X509CertificateHolder> certificateCollection = certificateStore.getMatches(signerId); X509CertificateHolder certificateHolder = certificateCollection.iterator().next(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded())); Security.addProvider(new BouncyCastleProvider()); SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder() .build(certificate); boolean signatureResult = signer.verify(signerInformationVerifier); assertTrue(signatureResult); LOG.debug("signer certificate: " + certificate); CMSTypedData signedContent = cmsSignedData.getSignedContent(); byte[] data = (byte[]) signedContent.getContent(); // decrypt content CMSEnvelopedDataParser cmsEnvelopedDataParser = new CMSEnvelopedDataParser(data); LOG.debug("content encryption algo: " + cmsEnvelopedDataParser.getContentEncryptionAlgorithm().getAlgorithm().getId()); RecipientInformationStore recipientInformationStore = cmsEnvelopedDataParser.getRecipientInfos(); @SuppressWarnings("unchecked") Collection<RecipientInformation> recipients = recipientInformationStore.getRecipients(); RecipientInformation recipientInformation = recipients.iterator().next(); LOG.debug("recipient info type: " + recipientInformation.getClass().getName()); KeyTransRecipientInformation keyTransRecipientInformation = (KeyTransRecipientInformation) recipientInformation; }
From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractCMSSignatureServiceTest.java
License:Open Source License
@Test public void testCMSSignature() throws Exception { // setup//from w w w .jav a 2 s. c o m 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); }
From source file:test.unit.be.fedict.eid.applet.service.signer.CMSTest.java
License:Open Source License
/** * CMS signature with embedded data and external certificate. The CMS only * contains the original content, signature and some certificate selector. * /*from www. j a v a 2s. c o m*/ * @throws Exception */ @Test public void testCmsSignatureWithContent() throws Exception { // setup KeyPair keyPair = PkiTestUtils.generateKeyPair(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusMonths(1); X509Certificate certificate = generateSelfSignedCertificate(keyPair, "CN=Test", notBefore, notAfter); byte[] toBeSigned = "hello world".getBytes(); // operate CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); generator.addSigner(keyPair.getPrivate(), certificate, CMSSignedDataGenerator.DIGEST_SHA1); CMSProcessable content = new CMSProcessableByteArray(toBeSigned); CMSSignedData signedData = generator.generate(content, true, (String) null); byte[] cmsSignature = signedData.getEncoded(); LOG.debug("CMS signature: " + ASN1Dump.dumpAsString(new ASN1StreamParser(cmsSignature).readObject())); // verify 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(); LOG.debug("signer: " + signerId); assertTrue(signerId.match(certificate)); assertTrue(signer.verify(keyPair.getPublic(), BouncyCastleProvider.PROVIDER_NAME)); } byte[] data = (byte[]) signedData.getSignedContent().getContent(); assertArrayEquals(toBeSigned, data); LOG.debug("content type: " + signedData.getSignedContentTypeOID()); }