List of usage examples for org.bouncycastle.cms CMSAbsentContent CMSAbsentContent
public CMSAbsentContent()
From source file:no.difi.oxalis.as2.util.SMimeBC.java
License:EUPL
public static byte[] createSignature(byte[] digest, SMimeDigestMethod digestMethod, PrivateKey privateKey, X509Certificate certificate) throws OxalisSecurityException { try {// w w w. j a va2 s . c om ASN1EncodableVector signedAttributes = new ASN1EncodableVector(); signedAttributes.add(new Attribute(CMSAttributes.contentType, new DERSet(digestMethod.getOid()))); signedAttributes .add(new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(digest)))); signedAttributes.add(new Attribute(CMSAttributes.signingTime, new DERSet(new DERUTCTime(new Date())))); AttributeTable signedAttributesTable = new AttributeTable(signedAttributes); signedAttributesTable.toASN1EncodableVector(); DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator( signedAttributesTable); /* Build the SignerInfo generator builder, that will build the generator... that will generate the SignerInformation... */ SignerInfoGeneratorBuilder signerInfoBuilder = new SignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME) .build()); signerInfoBuilder.setSignedAttributeGenerator(signedAttributeGenerator); CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); JcaContentSignerBuilder contentSigner = new JcaContentSignerBuilder(digestMethod.getMethod()) .setProvider(BouncyCastleProvider.PROVIDER_NAME); generator.addSignerInfoGenerator(signerInfoBuilder.build(contentSigner.build(privateKey), new X509CertificateHolder(certificate.getEncoded()))); generator.addCertificates(new JcaCertStore(Collections.singletonList(certificate))); return generator.generate(new CMSAbsentContent()).getEncoded(); } catch (CMSException | IOException | CertificateEncodingException | OperatorCreationException e) { throw new OxalisSecurityException(e.getMessage(), e); } }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSigner.java
License:Open Source License
private byte[] doSign(byte[] content, byte[] previewSignature) { try {//from w ww . j a v a 2 s . co m Security.addProvider(new BouncyCastleProvider()); // Completa os certificados ausentes da cadeia, se houver if (this.certificate == null && this.certificateChain != null && this.certificateChain.length > 0) { this.certificate = (X509Certificate) this.certificateChain[0]; } this.certificateChain = CAManager.getInstance().getCertificateChainArray(this.certificate); if (this.certificateChain.length < 3) { throw new SignerException( cadesMessagesBundle.getString("error.no.ca", this.certificate.getIssuerDN())); } Certificate[] certStore = new Certificate[] {}; CMSSignedData cmsPreviewSignedData = null; // Caso seja co-assinatura ou contra-assinatura // Importar todos os certificados da assinatura anterior if (previewSignature != null && previewSignature.length > 0) { cmsPreviewSignedData = new CMSSignedData(new CMSAbsentContent(), previewSignature); Collection<X509Certificate> previewCerts = this.getSignersCertificates(cmsPreviewSignedData); //previewCerts.add(this.certificate); certStore = previewCerts.toArray(new Certificate[] {}); } setCertificateManager(new CertificateManager(this.certificate)); // Recupera a lista de algoritmos da politica e o tamanho minimo da // chave List<AlgAndLength> listOfAlgAndLength = new ArrayList<AlgAndLength>(); for (AlgAndLength algLength : signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy() .getCommonRules().getAlgorithmConstraintSet().getSignerAlgorithmConstraints() .getAlgAndLengths()) { listOfAlgAndLength.add(algLength); } AlgAndLength algAndLength = null; // caso o algoritmo tenha sido informado como parmetro ir // verificar se o mesmo permitido pela politica if (this.pkcs1.getAlgorithm() != null) { String varSetedAlgorithmOID = AlgorithmNames.getOIDByAlgorithmName(this.pkcs1.getAlgorithm()); for (AlgAndLength algLength : listOfAlgAndLength) { if (algLength.getAlgID().getValue().equalsIgnoreCase(varSetedAlgorithmOID)) { algAndLength = algLength; SignerAlgorithmEnum varSignerAlgorithmEnum = SignerAlgorithmEnum .valueOf(this.pkcs1.getAlgorithm()); String varOIDAlgorithmHash = varSignerAlgorithmEnum.getOIDAlgorithmHash(); ObjectIdentifier varObjectIdentifier = signaturePolicy.getSignPolicyHashAlg() .getAlgorithm(); varObjectIdentifier.setValue(varOIDAlgorithmHash); AlgorithmIdentifier varAlgorithmIdentifier = signaturePolicy.getSignPolicyHashAlg(); varAlgorithmIdentifier.setAlgorithm(varObjectIdentifier); signaturePolicy.setSignPolicyHashAlg(varAlgorithmIdentifier); } } } else { algAndLength = listOfAlgAndLength.get(1); this.pkcs1.setAlgorithm(AlgorithmNames.getAlgorithmNameByOID(algAndLength.getAlgID().getValue())); SignerAlgorithmEnum varSignerAlgorithmEnum = SignerAlgorithmEnum.valueOf(this.pkcs1.getAlgorithm()); String varOIDAlgorithmHash = varSignerAlgorithmEnum.getOIDAlgorithmHash(); ObjectIdentifier varObjectIdentifier = signaturePolicy.getSignPolicyHashAlg().getAlgorithm(); varObjectIdentifier.setValue(varOIDAlgorithmHash); AlgorithmIdentifier varAlgorithmIdentifier = signaturePolicy.getSignPolicyHashAlg(); varAlgorithmIdentifier.setAlgorithm(varObjectIdentifier); signaturePolicy.setSignPolicyHashAlg(varAlgorithmIdentifier); } if (algAndLength == null) { throw new SignerException(cadesMessagesBundle.getString("error.no.algorithm.policy")); } logger.info(cadesMessagesBundle.getString("info.algorithm.id", algAndLength.getAlgID().getValue())); logger.info(cadesMessagesBundle.getString("info.algorithm.name", AlgorithmNames.getAlgorithmNameByOID(algAndLength.getAlgID().getValue()))); logger.info(cadesMessagesBundle.getString("info.min.key.length", algAndLength.getMinKeyLength())); // Recupera o tamanho minimo da chave para validacao logger.info(cadesMessagesBundle.getString("info.validating.key.length")); int keyLegth = ((RSAKey) certificate.getPublicKey()).getModulus().bitLength(); if (keyLegth < algAndLength.getMinKeyLength()) { throw new SignerException(cadesMessagesBundle.getString("error.min.key.length", algAndLength.getMinKeyLength().toString(), keyLegth)); } AttributeFactory attributeFactory = AttributeFactory.getInstance(); // Consulta e adiciona os atributos assinados ASN1EncodableVector signedAttributes = new ASN1EncodableVector(); logger.info(cadesMessagesBundle.getString("info.signed.attribute")); if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules() .getSignerAndVeriferRules().getSignerRules().getMandatedSignedAttr() .getObjectIdentifiers() != null) { for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo() .getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules() .getMandatedSignedAttr().getObjectIdentifiers()) { SignedOrUnsignedAttribute signedOrUnsignedAttribute = attributeFactory .factory(objectIdentifier.getValue()); signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), certificateChain, content, signaturePolicy, this.hash); signedAttributes.add(signedOrUnsignedAttribute.getValue()); } } // Monta a tabela de atributos assinados AttributeTable signedAttributesTable = new AttributeTable(signedAttributes); // Create the table table generator that will added to the Signer // builder CMSAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator( signedAttributesTable); // Recupera o(s) certificado(s) de confianca para validacao Collection<X509Certificate> trustedCAs = new HashSet<X509Certificate>(); Collection<CertificateTrustPoint> ctp = signaturePolicy.getSignPolicyInfo() .getSignatureValidationPolicy().getCommonRules().getSigningCertTrustCondition() .getSignerTrustTrees().getCertificateTrustPoints(); for (CertificateTrustPoint certificateTrustPoint : ctp) { logger.info(cadesMessagesBundle.getString("info.trust.point", certificateTrustPoint.getTrustpoint().getSubjectDN().toString())); trustedCAs.add(certificateTrustPoint.getTrustpoint()); } // Efetua a validacao das cadeias do certificado baseado na politica Collection<X509Certificate> certificateChainTrusted = new HashSet<X509Certificate>(); for (Certificate certCA : certificateChain) { certificateChainTrusted.add((X509Certificate) certCA); } X509Certificate rootOfCertificate = null; for (X509Certificate tcac : certificateChainTrusted) { logger.info(tcac.getIssuerDN().toString()); if (CAManager.getInstance().isRootCA(tcac)) { rootOfCertificate = tcac; } } if (trustedCAs.contains(rootOfCertificate)) { logger.info(cadesMessagesBundle.getString("info.trust.in.point", rootOfCertificate.getSubjectDN())); } else { // No encontrou na poltica, verificar nas cadeias do // componente chain-icp-brasil provavelmente certificado de // homologao. logger.warn(cadesMessagesBundle.getString("info.trust.poin.homolog")); CAManager.getInstance().validateRootCAs(certificateChainTrusted, certificate); } // validade da politica logger.info(cadesMessagesBundle.getString("info.policy.valid.period")); PolicyValidator pv = new PolicyValidator(this.signaturePolicy, this.policyName); pv.validate(); // Realiza a assinatura do conteudo CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addCertificates(this.generatedCertStore(certStore)); String algorithmOID = algAndLength.getAlgID().getValue(); logger.info(cadesMessagesBundle.getString("info.algorithm.id", algorithmOID)); SignerInfoGenerator signerInfoGenerator = new JcaSimpleSignerInfoGeneratorBuilder() .setSignedAttributeGenerator(signedAttributeGenerator).setUnsignedAttributeGenerator(null) .build(AlgorithmNames.getAlgorithmNameByOID(algorithmOID), this.pkcs1.getPrivateKey(), this.certificate); gen.addSignerInfoGenerator(signerInfoGenerator); CMSTypedData cmsTypedData; // para assinatura do hash, content nulo if (content == null) { cmsTypedData = new CMSAbsentContent(); } else { cmsTypedData = new CMSProcessableByteArray(content); } // Efetua a assinatura digital do contedo CMSSignedData cmsSignedData = gen.generate(cmsTypedData, this.attached); setAttached(false); // Consulta e adiciona os atributos no assinados// ASN1EncodableVector unsignedAttributes = new ASN1EncodableVector(); logger.info(cadesMessagesBundle.getString("info.unsigned.attribute")); Collection<SignerInformation> vNewSigners = cmsSignedData.getSignerInfos().getSigners(); Iterator<SignerInformation> it = vNewSigners.iterator(); SignerInformation oSi = it.next(); if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules() .getSignerAndVeriferRules().getSignerRules().getMandatedUnsignedAttr() .getObjectIdentifiers() != null) { for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo() .getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules() .getMandatedUnsignedAttr().getObjectIdentifiers()) { SignedOrUnsignedAttribute signedOrUnsignedAttribute = attributeFactory .factory(objectIdentifier.getValue()); if (signedOrUnsignedAttribute.getOID() .equalsIgnoreCase(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId())) { signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), this.certificateChainTimeStamp, oSi.getSignature(), signaturePolicy, this.hash); } if (signedOrUnsignedAttribute.getOID().equalsIgnoreCase("1.2.840.113549.1.9.16.2.25")) //EscTimeStamp { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); outputStream.write(oSi.getSignature()); AttributeTable varUnsignedAttributes = oSi.getUnsignedAttributes(); Attribute varAttribute = varUnsignedAttributes.get(new ASN1ObjectIdentifier( PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId())); outputStream.write(varAttribute.getAttrType().getEncoded()); outputStream.write(varAttribute.getAttrValues().getEncoded()); varAttribute = varUnsignedAttributes.get( new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_certificateRefs.getId())); outputStream.write(varAttribute.getAttrType().getEncoded()); outputStream.write(varAttribute.getAttrValues().getEncoded()); varAttribute = varUnsignedAttributes.get( new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_revocationRefs.getId())); outputStream.write(varAttribute.getAttrType().getEncoded()); outputStream.write(varAttribute.getAttrValues().getEncoded()); escTimeStampContent = outputStream.toByteArray(); signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), this.certificateChainTimeStamp, escTimeStampContent, signaturePolicy, this.hash); } else { signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), certificateChain, oSi.getSignature(), signaturePolicy, this.hash); } unsignedAttributes.add(signedOrUnsignedAttribute.getValue()); AttributeTable unsignedAttributesTable = new AttributeTable(unsignedAttributes); vNewSigners.remove(oSi); oSi = SignerInformation.replaceUnsignedAttributes(oSi, unsignedAttributesTable); vNewSigners.add(oSi); } } //TODO Estudar este mtodo de contra-assinatura posteriormente if (previewSignature != null && previewSignature.length > 0) { vNewSigners.addAll(cmsPreviewSignedData.getSignerInfos().getSigners()); } SignerInformationStore oNewSignerInformationStore = new SignerInformationStore(vNewSigners); CMSSignedData oSignedData = cmsSignedData; cmsSignedData = CMSSignedData.replaceSigners(oSignedData, oNewSignerInformationStore); byte[] result = cmsSignedData.getEncoded(); logger.info(cadesMessagesBundle.getString("info.signature.ok")); return result; } catch (CMSException | IOException | OperatorCreationException | CertificateEncodingException ex) { throw new SignerException(ex); } }
From source file:org.ejbca.core.protocol.scep.ScepResponseMessage.java
License:Open Source License
@Override public boolean create() throws CertificateEncodingException, CRLException { boolean ret = false; try {/*from w w w . ja va2 s . c om*/ if (status.equals(ResponseStatus.SUCCESS)) { log.debug("Creating a STATUS_OK message."); } else { if (status.equals(ResponseStatus.FAILURE)) { log.debug("Creating a STATUS_FAILED message (or returning false)."); if (failInfo.equals(FailInfo.WRONG_AUTHORITY)) { return false; } if (failInfo.equals(FailInfo.INCORRECT_DATA)) { return false; } } else { log.debug("Creating a STATUS_PENDING message."); } } CMSTypedData msg; // Create encrypted response if this is success and NOT a CRL response message if (status.equals(ResponseStatus.SUCCESS)) { CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator(); // Add the issued certificate to the signed portion of the CMS (as signer, degenerate case) List<X509Certificate> certList = new ArrayList<X509Certificate>(); if (cert != null) { log.debug("Adding certificates to response message"); certList.add((X509Certificate) cert); // Add the CA cert, it's optional but Cisco VPN client complains if it isn't there if (includeCACert) { if (caCert != null) { // If we have an explicit CAcertificate log.debug("Including explicitly set CA certificate in SCEP response."); certList.add((X509Certificate) caCert); } else { // If we don't have an explicit caCert, we think that the signCert is the CA cert // If we have an explicit caCert, the signCert is probably the RA certificate, and we don't include that one log.debug("Including message signer certificate in SCEP response."); certList.add((X509Certificate) signCertChain.iterator().next()); } } } // Create the signed CMS message to be contained inside the envelope // this message does not contain any message, and no signerInfo CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addCertificates(new CollectionStore(CertTools.convertToX509CertificateHolder(certList))); if (crl != null) { gen.addCRL(new JcaX509CRLHolder((X509CRL) crl)); } CMSSignedData s = gen.generate(new CMSAbsentContent(), false); // Envelope the CMS message if (recipientKeyInfo != null) { try { X509Certificate rec = (X509Certificate) CertTools.getCertfromByteArray(recipientKeyInfo); log.debug("Added recipient information - issuer: '" + CertTools.getIssuerDN(rec) + "', serno: '" + CertTools.getSerialNumberAsString(rec)); edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(rec) .setProvider(BouncyCastleProvider.PROVIDER_NAME)); } catch (CertificateParsingException e) { throw new IllegalArgumentException("Can not decode recipients self signed certificate!", e); } } else { edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator((X509Certificate) cert) .setProvider(BouncyCastleProvider.PROVIDER_NAME)); } try { JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder( SMIMECapability.dES_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME); CMSEnvelopedData ed = edGen.generate(new CMSProcessableByteArray(s.getEncoded()), jceCMSContentEncryptorBuilder.build()); if (log.isDebugEnabled()) { log.debug("Enveloped data is " + ed.getEncoded().length + " bytes long"); } msg = new CMSProcessableByteArray(ed.getEncoded()); } catch (IOException e) { throw new IllegalStateException("Unexpected IOException caught", e); } } else { // Create an empty message here //msg = new CMSProcessableByteArray("PrimeKey".getBytes()); msg = new CMSProcessableByteArray(new byte[0]); } // Create the outermost signed data CMSSignedDataGenerator gen1 = new CMSSignedDataGenerator(); // add authenticated attributes...status, transactionId, sender- and recipientNonce and more... Hashtable<ASN1ObjectIdentifier, Attribute> attributes = new Hashtable<ASN1ObjectIdentifier, Attribute>(); ASN1ObjectIdentifier oid; Attribute attr; DERSet value; // Message type (certrep) oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_messageType); value = new DERSet(new DERPrintableString("3")); attr = new Attribute(oid, value); attributes.put(attr.getAttrType(), attr); // TransactionId if (transactionId != null) { oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_transId); log.debug("Added transactionId: " + transactionId); value = new DERSet(new DERPrintableString(transactionId)); attr = new Attribute(oid, value); attributes.put(attr.getAttrType(), attr); } // status oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_pkiStatus); value = new DERSet(new DERPrintableString(status.getStringValue())); attr = new Attribute(oid, value); attributes.put(attr.getAttrType(), attr); if (status.equals(ResponseStatus.FAILURE)) { oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_failInfo); log.debug("Added failInfo: " + failInfo.getValue()); value = new DERSet(new DERPrintableString(failInfo.getValue())); attr = new Attribute(oid, value); attributes.put(attr.getAttrType(), attr); } // senderNonce if (senderNonce != null) { oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_senderNonce); log.debug("Added senderNonce: " + senderNonce); value = new DERSet(new DEROctetString(Base64.decode(senderNonce.getBytes()))); attr = new Attribute(oid, value); attributes.put(attr.getAttrType(), attr); } // recipientNonce if (recipientNonce != null) { oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_recipientNonce); log.debug("Added recipientNonce: " + recipientNonce); value = new DERSet(new DEROctetString(Base64.decode(recipientNonce.getBytes()))); attr = new Attribute(oid, value); attributes.put(attr.getAttrType(), attr); } // Add our signer info and sign the message Certificate cacert = signCertChain.iterator().next(); log.debug("Signing SCEP message with cert: " + CertTools.getSubjectDN(cacert)); String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromDigestAndKey(digestAlg, signKey.getAlgorithm()); try { ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithmName) .setProvider(provider).build(signKey); JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME); JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder( calculatorProviderBuilder.build()); builder.setSignedAttributeGenerator( new DefaultSignedAttributeTableGenerator(new AttributeTable(attributes))); gen1.addSignerInfoGenerator(builder.build(contentSigner, (X509Certificate) cacert)); } catch (OperatorCreationException e) { throw new IllegalStateException("BouncyCastle failed in creating signature provider.", e); } // The un-encoded response message itself final CMSSignedData signedData = gen1.generate(msg, true); try { responseMessage = signedData.getEncoded(); } catch (IOException e) { throw new IllegalStateException("Unexpected IOException caught.", e); } if (responseMessage != null) { ret = true; } } catch (CMSException e) { log.error("Error creating CMS message: ", e); } return ret; }
From source file:org.jscep.message.PkiMessageEncoder.java
License:Open Source License
private CMSTypedData getContent(final PkiMessage<?> message) throws MessageEncodingException { CMSTypedData signable;/* w ww.j a va2s . c o m*/ boolean hasMessageData = true; if (message instanceof CertRep) { CertRep response = (CertRep) message; if (response.getPkiStatus() != PkiStatus.SUCCESS) { hasMessageData = false; } } if (hasMessageData) { try { CMSEnvelopedData ed = encodeMessage(message); signable = new CMSProcessableByteArray(ed.getEncoded()); } catch (IOException e) { throw new MessageEncodingException(e); } } else { signable = new CMSAbsentContent(); } return signable; }
From source file:org.jscep.server.ScepServlet.java
License:Open Source License
private CMSSignedData getMessageData(final List<X509Certificate> certs) throws IOException, CMSException, GeneralSecurityException { CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); JcaCertStore store;// ww w . j a v a 2 s .c o m try { store = new JcaCertStore(certs); } catch (CertificateEncodingException e) { IOException ioe = new IOException(); ioe.initCause(e); throw ioe; } generator.addCertificates(store); return generator.generate(new CMSAbsentContent()); }
From source file:org.jscep.server.ScepServlet.java
License:Open Source License
private CMSSignedData getMessageData(final X509CRL crl) throws IOException, CMSException, GeneralSecurityException { CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); JcaCRLStore store;/*from ww w. j a va 2 s . c o m*/ if (crl == null) { store = new JcaCRLStore(Collections.emptyList()); } else { store = new JcaCRLStore(Collections.singleton(crl)); } generator.addCRLs(store); return generator.generate(new CMSAbsentContent()); }
From source file:org.jscep.server.ScepServlet.java
License:Open Source License
private void doGetNextCaCert(final HttpServletRequest req, final HttpServletResponse res) throws Exception { res.setHeader("Content-Type", "application/x-x509-next-ca-cert"); List<X509Certificate> certs = getNextCaCertificate(req.getParameter(MSG_PARAM)); if (certs.size() == 0) { res.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, "GetNextCACert Not Supported"); } else {// w w w .java2 s. c o m CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); JcaCertStore store; try { store = new JcaCertStore(certs); } catch (CertificateEncodingException e) { IOException ioe = new IOException(); ioe.initCause(e); throw ioe; } generator.addCertificates(store); DigestCalculatorProvider digestProvider = new JcaDigestCalculatorProviderBuilder().build(); SignerInfoGeneratorBuilder infoGenBuilder = new SignerInfoGeneratorBuilder(digestProvider); X509CertificateHolder certHolder = new X509CertificateHolder(getRecipient().getEncoded()); ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").build(getRecipientKey()); SignerInfoGenerator infoGen = infoGenBuilder.build(contentSigner, certHolder); generator.addSignerInfoGenerator(infoGen); CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent()); byte[] bytes = degenerateSd.getEncoded(); res.getOutputStream().write(bytes); res.getOutputStream().close(); } }
From source file:org.jscep.server.ScepServlet.java
License:Open Source License
private void doGetCaCert(final HttpServletRequest req, final HttpServletResponse res) throws Exception { final List<X509Certificate> certs = doGetCaCertificate(req.getParameter(MSG_PARAM)); final byte[] bytes; if (certs.size() == 0) { res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "GetCaCert failed to obtain CA from store"); bytes = new byte[0]; } else if (certs.size() == 1) { res.setHeader("Content-Type", "application/x-x509-ca-cert"); bytes = certs.get(0).getEncoded(); } else {//from ww w. j a va 2 s . co m res.setHeader("Content-Type", "application/x-x509-ca-ra-cert"); CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); JcaCertStore store; try { store = new JcaCertStore(certs); } catch (CertificateEncodingException e) { IOException ioe = new IOException(); ioe.initCause(e); throw ioe; } generator.addCertificates(store); CMSSignedData degenerateSd = generator.generate(new CMSAbsentContent()); bytes = degenerateSd.getEncoded(); } res.getOutputStream().write(bytes); res.getOutputStream().close(); }
From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java
License:Open Source License
private CMSSignedData getMessageData(final List<X509Certificate> certs) throws KeystoreException { CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); JcaCertStore store;/*from w w w. j a v a 2 s. c o m*/ try { store = new JcaCertStore(certs); generator.addCertificates(store); return generator.generate(new CMSAbsentContent()); } catch (CertificateEncodingException e) { String errorMsg = "Certificate encoding issue occurred when generating getMessageData"; throw new KeystoreException(errorMsg, e); } catch (CMSException e) { String errorMsg = "Message decoding issue occurred when generating getMessageData"; 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 . j a v a2 s. co 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); } }