Example usage for org.bouncycastle.cms.jcajce JceKeyTransRecipientId JceKeyTransRecipientId

List of usage examples for org.bouncycastle.cms.jcajce JceKeyTransRecipientId JceKeyTransRecipientId

Introduction

In this page you can find the example usage for org.bouncycastle.cms.jcajce JceKeyTransRecipientId JceKeyTransRecipientId.

Prototype

public JceKeyTransRecipientId(X509Certificate certificate) 

Source Link

Document

Construct a recipient id based on the issuer, serial number and subject key identifier (if present) of the passed in certificate.

Usage

From source file:be.e_contract.mycarenet.etee.Unsealer.java

License:Open Source License

@SuppressWarnings("unchecked")
private byte[] decrypt(byte[] encryptedData) throws CMSException, IOException {
    CMSEnvelopedDataParser cmsEnvelopedDataParser = new CMSEnvelopedDataParser(encryptedData);
    LOG.debug("content encryption algo: "
            + cmsEnvelopedDataParser.getContentEncryptionAlgorithm().getAlgorithm().getId());

    RecipientInformationStore recipientInformationStore = cmsEnvelopedDataParser.getRecipientInfos();
    RecipientId recipientId = new JceKeyTransRecipientId(this.decryptionCertificate);
    Collection<RecipientInformation> recipients = recipientInformationStore.getRecipients(recipientId);
    LOG.debug("number of recipients for given decryption cert: " + recipients.size());
    if (0 == recipients.size()) {
        recipients = recipientInformationStore.getRecipients();
        LOG.debug("number of all recipients: " + recipients.size());
        Iterator<RecipientInformation> recipientsIterator = recipients.iterator();
        while (recipientsIterator.hasNext()) {
            RecipientInformation recipientInformation = recipientsIterator.next();
            RecipientId actualRecipientId = recipientInformation.getRID();
            LOG.debug("actual recipient id type: " + actualRecipientId.getClass().getName());
            if (actualRecipientId instanceof KeyTransRecipientId) {
                KeyTransRecipientId actualKeyTransRecipientId = (KeyTransRecipientId) actualRecipientId;
                LOG.debug("actual recipient issuer: " + actualKeyTransRecipientId.getIssuer());
                LOG.debug("actual recipient serial number: " + actualKeyTransRecipientId.getSerialNumber());
            }/*from   ww  w.  j a va 2  s. c o  m*/
        }
        throw new SecurityException("message does not seem to be addressed to you");
    }
    Iterator<RecipientInformation> recipientsIterator = recipients.iterator();
    RecipientInformation recipientInformation = recipientsIterator.next();

    AsymmetricKeyParameter privKeyParams = PrivateKeyFactory.createKey(this.decryptionPrivateKey.getEncoded());
    BcRSAKeyTransEnvelopedRecipient recipient = new BcRSAKeyTransEnvelopedRecipient(privKeyParams);
    byte[] decryptedContent = recipientInformation.getContent(recipient);
    return decryptedContent;
}

From source file:br.ufpb.dicomflow.integrationAPI.mail.impl.SMTPServiceExtractor.java

License:Open Source License

private Multipart getDecryptedContent(Message message, X509Certificate signCert, X509Certificate encryptCert,
        PrivateKey privateKey) throws OperatorCreationException, Exception {
    RecipientId recId = new JceKeyTransRecipientId(encryptCert);
    SMIMEEnveloped m = new SMIMEEnveloped((MimeMessage) message);

    RecipientInformationStore recipients = m.getRecipientInfos();
    RecipientInformation recipient = recipients.get(recId);

    MimeBodyPart res = SMIMEUtil//from   w  w  w. jav a  2 s.c o  m
            .toMimeBodyPart(recipient.getContent(new JceKeyTransEnvelopedRecipient(privateKey)));
    MimeMultipart content = (MimeMultipart) res.getContent();
    Multipart decryptedContent = null;
    if (checkSignature(content, signCert)) {
        for (int i = 0; i < content.getCount(); i++) {
            Part part = content.getBodyPart(i);

            String contentType = part.getContentType();

            if (contentType.toLowerCase().startsWith("multipart/mixed")) {
                decryptedContent = (Multipart) part.getContent();
            }

        }
    }

    return decryptedContent;
}

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//ww  w .  j a v a2s.  com
 * @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:de.mendelson.util.security.BCCryptoHelper.java

/**
 * Used for mendelson rosettaNet//from   w  ww  .  j  ava2 s  . c o  m
 */
public MimeBodyPart decrypt(MimeBodyPart part, Certificate cert, Key key)
        throws GeneralSecurityException, MessagingException, CMSException, IOException, SMIMEException {
    if (!this.isEncrypted(part)) {
        throw new GeneralSecurityException(
                "decrypt: Unable to decrypt - Content-Type indicates data isn't encrypted");
    }
    X509Certificate x509Cert = castCertificate(cert);
    SMIMEEnveloped envelope = new SMIMEEnveloped(part);
    RecipientId recipientId = new JceKeyTransRecipientId(x509Cert);
    RecipientInformation recipient = envelope.getRecipientInfos().get(recipientId);
    if (recipient == null) {
        throw new GeneralSecurityException(
                "decrypt: Unable to decrypt data - wrong key used to decrypt the data.");
    } else {
        MimeBodyPart bodyPart = SMIMEUtil.toMimeBodyPart(recipient.getContentStream(
                new JceKeyTransEnvelopedRecipient(this.getPrivateKey(key)).setProvider("BC")));
        return (bodyPart);
    }
}

From source file:de.mendelson.util.security.BCCryptoHelper.java

/**
 * Decrypts a formerly encrypted stream. An exception will be thrown if
 * decryption is not possible//from   w  w w.j  a  v  a 2s.  c o  m
 */
public void decryptCMS(InputStream encrypted, OutputStream decrypted, Certificate cert, Key key)
        throws Exception {
    BufferedInputStream bufferedEncrypted = new BufferedInputStream(encrypted);
    BufferedOutputStream bufferedDecrypted = new BufferedOutputStream(decrypted);
    X509Certificate x509Cert = this.castCertificate(cert);
    CMSEnvelopedDataParser parser = new CMSEnvelopedDataParser(bufferedEncrypted);
    RecipientId recipientId = new JceKeyTransRecipientId(x509Cert);
    RecipientInformation recipient = parser.getRecipientInfos().get(recipientId);
    if (recipient != null) {
        CMSTypedStream cmsEncrypted = recipient
                .getContentStream(new JceKeyTransEnvelopedRecipient(this.getPrivateKey(key)).setProvider("BC"));
        InputStream encryptedContent = cmsEncrypted.getContentStream();
        this.copyStreams(encryptedContent, bufferedDecrypted);
        bufferedDecrypted.flush();
    } else {
        throw new GeneralSecurityException("Wrong key used to decrypt the data.");
    }
}

From source file:net.markenwerk.utils.mail.smime.SmimeUtil.java

License:Open Source License

private static byte[] decryptContent(SMIMEEnveloped smimeEnveloped, SmimeKey smimeKey)
        throws MessagingException, CMSException {
    X509Certificate certificate = smimeKey.getCertificate();
    PrivateKey privateKey = smimeKey.getPrivateKey();

    RecipientInformationStore recipients = smimeEnveloped.getRecipientInfos();
    RecipientInformation recipient = recipients.get(new JceKeyTransRecipientId(certificate));

    if (null == recipient) {
        throw new MessagingException("no recipient");
    }/*from w  ww. j  a v  a2  s  .c  o  m*/

    JceKeyTransRecipient transportRecipient = new JceKeyTransEnvelopedRecipient(privateKey);
    transportRecipient.setProvider(BouncyCastleProvider.PROVIDER_NAME);
    return recipient.getContent(transportRecipient);
}

From source file:org.votingsystem.signature.util.Encryptor.java

License:Open Source License

public Encryptor(X509Certificate localCert, PrivateKey localPrivateKey) {
    this.privateKey = localPrivateKey;
    recipientId = new JceKeyTransRecipientId(localCert);
    recipient = new JceKeyTransEnvelopedRecipient(localPrivateKey).setProvider(ContextVS.PROVIDER);
}

From source file:org.xipki.pki.scep.message.EnvelopedDataDecryptorInstance.java

License:Open Source License

public EnvelopedDataDecryptorInstance(final X509Certificate recipientCert, final PrivateKey privKey) {
    ParamUtil.requireNonNull("recipientCert", recipientCert);
    ParamUtil.requireNonNull("privKey", privKey);

    this.recipientId = new JceKeyTransRecipientId(recipientCert);
    this.recipient = new JceKeyTransEnvelopedRecipient(privKey);
}