Example usage for org.bouncycastle.cms KeyTransRecipientId KeyTransRecipientId

List of usage examples for org.bouncycastle.cms KeyTransRecipientId KeyTransRecipientId

Introduction

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

Prototype

public KeyTransRecipientId(X500Name issuer, BigInteger serialNumber) 

Source Link

Document

Construct a key trans recipient ID based on the issuer and serial number of the recipient's associated certificate.

Usage

From source file:chapter9.EnvelopedMailExample.java

/**
 *
 * @param args/*from   w ww. j  av  a  2  s .  co m*/
 * @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.- Create the message we want encrypted
    MimeBodyPart dataPart = new MimeBodyPart();

    dataPart.setText("Hello World!!");

    //2.- Set up the generator
    SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator();

    gen.addKeyTransRecipient(cert);

    //3.- Generate the enveloped message
    MimeBodyPart envPart = gen.generate(dataPart, SMIMEEnvelopedGenerator.AES256_CBC,
            CryptoDefs.Provider.BC.getName());

    //4.- Create the mail message
    MimeMessage mail = Utils.createMimeMessage("example enveloped message", envPart.getContent(),
            envPart.getContentType());

    //5.- Create the enveloped object from the mail message
    SMIMEEnveloped enveloped = new SMIMEEnveloped(mail);

    //6.- Look for our recipient identifier
    RecipientId recId = new KeyTransRecipientId(new X500Name(cert.getIssuerX500Principal().getName()),
            cert.getSerialNumber());

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

    if (recipient != null) {
        //7.- Decryption step
        MimeBodyPart recoveredPart = SMIMEUtil
                .toMimeBodyPart(recipient.getContent(key, CryptoDefs.Provider.BC.getName()));

        //8.- Content display step
        System.out.print("\t Content:");
        System.out.println(recoveredPart.getContent());
    } else
        System.out.println("\t could not find a matching recipient!!");
}

From source file:chapter9.EnvelopedSignedMailExample.java

/**
 *
 * @param args/*  w w  w. j av  a  2  s. c  o  m*/
 * @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);

    CertStore certsAndCRLs = CertStore.getInstance("Collection",
            new CollectionCertStoreParameters(Arrays.asList(chain)), CryptoDefs.Provider.BC.getName());

    X509Certificate cert = (X509Certificate) chain[0];

    //1.- Create the message we want signed
    MimeBodyPart dataPart = new MimeBodyPart();

    dataPart.setText("Hello World!!");

    //2.- Create the signed message
    MimeMultipart signedMulti = SignedMailExample.createMultipartWithSignature(key, cert, certsAndCRLs,
            dataPart);

    //3.- Create the body part containing the signed message
    MimeBodyPart signedPart = new MimeBodyPart();

    signedPart.setContent(signedMulti);

    //4.- Set up the generator
    SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator();

    gen.addKeyTransRecipient(cert);

    //5.- Generate the enveloped message
    MimeBodyPart envPart = gen.generate(signedPart, SMIMEEnvelopedGenerator.AES256_CBC,
            CryptoDefs.Provider.BC.getName());

    //6.- Create the mail message
    MimeMessage mail = Utils.createMimeMessage("example signed and enveloped message", envPart.getContent(),
            envPart.getContentType());

    //7.- Create the enveloped object from the mail message
    SMIMEEnveloped enveloped = new SMIMEEnveloped(mail);

    //8.- Look for our recipient identifier
    RecipientId recId = new KeyTransRecipientId(new X500Name(cert.getIssuerX500Principal().getName()),
            cert.getSerialNumber());

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

    //9.- Decryption step
    MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContent(key, CryptoDefs.Provider.BC.getName()));

    //10.- Extract the multipart from the body part
    if (res.getContent() instanceof MimeMultipart) {
        SMIMESigned signed = new SMIMESigned((MimeMultipart) res.getContent());

        //11.- Verification step
        X509Certificate rootCert = (X509Certificate) credentials.getCertificate(Utils.ROOT_ALIAS);

        if (isValid(signed, rootCert))
            System.out.println("\t verification succeeded!!");
        else
            System.out.println("\t verification failed!!");

        //12.- Content display step
        MimeBodyPart content = signed.getContent();

        System.out.print("\t Content: ");
        System.out.println(content.getContent());
    } else
        System.out.println("\t wrong content found!!");
}

From source file:chapter9.KeyTransEnvelopedDataExample.java

/**
 *
 * @param args//from ww w  . ja  va 2  s  .  c  o  m
 * @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
    RecipientId recId = new KeyTransRecipientId(new X500Name(cert.getIssuerX500Principal().getName()),
            cert.getSerialNumber());

    recId.setSerialNumber(cert.getSerialNumber());
    recId.setIssuer(cert.getIssuerX500Principal().getEncoded());

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

    if (recipient != null) {
        //5.- Decrypt the data
        byte[] recData = recipient.getContent(key, CryptoDefs.Provider.BC.getName());

        //6.- Compare recovered data to the original data
        if (Arrays.equals((byte[]) data.getContent(), recData))
            System.out.println("\t data recovery succeeded!!");
        else
            System.out.println("\t data recovery failed!!");
    } else
        System.out.println("\t Could not find a matching recipient!!");
}

From source file:org.ejbca.core.model.ca.caadmin.extendedcaservices.CmsCAService.java

License:Open Source License

@Override
public ExtendedCAServiceResponse extendedService(final CryptoToken cryptoToken,
        final ExtendedCAServiceRequest request) throws ExtendedCAServiceRequestException,
        IllegalExtendedCAServiceRequestException, ExtendedCAServiceNotActiveException {
    if (log.isTraceEnabled()) {
        log.trace(">extendedService");
    }//from   ww  w  .  j  ava 2  s. c om
    if (!(request instanceof CmsCAServiceRequest)) {
        throw new IllegalExtendedCAServiceRequestException();
    }
    if (getStatus() != ExtendedCAServiceInfo.STATUS_ACTIVE) {
        final String msg = intres.getLocalizedMessage("caservice.notactive", "CMS");
        log.error(msg);
        throw new ExtendedCAServiceNotActiveException(msg);
    }
    ExtendedCAServiceResponse returnval = null;
    final X509Certificate signerCert = (X509Certificate) certificatechain.get(0);
    final CmsCAServiceRequest serviceReq = (CmsCAServiceRequest) request;
    // Create the signed data
    final CMSSignedDataGenerator gen1 = new CMSSignedDataGenerator();
    try {
        byte[] resp = serviceReq.getDoc();
        // Add our signer info and sign the message
        if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_SIGN) != 0) {
            final List<X509Certificate> x509CertChain = new ArrayList<X509Certificate>();
            for (Certificate certificate : certificatechain) {
                x509CertChain.add((X509Certificate) certificate);
            }
            gen1.addCertificates(new CollectionStore(CertTools.convertToX509CertificateHolder(x509CertChain)));
            JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME);
            JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder(
                    calculatorProviderBuilder.build());
            ASN1ObjectIdentifier oid = AlgorithmTools
                    .getSignAlgOidFromDigestAndKey(CMSSignedGenerator.DIGEST_SHA1, privKey.getAlgorithm());
            String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromOID(oid);
            JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithmName)
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME);
            ContentSigner contentSigner = signerBuilder.build(privKey);
            gen1.addSignerInfoGenerator(builder.build(contentSigner, signerCert));
            final CMSTypedData msg = new CMSProcessableByteArray(resp);
            final CMSSignedData s = gen1.generate(msg, true);
            resp = s.getEncoded();
        }
        if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_ENCRYPT) != 0) {
            CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
            edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(getCMSCertificate())
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME));
            JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder(
                    PKCSObjectIdentifiers.des_EDE3_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME);
            CMSEnvelopedData ed = edGen.generate(new CMSProcessableByteArray(resp),
                    jceCMSContentEncryptorBuilder.build());
            resp = ed.getEncoded();
        }
        if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_DECRYPT) != 0) {
            final CMSEnvelopedData ed = new CMSEnvelopedData(resp);
            final RecipientInformationStore recipients = ed.getRecipientInfos();
            final X500Name issuer = X500Name
                    .getInstance(getCMSCertificate().getIssuerX500Principal().getEncoded());
            final KeyTransRecipientId id = new KeyTransRecipientId(issuer,
                    getCMSCertificate().getSerialNumber());
            final RecipientInformation recipient = recipients.get(id);
            if (recipient != null) {
                JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(this.privKey);
                // Provider for decrypting the symmetric key 
                rec.setContentProvider(BouncyCastleProvider.PROVIDER_NAME);
                rec.setProvider(cryptoToken.getSignProviderName());
                // We can use a different provider for decrypting the content, for example of we used a PKCS#11 provider above we could use the BC provider below
                resp = recipient.getContent(rec);
            }
        }
        returnval = new CmsCAServiceResponse(resp);
    } catch (CMSException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    } catch (IOException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    } catch (OperatorCreationException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    } catch (CertificateEncodingException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<extendedService");
    }
    return returnval;
}