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

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

Introduction

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

Prototype

public JceKeyTransRecipientInfoGenerator(X509Certificate recipientCert, AlgorithmIdentifier algorithmIdentifier)
        throws CertificateEncodingException 

Source Link

Document

Create a generator overriding the algorithm type implied by the public key in the certificate passed in.

Usage

From source file:mitm.common.security.smime.SMIMEBuilderImpl.java

License:Open Source License

@Override
public void addRecipient(X509Certificate certificate, SMIMERecipientMode mode) throws SMIMEBuilderException {
    Check.notNull(certificate, "certificate");

    try {/*from   ww w.  j  a v a  2  s .  c o m*/
        byte[] subjectKeyIdentifier = X509CertificateInspector.getSubjectKeyIdentifier(certificate);

        if ((mode == SMIMERecipientMode.SUBJECT_KEY_ID_IF_AVAILABLE || mode == SMIMERecipientMode.BOTH)
                && subjectKeyIdentifier != null) {
            PublicKey publicKey = certificate.getPublicKey();

            JceKeyTransRecipientInfoGenerator recipientInfoGenerator = new JceKeyTransRecipientInfoGenerator(
                    subjectKeyIdentifier, publicKey);

            recipientInfoGenerator.setProvider(nonSensitiveProvider);

            envelopedGenerator.addRecipientInfoGenerator(recipientInfoGenerator);
        }

        if (mode == SMIMERecipientMode.ISSUER_SERIAL || mode == SMIMERecipientMode.BOTH
                || subjectKeyIdentifier == null) {
            JceKeyTransRecipientInfoGenerator recipientInfoGenerator = new JceKeyTransRecipientInfoGenerator(
                    certificate);

            recipientInfoGenerator.setProvider(nonSensitiveProvider);

            envelopedGenerator.addRecipientInfoGenerator(recipientInfoGenerator);
        }
    } catch (IOException e) {
        throw new SMIMEBuilderException(e);
    } catch (CertificateEncodingException e) {
        throw new SMIMEBuilderException(e);
    }
}

From source file:no.difi.sdp.client.internal.CreateCMSDocument.java

License:Apache License

public CMSDocument createCMS(byte[] bytes, Sertifikat sertifikat) {
    try {//from  w w w. j  a v  a 2 s .  c  o m
        JceKeyTransRecipientInfoGenerator recipientInfoGenerator = new JceKeyTransRecipientInfoGenerator(
                sertifikat.getX509Certificate(), keyEncryptionScheme)
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME);

        CMSEnvelopedDataGenerator envelopedDataGenerator = new CMSEnvelopedDataGenerator();
        envelopedDataGenerator.addRecipientInfoGenerator(recipientInfoGenerator);

        OutputEncryptor contentEncryptor = new JceCMSContentEncryptorBuilder(cmsEncryptionAlgorithm).build();
        CMSEnvelopedData cmsData = envelopedDataGenerator.generate(new CMSProcessableByteArray(bytes),
                contentEncryptor);

        return new CMSDocument(cmsData.getEncoded());

    } catch (CertificateEncodingException e) {
        throw new KonfigurasjonException("Feil med mottakers sertifikat", e);
    } catch (CMSException e) {
        throw new KonfigurasjonException("Kunne ikke generere Cryptographic Message Syntax for dokumentpakke",
                e);
    } catch (IOException e) {
        throw new RuntimeIOException(e);
    }
}

From source file:no.digipost.api.client.util.Encrypter.java

License:Apache License

public InputStream encrypt(byte[] content) {
    if (key == null) {
        throw new DigipostClientException(ENCRYPTION_KEY_NOT_FOUND,
                "Trying to preencrypt but have no encryption key.");
    }//from   w ww  .  ja  v a2  s . c o m
    try {
        CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator();
        gen.addRecipientInfoGenerator(
                new JceKeyTransRecipientInfoGenerator(key.publicKeyHash.getBytes(), key.publicKey));
        CMSEnvelopedData d = gen.generate(new CMSProcessableByteArray(content), encryptorBuilder.build());
        return new ByteArrayInputStream(d.getEncoded());
    } catch (Exception e) {
        if (e instanceof CMSException && getRootCause(e) instanceof InvalidKeyException) {
            throw new DigipostClientException(FAILED_PREENCRYPTION, "Ugyldig krypteringsnkkel. ("
                    + InvalidKeyException.class.getName() + ") Er Java Cryptographic Extensions (JCE) "
                    + "Unlimited Strength Jurisdiction Policy Files installert? "
                    + "Dette kan lastes ned fra http://www.oracle.com/technetwork/java/javase/downloads/ under \"Additional Resources\". "
                    + "Plasser filene US_export_policy.jar og local_policy.jar i ${JAVA_HOME}/jre/lib/security (overskriv eksisterende).",
                    e);
        } else {
            throw new DigipostClientException(FAILED_PREENCRYPTION, "Feil ved kryptering av innhold: "
                    + e.getClass().getSimpleName() + " '" + e.getMessage() + "'", e);
        }
    }
}

From source file:org.cesecore.certificates.ca.X509CA.java

License:Open Source License

@Override
public byte[] encryptKeys(CryptoToken cryptoToken, String alias, KeyPair keypair) throws IOException,
        CMSException, CryptoTokenOfflineException, NoSuchAlgorithmException, NoSuchProviderException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(baos);
    os.writeObject(keypair);/*  w ww  .j  a va 2  s.c  o  m*/
    CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
    CMSEnvelopedData ed;
    // Creating the KeyId may just throw an exception, we will log this but store the cert and ignore the error
    final PublicKey pk = cryptoToken.getPublicKey(alias);
    byte[] keyId = KeyTools.createSubjectKeyId(pk).getKeyIdentifier();
    edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(keyId, pk));
    JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder(
            NISTObjectIdentifiers.id_aes256_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME);
    ed = edGen.generate(new CMSProcessableByteArray(baos.toByteArray()), jceCMSContentEncryptorBuilder.build());
    log.info("Encrypted keys using key alias '" + alias + "' from Crypto Token " + cryptoToken.getId());
    return ed.getEncoded();
}

From source file:org.cesecore.certificates.ca.X509CA.java

License:Open Source License

@Override
public byte[] encryptData(CryptoToken cryptoToken, byte[] data, int keyPurpose) throws IOException,
        CMSException, CryptoTokenOfflineException, NoSuchAlgorithmException, NoSuchProviderException {
    CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
    CMSEnvelopedData ed;/*from   w w w . j  a  v a 2  s . c  o m*/
    final String keyAlias = getCAToken().getAliasFromPurpose(keyPurpose);
    final PublicKey pk = cryptoToken.getPublicKey(keyAlias);
    byte[] keyId = KeyTools.createSubjectKeyId(pk).getKeyIdentifier();
    edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(keyId, pk));
    JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder(
            NISTObjectIdentifiers.id_aes256_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME);
    ed = edGen.generate(new CMSProcessableByteArray(data), jceCMSContentEncryptorBuilder.build());
    log.info("Encrypted data using key alias '" + keyAlias + "' from Crypto Token " + cryptoToken.getId());
    return ed.getEncoded();
}

From source file:org.ejbca.util.CMS.java

License:Open Source License

/**
 * @param is data to be encrypted//from  www.ja v a  2s.c o m
 * @param os encrypted data
 * @param cert certificate with the public key to be used for the encryption
 * @param symmAlgOid the symmetric encryption algorithm to use, for example CMSEnvelopedGenerator.AES128_CBC
 * @throws Exception
 */
public static void encrypt(final InputStream is, final OutputStream os, final X509Certificate cert,
        final String symmAlgOid) throws Exception {
    final InputStream bis = new BufferedInputStream(is, bufferSize);
    final OutputStream bos = new BufferedOutputStream(os, bufferSize);
    final CMSEnvelopedDataStreamGenerator edGen = new CMSEnvelopedDataStreamGenerator();
    edGen.addRecipientInfoGenerator(
            new JceKeyTransRecipientInfoGenerator("hej".getBytes(), cert.getPublicKey()));
    BcCMSContentEncryptorBuilder bcCMSContentEncryptorBuilder = new BcCMSContentEncryptorBuilder(
            new ASN1ObjectIdentifier(symmAlgOid));
    final OutputStream out = edGen.open(bos, bcCMSContentEncryptorBuilder.build());
    fromInToOut(bis, out);
    bos.close();
    os.close();
}

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

License:Open Source License

public byte[] encryptMessage(byte[] bytesToEncrypt, PublicKey publicKey) throws Exception {
    MimeBodyPart mimeMessage = new MimeBodyPart();
    mimeMessage.setText(new String(bytesToEncrypt));
    //mimeMessage.setSentDate(new Date());// set the Date: header
    SMIMEEnvelopedGenerator encryptor = new SMIMEEnvelopedGenerator();
    encryptor.addRecipientInfoGenerator(
            new JceKeyTransRecipientInfoGenerator("".getBytes(), publicKey).setProvider(ContextVS.PROVIDER));
    /* Encrypt the message */
    MimeBodyPart encryptedPart = encryptor.generate(mimeMessage,
            new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider(ContextVS.PROVIDER)
                    .build());/* w  w w  . j av  a  2  s.  c om*/
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    encryptedPart.writeTo(baos);
    baos.close();
    return baos.toByteArray();
}

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

License:Open Source License

public static byte[] encryptToCMS(byte[] dataToEncrypt, PublicKey receptorPublicKey) throws Exception {
    CMSEnvelopedDataStreamGenerator dataStreamGen = new CMSEnvelopedDataStreamGenerator();
    dataStreamGen//from   w  w w.  j  ava 2  s .c o  m
            .addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator("".getBytes(), receptorPublicKey)
                    .setProvider(ContextVS.PROVIDER));
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    OutputStream out = dataStreamGen.open(bOut, new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC)
            .setProvider(ContextVS.PROVIDER).build());
    out.write(dataToEncrypt);
    out.close();
    return Base64.getEncoder().encode(bOut.toByteArray());
}