List of usage examples for org.bouncycastle.cms RecipientInformationStore getRecipients
public Collection<RecipientInformation> getRecipients()
From source file:chapter9.KeyTransEnvelopedDataExample2.java
/** * * @param args/*from w w w . ja v a2 s . c om*/ * @throws Exception */ public static void main(String[] args) throws Exception { KeyStore credentials = Utils.createCredentials(); PrivateKey key = (PrivateKey) credentials.getKey(Utils.END_ENTITY_ALIAS, Utils.KEY_PASSWD); Certificate[] chain = credentials.getCertificateChain(Utils.END_ENTITY_ALIAS); X509Certificate cert = (X509Certificate) chain[0]; //1.- Set up the generator CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator(); gen.addKeyTransRecipient(cert); //2.- Create the enveloped-data object CMSProcessable data = new CMSProcessableByteArray("Hello World!!".getBytes()); CMSEnvelopedData enveloped = gen.generate(data, CMSEnvelopedDataGenerator.AES128_CBC, CryptoDefs.Provider.BC.getName()); //3.- Re-create enveloped = new CMSEnvelopedData(enveloped.getEncoded()); //4.- Look for our recipient identifier // Set up to iterate through the recipients RecipientInformationStore recipients = enveloped.getRecipientInfos(); CertStore certStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(Collections.singleton(cert)), CryptoDefs.Provider.BC.getName()); RecipientInformation recipient = null; for (Object o : recipients.getRecipients()) { recipient = (RecipientInformation) o; if (recipient instanceof KeyTransRecipientInformation) { //5.- Match the recipient ID Collection<?> matches = certStore.getCertificates(recipient.getRID()); if (matches.isEmpty() == false) { //6.- Decrypt the data byte[] recData = recipient.getContent(key, CryptoDefs.Provider.BC.getName()); //7.- Compare recovered data to the original data if (Arrays.equals((byte[]) data.getContent(), recData) == true) { System.out.println("\t data recovery succeeded!!"); break; } else { System.out.println("\t data recovery failed!!"); break; } } } } if (recipient == null) { System.out.println("\t Could not find a matching recipient!!"); } }
From source file:com.cordys.coe.ac.emailio.util.smime.SMIMEUtil.java
License:Apache License
/** * This method will decrypt the source message and return the decrypted version of the mail. * * @param mmSource The message to decrypt. * @param scConfig The S/MIME configuration details. * * @return The decrypted message./* w w w.ja v a 2s.co m*/ * * @throws EmailIOException In case of any exceptions. */ public static MimeMessage decryptMessage(MimeMessage mmSource, ISMIMEConfiguration scConfig) throws EmailIOException { MimeMessage mmReturn = null; // First we create the wrapper around the encrypted message try { SMIMEEnveloped seSMIME = new SMIMEEnveloped(mmSource); // Now get all recipients for this mail and try to find the matching certificate with // the private key. RecipientInformationStore recipients = seSMIME.getRecipientInfos(); ICertificateInfo ciInfo = null; RecipientInformation riInfo = null; Collection<?> cRecipients = recipients.getRecipients(); for (Iterator<?> iRecipients = cRecipients.iterator(); iRecipients.hasNext();) { riInfo = (RecipientInformation) iRecipients.next(); // Figure out if we have a key for this recipient ID. ciInfo = scConfig.getCertificateInfo(riInfo.getRID()); if (ciInfo != null) { if (LOG.isDebugEnabled()) { LOG.debug("Found certificate info for RID " + riInfo.getRID()); } break; } } // Check if we found all information. if (ciInfo == null) { throw new EmailIOException( EmailIOExceptionMessages.EIOE_COULD_NOT_FIND_ANY_CERTIFICATE_INFORMATION_FOR_ANY_OF_THE_RECIPIENTS); } if (riInfo == null) { throw new EmailIOException( EmailIOExceptionMessages.EIOE_COULD_NOT_DECRYPT_MESSAGE_BECAUSE_NO_RECIPIENT_INFORMATION_WAS_FOUND); } // We have all the necessary information, so now we can really decrypt the message. Key kPrivate = ciInfo.getKey(); if (kPrivate == null) { throw new EmailIOException( EmailIOExceptionMessages.EIOE_COULD_NOT_FIND_A_PRIVATE_KEY_FOR_RECIPIENT_0, riInfo.getRID().getSubjectAsString()); } // Do the actual decrypting of the content. MimeBodyPart res = org.bouncycastle.mail.smime.SMIMEUtil .toMimeBodyPart(riInfo.getContent(kPrivate, "BC")); // Now create a decrypted version of the mail. mmReturn = new MimeMessage(mmSource); MimeMultipart mmTemp = new MimeMultipart(); mmTemp.addBodyPart(res); mmReturn.setContent(mmTemp); mmReturn.saveChanges(); if (LOG.isDebugEnabled()) { LOG.debug( "The message was now decrypted. Returning mail:\n" + MailMessageUtil.rawMessage(mmReturn)); } } catch (EmailIOException eioe) { throw eioe; } catch (Exception e) { throw new EmailIOException(e, EmailIOExceptionMessages.EIOE_ERROR_DECRYPTING_EMAIL_MESSAGE); } return mmReturn; }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/** * Decrypts the data of a message with all given certificates etc * * @param info MessageInfo, the encryption algorith will be stored in the * encryption type of this info//from ww w . j av a 2s.c o m * @param rawMessageData encrypted data, will be decrypted * @param contentType contentType of the data * @param privateKey receivers private key * @param certificate receivers certificate */ public byte[] decryptData(AS2Message message, byte[] data, String contentType, PrivateKey privateKeyReceiver, X509Certificate certificateReceiver, String receiverCryptAlias) throws Exception { AS2MessageInfo info = (AS2MessageInfo) message.getAS2Info(); MimeBodyPart encryptedBody = new MimeBodyPart(); encryptedBody.setHeader("content-type", contentType); encryptedBody.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType))); JceKeyTransRecipientId recipientId = new JceKeyTransRecipientId(certificateReceiver); SMIMEEnveloped enveloped = new SMIMEEnveloped(encryptedBody); BCCryptoHelper helper = new BCCryptoHelper(); String algorithm = helper.convertOIDToAlgorithmName(enveloped.getEncryptionAlgOID()); if (algorithm.equals(BCCryptoHelper.ALGORITHM_3DES)) { info.setEncryptionType(AS2Message.ENCRYPTION_3DES); } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_DES)) { info.setEncryptionType(AS2Message.ENCRYPTION_DES); } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_RC2)) { info.setEncryptionType(AS2Message.ENCRYPTION_RC2_UNKNOWN); } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_128)) { info.setEncryptionType(AS2Message.ENCRYPTION_AES_128); } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_192)) { info.setEncryptionType(AS2Message.ENCRYPTION_AES_192); } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_256)) { info.setEncryptionType(AS2Message.ENCRYPTION_AES_256); } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_RC4)) { info.setEncryptionType(AS2Message.ENCRYPTION_RC4_UNKNOWN); } else { info.setEncryptionType(AS2Message.ENCRYPTION_UNKNOWN_ALGORITHM); } RecipientInformationStore recipients = enveloped.getRecipientInfos(); enveloped = null; encryptedBody = null; RecipientInformation recipient = recipients.get(recipientId); if (recipient == null) { //give some details about the required and used cert for the decryption Collection recipientList = recipients.getRecipients(); Iterator iterator = recipientList.iterator(); while (iterator.hasNext()) { RecipientInformation recipientInfo = (RecipientInformation) iterator.next(); if (this.logger != null) { this.logger.log(Level.SEVERE, this.rb.getResourceString("decryption.inforequired", new Object[] { info.getMessageId(), ((KeyTransRecipientId) recipientInfo.getRID()).getIssuer() + ", " + ((KeyTransRecipientId) recipientInfo.getRID()).getSerialNumber() }), info); } } if (this.logger != null) { this.logger.log( Level.SEVERE, this.rb .getResourceString("decryption.infoassigned", new Object[] { info.getMessageId(), receiverCryptAlias, recipientId.getIssuer() + ", " + recipientId.getSerialNumber() }), info); } throw new AS2Exception(AS2Exception.AUTHENTIFICATION_ERROR, "Error decrypting the message: Recipient certificate does not match.", message); } //Streamed decryption. Its also possible to use in memory decryption using getContent but that uses //far more memory. InputStream contentStream = recipient .getContentStream(new JceKeyTransEnvelopedRecipient(privateKeyReceiver).setProvider("BC")) .getContentStream(); //InputStream contentStream = recipient.getContentStream(privateKeyReceiver, "BC").getContentStream(); //threshold set to 20 MB: if the data is less then 20MB perform the operaion in memory else stream to disk DeferredFileOutputStream decryptedOutput = new DeferredFileOutputStream(20 * 1024 * 1024, "as2decryptdata_", ".mem", null); this.copyStreams(contentStream, decryptedOutput); decryptedOutput.flush(); decryptedOutput.close(); contentStream.close(); byte[] decryptedData = null; //size of the data was < than the threshold if (decryptedOutput.isInMemory()) { decryptedData = decryptedOutput.getData(); } else { //data has been written to a temp file: reread and return ByteArrayOutputStream memOut = new ByteArrayOutputStream(); decryptedOutput.writeTo(memOut); memOut.flush(); memOut.close(); //finally delete the temp file boolean deleted = decryptedOutput.getFile().delete(); decryptedData = memOut.toByteArray(); } if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("decryption.done.alias", new Object[] { info.getMessageId(), receiverCryptAlias, this.rbMessage.getResourceString("encryption." + info.getEncryptionType()) }), info); } return (decryptedData); }
From source file:io.aos.crypto.spl09.KeyTransEnvelopedDataWithCertMatchExample.java
License:Apache License
public static void main(String... args) throws Exception { KeyStore credentials = Utils.createCredentials(); PrivateKey key = (PrivateKey) credentials.getKey(Utils.END_ENTITY_ALIAS, Utils.KEY_PASSWD); Certificate[] chain = credentials.getCertificateChain(Utils.END_ENTITY_ALIAS); X509Certificate cert = (X509Certificate) chain[0]; // set up the generator CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator(); gen.addKeyTransRecipient(cert);/*from w w w. j a v a 2 s . c o m*/ // create the enveloped-data object CMSProcessable data = new CMSProcessableByteArray("Hello World!".getBytes()); CMSEnvelopedData enveloped = gen.generate(data, CMSEnvelopedDataGenerator.AES256_CBC, "BC"); // recreate enveloped = new CMSEnvelopedData(enveloped.getEncoded()); // set up to iterate through the recipients RecipientInformationStore recipients = enveloped.getRecipientInfos(); CertStore certStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(Collections.singleton(cert)), "BC"); Iterator it = recipients.getRecipients().iterator(); RecipientInformation recipient = null; while (it.hasNext()) { recipient = (RecipientInformation) it.next(); if (recipient instanceof KeyTransRecipientInformation) { // match the recipient ID Collection matches = certStore.getCertificates(recipient.getRID()); if (!matches.isEmpty()) { // decrypt the data byte[] recData = recipient.getContent(key, "BC"); // compare recovered data to the original data if (Arrays.equals((byte[]) data.getContent(), recData)) { System.out.println("data recovery succeeded"); break; } else { System.out.println("data recovery failed"); break; } } } } if (recipient == null) { System.out.println("could not find a matching recipient"); } }
From source file:mitm.common.security.cms.CMSEnvelopedInspectorImpl.java
License:Open Source License
@SuppressWarnings("unchecked") @Override/*from w w w . jav a2s . c o m*/ public List<RecipientInfo> getRecipients() throws CryptoMessageSyntaxException { if (recipients == null) { recipients = new LinkedList<RecipientInfo>(); RecipientInformationStore store = envelopedDataAdapter.getRecipientInfos(); Collection<RecipientInformation> cmsRecipients = store.getRecipients(); for (RecipientInformation recipientInformation : cmsRecipients) { /* * currently only KeyTransRecipientInformation is supported */ if (recipientInformation instanceof KeyTransRecipientInformation) { try { recipients.add(new RecipientInfoImpl(recipientInformation, nonSensitiveProvider, sensitiveProvider)); } catch (RecipientInfoException e) { throw new CryptoMessageSyntaxException(e); } } else { logger.warn("Unsopported recipientInformation. Class: " + recipientInformation.getClass()); } } } return Collections.unmodifiableList(recipients); }
From source file:org.apache.james.transport.mailets.SMIMEDecrypt.java
License:Apache License
/** * @see org.apache.mailet.Mailet#service(org.apache.mailet.Mail) */// w w w .j a va2s . c om @SuppressWarnings("unchecked") public void service(Mail mail) throws MessagingException { MimeMessage message = mail.getMessage(); Part strippedMessage = null; log("Starting message decryption.."); if (message.isMimeType("application/x-pkcs7-mime") || message.isMimeType("application/pkcs7-mime")) { try { SMIMEEnveloped env = new SMIMEEnveloped(message); RecipientInformationStore informationStore = env.getRecipientInfos(); Collection<RecipientInformation> recipients = informationStore.getRecipients(); for (RecipientInformation info : recipients) { RecipientId id = info.getRID(); if (id.match(keyHolder.getCertificate())) { try { JceKeyTransEnvelopedRecipient recipient = new JceKeyTransEnvelopedRecipient( keyHolder.getPrivateKey()); // strippedMessage contains the decrypted message. strippedMessage = SMIMEUtil.toMimeBodyPart(info.getContent(recipient)); log("Encrypted message decrypted"); } catch (Exception e) { throw new MessagingException("Error during the decryption of the message", e); } } else { log("Found an encrypted message but it isn't encrypted for the supplied key"); } } } catch (CMSException e) { throw new MessagingException("Error during the decryption of the message", e); } } // if the decryption has been successful.. if (strippedMessage != null) { // I put the private key's public certificate as a mailattribute. // I create a list of certificate because I want to minic the // behavior of the SMIMEVerifySignature mailet. In that way // it is possible to reuse the same matchers to analyze // the result of the operation. ArrayList<X509Certificate> list = new ArrayList<X509Certificate>(1); list.add(keyHolder.getCertificate()); mail.setAttribute(mailAttribute, list); // I start the message stripping. try { MimeMessage newmex = new MimeMessage(message); Object obj = strippedMessage.getContent(); if (obj instanceof Multipart) { log("The message is multipart, content type " + ((Multipart) obj).getContentType()); newmex.setContent((Multipart) obj); } else { newmex.setContent(obj, strippedMessage.getContentType()); newmex.setDisposition(null); } newmex.saveChanges(); mail.setMessage(newmex); } catch (IOException e) { log("Error during the strip of the encrypted message"); throw new MessagingException("Error during the stripping of the encrypted message", e); } } }
From source file:org.apache.kerby.pkix.EnvelopedDataEngine.java
License:Apache License
/** * Uses a private key to decrypt data in a CMS EnvelopedData structure and * returns the recovered (decrypted) data bytes. * * @param envelopedDataBytes//from w w w .j a v a 2 s. co m * @param privateKey * @return The recovered (decrypted) data bytes. * @throws IOException * @throws CMSException */ @SuppressWarnings("unchecked") public static byte[] getUnenvelopedData(byte[] envelopedDataBytes, PrivateKey privateKey) throws CMSException, IOException { CMSEnvelopedData envelopedData = new CMSEnvelopedData(envelopedDataBytes); // Set up to iterate through the recipients. RecipientInformationStore recipients = envelopedData.getRecipientInfos(); Collection c = recipients.getRecipients(); Iterator it = c.iterator(); byte[] recData = new byte[0]; while (it.hasNext()) { RecipientInformation recipient = (RecipientInformation) it.next(); recData = recipient.getContent(new BcRSAKeyTransEnvelopedRecipient( PrivateKeyFactory.createKey(PrivateKeyInfo.getInstance(privateKey.getEncoded())))); } return recData; }
From source file:org.cesecore.certificates.ca.X509CA.java
License:Open Source License
@Override public KeyPair decryptKeys(CryptoToken cryptoToken, String alias, byte[] data) throws IOException, CMSException, CryptoTokenOfflineException, ClassNotFoundException { CMSEnvelopedData ed = new CMSEnvelopedData(data); RecipientInformationStore recipients = ed.getRecipientInfos(); RecipientInformation recipient = (RecipientInformation) recipients.getRecipients().iterator().next(); ObjectInputStream ois = null; JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(cryptoToken.getPrivateKey(alias)); rec.setProvider(cryptoToken.getEncProviderName()); rec.setContentProvider("BC"); byte[] recdata = recipient.getContent(rec); ois = new ObjectInputStream(new ByteArrayInputStream(recdata)); log.info("Decrypted keys using key alias '" + alias + "' from Crypto Token " + cryptoToken.getId()); return (KeyPair) ois.readObject(); }
From source file:org.cesecore.certificates.ca.X509CA.java
License:Open Source License
@Override public byte[] decryptData(CryptoToken cryptoToken, byte[] data, int cAKeyPurpose) throws CMSException, CryptoTokenOfflineException { CMSEnvelopedData ed = new CMSEnvelopedData(data); RecipientInformationStore recipients = ed.getRecipientInfos(); RecipientInformation recipient = (RecipientInformation) recipients.getRecipients().iterator().next(); final String keyAlias = getCAToken().getAliasFromPurpose(cAKeyPurpose); JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(cryptoToken.getPrivateKey(keyAlias)); rec.setProvider(cryptoToken.getSignProviderName()); rec.setContentProvider("BC"); byte[] recdata = recipient.getContent(rec); log.info("Decrypted data using key alias '" + keyAlias + "' from Crypto Token " + cryptoToken.getId()); return recdata; }
From source file:org.cryptable.pki.communication.PKICMPMessagesTest.java
License:Open Source License
/** * Check the private key archive control in the certification request * * @throws OperatorCreationException/*from w ww. j ava2 s. co m*/ * @throws PKICMPMessageException * @throws CertificateEncodingException * @throws IOException * @throws CRMFException * @throws CMPException * @throws CMSException */ @Test public void testCertificationWithPrivateKeyControl() throws OperatorCreationException, PKICMPMessageException, CertificateException, IOException, CRMFException, CMPException, CMSException, InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchFieldException, IllegalAccessException, CRLException { String distinguishedName = pki.getTestUser1Cert().getSubjectX500Principal().getName(); KeyPair keyPair = new KeyPair(pki.getTestUser1Cert().getPublicKey(), pki.getTestUser1CertPrivateKey()); PKICMPMessages pkiMessages = new PKICMPMessages(); pkiMessages.setPkiKeyStore(pkiKeyStoreRA); byte[] result = pkiMessages.createCertificateMessageWithLocalKey(distinguishedName, keyPair); ASN1InputStream asn1InputStream = new ASN1InputStream(result); ASN1Primitive asn1Primitive = asn1InputStream.readObject(); PKIMessage pkiMessage = PKIMessage.getInstance(asn1Primitive); CertReqMsg[] certReqMsgs = CertReqMessages.getInstance(pkiMessage.getBody().getContent()) .toCertReqMsgArray(); AttributeTypeAndValue[] attributeTypeAndValues = certReqMsgs[0].getCertReq().getControls() .toAttributeTypeAndValueArray(); GeneratePKI genPKI = new GeneratePKI(); genPKI.createPKI(); boolean bFound = false; for (AttributeTypeAndValue attributeTypeAndValue : attributeTypeAndValues) { if (attributeTypeAndValue.getType().equals(CRMFObjectIdentifiers.id_regCtrl_pkiArchiveOptions)) { PKIArchiveControl pkiArchiveControl = new PKIArchiveControl( PKIArchiveOptions.getInstance(attributeTypeAndValue.getValue())); // Decrypt data CMSEnvelopedDataParser cmsEnvelopedDataParser = new CMSEnvelopedDataParser( pkiArchiveControl.getEnvelopedData().getEncoded()); RecipientInformationStore recipients = cmsEnvelopedDataParser.getRecipientInfos(); Collection c = recipients.getRecipients(); Iterator it = c.iterator(); if (it.hasNext()) { RecipientInformation recipient = (RecipientInformation) it.next(); byte[] recdata = recipient .getContent(new JceKeyTransEnvelopedRecipient(genPKI.getSubCACertPrivateKey()) .setProvider(pkiKeyStoreRA.getProvider())); ASN1InputStream tstAsn1InputStream = new ASN1InputStream(recdata); ASN1Primitive tstAsn1Primitive = tstAsn1InputStream.readObject(); EncKeyWithID encKeyWithID = EncKeyWithID.getInstance(tstAsn1Primitive); Assert.assertArrayEquals(keyPair.getPrivate().getEncoded(), encKeyWithID.getPrivateKey().getEncoded()); Assert.assertTrue(encKeyWithID.hasIdentifier()); GeneralName identifier = GeneralName.getInstance(encKeyWithID.getIdentifier()); Assert.assertEquals(genPKI.getTestUser1Cert().getSubjectDN().getName(), identifier.getName().toString()); bFound = true; } } } Assert.assertTrue(bFound); }