List of usage examples for org.bouncycastle.cms CMSSignedData getEncoded
public byte[] getEncoded() throws IOException
From source file:org.usrz.libs.crypto.utils.PKCS7.java
License:Apache License
/** * Prepare a detached <code>PKCS7</code> signature. * * @param privateKey The private key to use for signing * @param certificate The certificate associated with the private key. * @param authorities An optional list of certificate authorities to include. * @param data The {@linkplain Hash hashing algorithm} to use for signing. * @param data The binary data to sign./*from w ww . j av a 2 s. c om*/ * @return The <code>PKCS7</code> as a byte array. * @throws SignatureException If there was a problem generating the signature. */ public static byte[] sign(final PrivateKey privateKey, final X509Certificate certificate, final List<X509Certificate> authorities, final Hash hash, final byte[] data) throws SignatureException { try { final String signatureAlgorithm = CryptoUtils.getSignatureAlgorithm(privateKey, hash); final ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey); final CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); generator.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()) .setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator()) .build(signer, certificate)); final Set<Certificate> certificates = new HashSet<>(); if (authorities != null) { for (Certificate authority : authorities) certificates.add(authority); } certificates.add(certificate); generator.addCertificates(new JcaCertStore(certificates)); final CMSTypedData cmsData = new CMSProcessableByteArray(data); final CMSSignedData signeddata = generator.generate(cmsData, false); return signeddata.getEncoded(); } catch (Exception exception) { throw new SignatureException("Signature could not be generated", exception); } }
From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java
License:Open Source License
public byte[] getPKIMessage(InputStream inputStream) throws KeystoreException { try {// w w w .j a va 2 s . c o m CMSSignedData signedData = new CMSSignedData(inputStream); Store reqStore = signedData.getCertificates(); @SuppressWarnings("unchecked") Collection<X509CertificateHolder> reqCerts = reqStore.getMatches(null); KeyStoreReader keyStoreReader = new KeyStoreReader(); PrivateKey privateKeyRA = keyStoreReader.getRAPrivateKey(); PrivateKey privateKeyCA = keyStoreReader.getCAPrivateKey(); X509Certificate certRA = (X509Certificate) keyStoreReader.getRACertificate(); X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate(); CertificateFactory certificateFactory = CertificateFactory.getInstance(CertificateManagementConstants.X_509); X509CertificateHolder holder = reqCerts.iterator().next(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(holder.getEncoded()); X509Certificate reqCert = (X509Certificate) certificateFactory.generateCertificate(byteArrayInputStream); PkcsPkiEnvelopeDecoder envelopeDecoder = new PkcsPkiEnvelopeDecoder(certRA, privateKeyRA); PkiMessageDecoder messageDecoder = new PkiMessageDecoder(reqCert, envelopeDecoder); PkiMessage<?> pkiMessage = messageDecoder.decode(signedData); Object msgData = pkiMessage.getMessageData(); Nonce senderNonce = Nonce.nextNonce(); TransactionId transId = pkiMessage.getTransactionId(); Nonce recipientNonce = pkiMessage.getSenderNonce(); CertRep certRep; PKCS10CertificationRequest certRequest = (PKCS10CertificationRequest) msgData; X509Certificate generatedCert = generateCertificateFromCSR( privateKeyCA, certRequest, certCA.getIssuerX500Principal().getName()); List<X509Certificate> issued = new ArrayList<X509Certificate>(); issued.add(generatedCert); if (issued.size() == 0) { certRep = new CertRep(transId, senderNonce, recipientNonce, FailInfo.badCertId); } else { CMSSignedData messageData = getMessageData(issued); certRep = new CertRep(transId, senderNonce, recipientNonce, messageData); } PkcsPkiEnvelopeEncoder envEncoder = new PkcsPkiEnvelopeEncoder(reqCert, CertificateManagementConstants.DES_EDE); PkiMessageEncoder encoder = new PkiMessageEncoder(privateKeyRA, certRA, envEncoder); CMSSignedData cmsSignedData = encoder.encode(certRep); return cmsSignedData.getEncoded(); } catch (CertificateException e) { String errorMsg = "Certificate issue occurred when generating getPKIMessage"; throw new KeystoreException(errorMsg, e); } catch (MessageEncodingException e) { String errorMsg = "Message encoding issue occurred when generating getPKIMessage"; throw new KeystoreException(errorMsg, e); } catch (IOException e) { String errorMsg = "Input output issue occurred when generating getPKIMessage"; throw new KeystoreException(errorMsg, e); } catch (MessageDecodingException e) { String errorMsg = "Message decoding issue occurred when generating getPKIMessage"; throw new KeystoreException(errorMsg, e); } catch (CMSException e) { String errorMsg = "CMS issue occurred when generating getPKIMessage"; throw new KeystoreException(errorMsg, e); } }
From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java
License:Open Source License
public SCEPResponse getCACert() throws KeystoreException { try {/*from ww w. java 2s . c o m*/ SCEPResponse scepResponse = new SCEPResponse(); KeyStoreReader keyStoreReader = new KeyStoreReader(); byte[] caBytes = keyStoreReader.getCACertificate().getEncoded(); byte[] raBytes = keyStoreReader.getRACertificate().getEncoded(); final List<X509Certificate> certs = getRootCertificates(caBytes, raBytes); byte[] bytes; if (certs.size() == 0) { scepResponse.setResultCriteria(CAStatus.CA_CERT_FAILED); bytes = new byte[0]; } else if (certs.size() == 1) { scepResponse.setResultCriteria(CAStatus.CA_CERT_RECEIVED); bytes = certs.get(0).getEncoded(); } else { scepResponse.setResultCriteria(CAStatus.CA_RA_CERT_RECEIVED); CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); JcaCertStore store = new JcaCertStore(certs); generator.addCertificates(store); CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent()); bytes = degenerateSd.getEncoded(); } scepResponse.setEncodedResponse(bytes); return scepResponse; } catch (CertificateEncodingException e) { String errorMsg = "Certificate encoding issue occurred in getCACert"; throw new KeystoreException(errorMsg, e); } catch (CMSException e) { String errorMsg = "CMS issue occurred in getCACert"; throw new KeystoreException(errorMsg, e); } catch (IOException e) { String errorMsg = "Input output issue occurred in getCACert"; throw new KeystoreException(errorMsg, e); } }
From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateManagementServiceImplTests.java
License:Open Source License
@Test(description = "This test case tests Signature verification of a Certificate against the keystore") public void testVerifySignature() throws KeystoreException, CertificateEncodingException, CMSException, IOException { BASE64Encoder encoder = new BASE64Encoder(); //generate and save a certificate in the keystore X509Certificate x509Certificate = managementService.generateX509Certificate(); //Generate CMSdata CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); List<X509Certificate> list = new ArrayList<>(); list.add(x509Certificate);/*from w w w . ja va 2s .c o m*/ JcaCertStore store = new JcaCertStore(list); generator.addCertificates(store); CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent()); byte[] signature = degenerateSd.getEncoded(); boolean verifySignature = managementService.verifySignature(encoder.encode(signature)); Assert.assertNotNull(verifySignature); Assert.assertTrue(verifySignature); log.info("VerifySignature Test Successful"); }
From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateManagementServiceImplTests.java
License:Open Source License
@Test(description = "This test case tests extracting Certificate from the header Signature") public void testExtractCertificateFromSignature() throws KeystoreException, CertificateEncodingException, CMSException, IOException { BASE64Encoder encoder = new BASE64Encoder(); //generate and save a certificate in the keystore X509Certificate x509Certificate = managementService.generateX509Certificate(); //Generate CMSdata CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); List<X509Certificate> list = new ArrayList<>(); list.add(x509Certificate);/*from www . j av a 2s.co m*/ JcaCertStore store = new JcaCertStore(list); generator.addCertificates(store); CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent()); byte[] signature = degenerateSd.getEncoded(); X509Certificate certificate = managementService.extractCertificateFromSignature(encoder.encode(signature)); Assert.assertNotNull(certificate); Assert.assertEquals(certificate.getType(), CertificateManagementConstants.X_509); log.info("ExtractCertificateFromSignature Test Successful"); }
From source file:org.wso2.carbon.identity.certificateauthority.endpoint.scep.ScepEndpoint.java
License:Open Source License
private Response pkiOperation(int tenantId, HttpServletRequest request) { try {/* ww w . j av a 2 s. c o m*/ byte[] body = getMessageBytes(request); CMSSignedData sd = new CMSSignedData(body); Store reqStore = sd.getCertificates(); Collection<X509CertificateHolder> reqCerts = reqStore.getMatches(null); CertificateFactory factory = CertificateFactory.getInstance("X.509"); X509CertificateHolder holder = reqCerts.iterator().next(); ByteArrayInputStream bais = new ByteArrayInputStream(holder.getEncoded()); X509Certificate reqCert = (X509Certificate) factory.generateCertificate(bais); PkcsPkiEnvelopeDecoder envDecoder = new PkcsPkiEnvelopeDecoder(getRecipient(tenantId), getRecipientKey(tenantId)); PkiMessageDecoder decoder = new PkiMessageDecoder(reqCert, envDecoder); PkiMessage<?> msg = decoder.decode(sd); MessageType msgType = msg.getMessageType(); Object msgData = msg.getMessageData(); Nonce senderNonce = Nonce.nextNonce(); TransactionId transId = msg.getTransactionId(); Nonce recipientNonce = msg.getSenderNonce(); CertRep certRep; if (msgType == MessageType.GET_CERT) { final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData; final X509Name principal = iasn.getName(); final BigInteger serial = iasn.getSerialNumber().getValue(); List<X509Certificate> issued = doGetCert(principal, serial); if (issued.size() == 0) { certRep = new CertRep(transId, senderNonce, recipientNonce, FailInfo.badCertId); } else { CMSSignedData messageData = getMessageData(issued); certRep = new CertRep(transId, senderNonce, recipientNonce, messageData); } } else if (msgType == MessageType.GET_CERT_INITIAL) { final IssuerAndSubject ias = (IssuerAndSubject) msgData; final X500Name issuer = X500Name.getInstance(ias.getIssuer()); final X500Name subject = X500Name.getInstance(ias.getSubject()); try { List<X509Certificate> issued = doGetCertInitial(tenantId, issuer, subject, transId); if (issued.size() == 0) { certRep = new CertRep(transId, senderNonce, recipientNonce); } else { CMSSignedData messageData = getMessageData(issued); certRep = new CertRep(transId, senderNonce, recipientNonce, messageData); } } catch (Exception e) { throw new ServletException(e); } } else if (msgType == MessageType.GET_CRL) { final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData; final X509Name issuer = iasn.getName(); final BigInteger serialNumber = iasn.getSerialNumber().getValue(); try { CMSSignedData messageData = getMessageData(doGetCrl(tenantId, issuer, serialNumber)); certRep = new CertRep(transId, senderNonce, recipientNonce, messageData); } catch (Exception e) { throw new ServletException(e); } } else if (msgType == MessageType.PKCS_REQ) { final PKCS10CertificationRequest certReq = (PKCS10CertificationRequest) msgData; try { List<X509Certificate> issued = doEnrol(certReq, transId, tenantId); if (issued.size() == 0) { certRep = new CertRep(transId, senderNonce, recipientNonce); } else { CMSSignedData messageData = getMessageData(issued); certRep = new CertRep(transId, senderNonce, recipientNonce, messageData); } } catch (Exception e) { throw new ServletException(e); } } else { log.error("Unknown message for operation"); return ResponseUtils.badRequest("Unknown message for operation"); } PkcsPkiEnvelopeEncoder envEncoder = new PkcsPkiEnvelopeEncoder(reqCert, "DESede"); PkiMessageEncoder encoder = new PkiMessageEncoder(getSignerKey(tenantId), getSigner(tenantId), envEncoder); CMSSignedData signedData = encoder.encode(certRep); return Response.ok().type("application/x-pki-message").entity(signedData.getEncoded()).build(); } catch (Exception e) { log.error(e); return ResponseUtils.serverError(); } }
From source file:org.xipki.pki.ca.server.impl.scep.CaCertRespBytes.java
License:Open Source License
CaCertRespBytes(final X509Certificate caCert, final X509Certificate responderCert) throws CMSException, CertificateException { ParamUtil.requireNonNull("caCert", caCert); ParamUtil.requireNonNull("responderCert", responderCert); CMSSignedDataGenerator cmsSignedDataGen = new CMSSignedDataGenerator(); try {/* w ww . j a v a 2 s. c o m*/ cmsSignedDataGen.addCertificate(new X509CertificateHolder(caCert.getEncoded())); cmsSignedDataGen.addCertificate(new X509CertificateHolder(responderCert.getEncoded())); CMSSignedData degenerateSignedData = cmsSignedDataGen.generate(new CMSAbsentContent()); bytes = degenerateSignedData.getEncoded(); } catch (IOException ex) { throw new CMSException("could not build CMS SignedDta"); } }
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;/*w ww . j a v a 2 s . com*/ 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.xwiki.crypto.x509.internal.X509SignatureService.java
License:Open Source License
/** * {@inheritDoc}// ww w . j a v a2 s . c o m * * @see org.xwiki.crypto.CryptoService#signText(java.lang.String, org.xwiki.crypto.data.XWikiX509KeyPair) */ public String signText(final String textToSign, final XWikiX509KeyPair toSignWith, final String password) throws GeneralSecurityException { XWikiX509Certificate certificate = toSignWith.getCertificate(); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); Collection<?> certs = Collections.singleton(certificate); CertStore store = CertStore.getInstance(CERT_STORE_TYPE, new CollectionCertStoreParameters(certs)); try { gen.addCertificatesAndCRLs(store); gen.addSigner(toSignWith.getPrivateKey(password), certificate, DIGEST_OID); byte[] data = textToSign.getBytes(); CMSSignedData cmsData = gen.generate(new CMSProcessableByteArray(data), false, PROVIDER); return Convert.toBase64String(cmsData.getEncoded()); } catch (GeneralSecurityException exception) { throw exception; } catch (Exception exception) { throw new GeneralSecurityException(exception); } }
From source file:test.unit.be.fedict.eid.applet.service.signer.CMSTest.java
License:Open Source License
/** * CMS signature with external data and external certificate. The CMS only * contains the signature and some certificate selector. * //from ww w . j a v a 2 s . c o m * @throws Exception */ @Test public void testBasicCmsSignature() 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, false, (String) null); byte[] cmsSignature = signedData.getEncoded(); LOG.debug("CMS signature: " + ASN1Dump.dumpAsString(new ASN1StreamParser(cmsSignature).readObject())); // verify signedData = new CMSSignedData(content, 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)); } LOG.debug("content type: " + signedData.getSignedContentTypeOID()); }