List of usage examples for org.bouncycastle.asn1.cms CMSObjectIdentifiers envelopedData
ASN1ObjectIdentifier envelopedData
To view the source code for org.bouncycastle.asn1.cms CMSObjectIdentifiers envelopedData.
Click Source Link
From source file:mitm.common.security.cms.CMSContentTypeClassifier.java
License:Open Source License
/** * Returns the CMS content type of the provided sequence. * //from w w w .ja v a2 s .c o m * See RFC3852 for content types * * @param sequenceParser * @return */ public static CMSContentType getContentType(ASN1SequenceParser sequenceParser) { CMSContentType contentType = CMSContentType.UNKNOWN; try { ContentInfoParser contentInfoParser = new ContentInfoParser(sequenceParser); DERObjectIdentifier derContentType = contentInfoParser.getContentType(); if (CMSObjectIdentifiers.data.equals(derContentType)) { contentType = CMSContentType.DATA; } else if (CMSObjectIdentifiers.signedData.equals(derContentType)) { contentType = CMSContentType.SIGNEDDATA; } else if (CMSObjectIdentifiers.envelopedData.equals(derContentType)) { contentType = CMSContentType.ENVELOPEDDATA; } else if (CMSObjectIdentifiers.signedAndEnvelopedData.equals(derContentType)) { contentType = CMSContentType.SIGNEDANDENVELOPEDDATA; } else if (CMSObjectIdentifiers.digestedData.equals(derContentType)) { contentType = CMSContentType.DIGESTEDDATA; } else if (CMSObjectIdentifiers.encryptedData.equals(derContentType)) { contentType = CMSContentType.ENCRYPTEDDATA; } else if (CMSObjectIdentifiers.compressedData.equals(derContentType)) { contentType = CMSContentType.COMPRESSEDDATA; } } catch (IOException e) { logger.error("IOException retrieving CMS content type", e); } return contentType; }
From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java
License:Open Source License
private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data, String type, String fileName, String path, String storepass, KeyStore store) throws KeystoreEditorException { OutputStream fos = null;//from w w w . j ava2s . co m try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) { if (StringUtils.isBlank(alias)) { throw new IllegalArgumentException("Alias cannot be null."); } Path storeFile = Paths.get(path); //check the two most common key/cert stores first (pkcs12 and jks) if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) { //priv key + cert chain KeyStore pkcs12Store = KeyStore.getInstance("PKCS12"); pkcs12Store.load(inputStream, storePassword.toCharArray()); Certificate[] chain = pkcs12Store.getCertificateChain(alias); Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray()); if (key != null) { store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain); fos = Files.newOutputStream(storeFile); store.store(fos, storepass.toCharArray()); } } else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) { //java keystore file KeyStore jks = KeyStore.getInstance("jks"); jks.load(inputStream, storePassword.toCharArray()); Enumeration<String> aliases = jks.aliases(); //we are going to store all entries from the jks regardless of the passed in alias while (aliases.hasMoreElements()) { String jksAlias = aliases.nextElement(); if (jks.isKeyEntry(jksAlias)) { Key key = jks.getKey(jksAlias, keyPassword.toCharArray()); Certificate[] certificateChain = jks.getCertificateChain(jksAlias); store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain); } else { Certificate certificate = jks.getCertificate(jksAlias); store.setCertificateEntry(jksAlias, certificate); } } fos = Files.newOutputStream(storeFile); store.store(fos, storepass.toCharArray()); //need to parse der separately from pem, der has the same mime type but is binary hence checking both } else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) { ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream); ASN1Primitive asn1Primitive = asn1InputStream.readObject(); X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded()); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC"); Certificate certificate = certificateFactory .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded())); X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject(); RDN cn = x500name.getRDNs(BCStyle.CN)[0]; String cnStr = IETFUtils.valueToString(cn.getFirst().getValue()); if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) { store.setCertificateEntry(cnStr, certificate); } store.setCertificateEntry(alias, certificate); fos = Files.newOutputStream(storeFile); store.store(fos, storepass.toCharArray()); //if it isn't one of the stores we support, it might be a key or cert by itself } else if (isPemParsable(type, fileName)) { //This is the catch all case for PEM, P7B, etc. with common file extensions if the mime type isn't read correctly in the browser Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); PEMParser pemParser = new PEMParser(reader); Object object; boolean setEntry = false; while ((object = pemParser.readObject()) != null) { if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) { PEMKeyPair pemKeyPair; if (object instanceof PEMEncryptedKeyPair) { PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object; JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder(); pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair( jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray())); } else { pemKeyPair = (PEMKeyPair) object; } KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair); PrivateKey privateKey = keyPair.getPrivate(); Certificate[] chain = store.getCertificateChain(alias); if (chain == null) { chain = buildCertChain(alias, store); } store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain); setEntry = true; } else if (object instanceof X509CertificateHolder) { X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object; CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC"); Certificate certificate = certificateFactory .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded())); X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate) .getSubject(); RDN cn = x500name.getRDNs(BCStyle.CN)[0]; String cnStr = IETFUtils.valueToString(cn.getFirst().getValue()); if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) { store.setCertificateEntry(cnStr, certificate); } store.setCertificateEntry(alias, certificate); setEntry = true; } else if (object instanceof ContentInfo) { ContentInfo contentInfo = (ContentInfo) object; if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) { CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo); OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure(); ASN1Set certificates = originatorInfo.getCertificates(); setEntry = importASN1CertificatesToStore(store, setEntry, certificates); } else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) { SignedData signedData = SignedData.getInstance(contentInfo.getContent()); ASN1Set certificates = signedData.getCertificates(); setEntry = importASN1CertificatesToStore(store, setEntry, certificates); } } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) { PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object; Certificate[] chain = store.getCertificateChain(alias); if (chain == null) { chain = buildCertChain(alias, store); } try { store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain); setEntry = true; } catch (KeyStoreException keyEx) { try { PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(), keyPassword.toCharArray()); store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(), chain); setEntry = true; } catch (GeneralSecurityException e) { LOGGER.info( "Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.", e); throw keyEx; } } } } if (setEntry) { fos = Files.newOutputStream(storeFile); store.store(fos, storepass.toCharArray()); } } } catch (Exception e) { LOGGER.info("Unable to add entry {} to store", alias, e); throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e); } finally { if (fos != null) { try { fos.close(); } catch (IOException ignore) { } } } init(); }
From source file:org.ejbca.core.protocol.scep.ScepRequestMessage.java
License:Open Source License
private void init() throws IOException { if (log.isTraceEnabled()) { log.trace(">init"); }/* w w w . j a v a 2 s. c o m*/ try { CMSSignedData csd = new CMSSignedData(scepmsg); SignerInformationStore infoStore = csd.getSignerInfos(); @SuppressWarnings("unchecked") Collection<SignerInformation> signers = infoStore.getSigners(); Iterator<SignerInformation> iter = signers.iterator(); if (iter.hasNext()) { SignerInformation si = (SignerInformation) iter.next(); preferredDigestAlg = si.getDigestAlgOID(); log.debug("Set " + preferredDigestAlg + " as preferred digest algorithm for SCEP"); } } catch (CMSException e) { // ignore, use default digest algo log.error("CMSException trying to get preferred digest algorithm: ", e); } // Parse and verify the integrity of the PKIOperation message PKCS#7 /* If this would have been done using the newer CMS it would have made me so much happier... */ ASN1InputStream seqAsn1InputStream = new ASN1InputStream(new ByteArrayInputStream(scepmsg)); ASN1Sequence seq = null; try { seq = (ASN1Sequence) seqAsn1InputStream.readObject(); } finally { seqAsn1InputStream.close(); } ContentInfo ci = ContentInfo.getInstance(seq); String ctoid = ci.getContentType().getId(); if (ctoid.equals(CMSObjectIdentifiers.signedData.getId())) { // This is SignedData so it is a pkcsCertReqSigned, pkcsGetCertInitialSigned, pkcsGetCertSigned, pkcsGetCRLSigned // (could also be pkcsRepSigned or certOnly, but we don't receive them on the server side // Try to find out what kind of message this is sd = SignedData.getInstance((ASN1Sequence) ci.getContent()); // Get self signed cert to identify the senders public key ASN1Set certs = sd.getCertificates(); if (certs.size() > 0) { // There should be only one... ASN1Encodable dercert = certs.getObjectAt(0); if (dercert != null) { // Requester's self-signed certificate is requestKeyInfo ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(dercert); if (bOut.size() > 0) { requestKeyInfo = bOut.toByteArray(); //Create Certificate used for debugging try { signercert = CertTools.getCertfromByteArray(requestKeyInfo); if (log.isDebugEnabled()) { log.debug("requestKeyInfo is SubjectDN: " + CertTools.getSubjectDN(signercert) + ", Serial=" + CertTools.getSerialNumberAsString(signercert) + "; IssuerDN: " + CertTools.getIssuerDN(signercert).toString()); } } catch (CertificateException e) { log.error("Error parsing requestKeyInfo : ", e); } } } } Enumeration<?> sis = sd.getSignerInfos().getObjects(); if (sis.hasMoreElements()) { SignerInfo si = SignerInfo.getInstance((ASN1Sequence) sis.nextElement()); Enumeration<?> attr = si.getAuthenticatedAttributes().getObjects(); while (attr.hasMoreElements()) { Attribute a = Attribute.getInstance((ASN1Sequence) attr.nextElement()); if (log.isDebugEnabled()) { log.debug("Found attribute: " + a.getAttrType().getId()); } if (a.getAttrType().getId().equals(id_senderNonce)) { Enumeration<?> values = a.getAttrValues().getObjects(); ASN1OctetString str = ASN1OctetString.getInstance(values.nextElement()); senderNonce = new String(Base64.encode(str.getOctets(), false)); if (log.isDebugEnabled()) { log.debug("senderNonce = " + senderNonce); } } if (a.getAttrType().getId().equals(id_transId)) { Enumeration<?> values = a.getAttrValues().getObjects(); DERPrintableString str = DERPrintableString.getInstance(values.nextElement()); transactionId = str.getString(); if (log.isDebugEnabled()) { log.debug("transactionId = " + transactionId); } } if (a.getAttrType().getId().equals(id_messageType)) { Enumeration<?> values = a.getAttrValues().getObjects(); DERPrintableString str = DERPrintableString.getInstance(values.nextElement()); messageType = Integer.parseInt(str.getString()); if (log.isDebugEnabled()) { log.debug("messagetype = " + messageType); } } } } // If this is a PKCSReq if ((messageType == ScepRequestMessage.SCEP_TYPE_PKCSREQ) || (messageType == ScepRequestMessage.SCEP_TYPE_GETCRL) || (messageType == ScepRequestMessage.SCEP_TYPE_GETCERTINITIAL)) { // Extract the contents, which is an encrypted PKCS10 if messageType == 19 // , and an encrypted issuer and subject if messageType == 20 (not extracted) // and an encrypted IssuerAndSerialNumber if messageType == 22 ci = sd.getEncapContentInfo(); ctoid = ci.getContentType().getId(); if (ctoid.equals(CMSObjectIdentifiers.data.getId())) { ASN1OctetString content = (ASN1OctetString) ci.getContent(); if (log.isDebugEnabled()) { log.debug("envelopedData is " + content.getOctets().length + " bytes."); } ASN1InputStream seq1Asn1InputStream = new ASN1InputStream( new ByteArrayInputStream(content.getOctets())); ASN1Sequence seq1 = null; try { seq1 = (ASN1Sequence) seq1Asn1InputStream.readObject(); } finally { seq1Asn1InputStream.close(); } envEncData = ContentInfo.getInstance(seq1); ctoid = envEncData.getContentType().getId(); if (ctoid.equals(CMSObjectIdentifiers.envelopedData.getId())) { envData = EnvelopedData.getInstance((ASN1Sequence) envEncData.getContent()); ASN1Set recipientInfos = envData.getRecipientInfos(); Enumeration<?> e = recipientInfos.getObjects(); while (e.hasMoreElements()) { RecipientInfo ri = RecipientInfo.getInstance(e.nextElement()); KeyTransRecipientInfo recipientInfo = KeyTransRecipientInfo.getInstance(ri.getInfo()); RecipientIdentifier rid = recipientInfo.getRecipientIdentifier(); IssuerAndSerialNumber iasn = IssuerAndSerialNumber.getInstance(rid.getId()); issuerDN = iasn.getName().toString(); serialNo = iasn.getSerialNumber().getValue(); if (log.isDebugEnabled()) { log.debug("IssuerDN: " + issuerDN); log.debug("SerialNumber: " + iasn.getSerialNumber().getValue().toString(16)); } } } else { errorText = "EncapsulatedContentInfo does not contain PKCS7 envelopedData: "; log.error(errorText + ctoid); error = 2; } } else { errorText = "EncapsulatedContentInfo is not of type 'data': "; log.error(errorText + ctoid); error = 3; } } else { errorText = "This is not a certification request!"; log.error(errorText); error = 4; } } else { errorText = "PKCSReq does not contain 'signedData': "; log.error(errorText + ctoid); error = 1; } log.trace("<init"); }
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()); }// w w w .ja va 2 s . c om 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.xipki.pki.scep.message.PkiMessage.java
License:Open Source License
public ContentInfo encode(final ContentSigner signer, final X509Certificate signerCert, final X509Certificate[] cmsCertSet, final X509Certificate recipientCert, final ASN1ObjectIdentifier encAlgId) throws MessageEncodingException { ParamUtil.requireNonNull("signer", signer); ParamUtil.requireNonNull("signerCert", signerCert); ParamUtil.requireNonNull("recipientCert", recipientCert); ParamUtil.requireNonNull("encAlgId", encAlgId); CMSTypedData content;/*w w w . j a v a 2s . c o m*/ if (messageData == null) { content = new CMSAbsentContent(); } else { CMSEnvelopedData envelopedData = encrypt(recipientCert, encAlgId); byte[] encoded; try { encoded = envelopedData.getEncoded(); } catch (IOException ex) { throw new MessageEncodingException(ex); } content = new CMSProcessableByteArray(CMSObjectIdentifiers.envelopedData, encoded); } try { CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); // signerInfo JcaSignerInfoGeneratorBuilder signerInfoBuilder = new JcaSignerInfoGeneratorBuilder( new BcDigestCalculatorProvider()); signerInfoBuilder .setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(getSignedAttributes())); AttributeTable attrTable = getUnsignedAttributes(); if (attrTable != null) { signerInfoBuilder.setUnsignedAttributeGenerator(new SimpleAttributeTableGenerator(attrTable)); } // certificateSet ScepUtil.addCmsCertSet(generator, cmsCertSet); SignerInfoGenerator signerInfo; try { signerInfo = signerInfoBuilder.build(signer, signerCert); } catch (Exception ex) { throw new MessageEncodingException(ex); } generator.addSignerInfoGenerator(signerInfo); CMSSignedData signedData = generator.generate(content, true); return signedData.toASN1Structure(); } catch (CMSException ex) { throw new MessageEncodingException(ex); } catch (Exception ex) { throw new MessageEncodingException(ex); } }