Example usage for org.bouncycastle.cms CMSTypedStream getContentStream

List of usage examples for org.bouncycastle.cms CMSTypedStream getContentStream

Introduction

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

Prototype

public InputStream getContentStream() 

Source Link

Usage

From source file:com.gc.iotools.fmt.decoders.Pkcs7Decoder.java

License:BSD License

/**
 * {@inheritDoc}/*from  w  w w .ja va2 s  .  c o  m*/
 */
@Override
public InputStream decode(final InputStream istream) throws IOException {
    CMSSignedDataParser sdp;
    try {
        sdp = new CMSSignedDataParser(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(),
                istream);
    } catch (final CMSException e) {
        final IOException e1 = new IOException("Error parsing PKCS7 content");
        e1.initCause(e);
        throw e1;
    } catch (OperatorCreationException e) {
        final IOException e1 = new IOException("Error initializing PKCS7 decoder.");
        e1.initCause(e);
        throw e1;
    }
    final CMSTypedStream ts = sdp.getSignedContent();
    return ts.getContentStream();
}

From source file:com.zotoh.crypto.CryptoUte.java

License:Open Source License

/**
 * @param key/*from   w w w.  j  a  va 2 s .  c o  m*/
 * @param part
 * @return
 * @throws MessagingException
 * @throws GeneralSecurityException
 * @throws IOException
 */
public static StreamData smimeDecrypt(PrivateKey key, BodyPart part)
        throws MessagingException, GeneralSecurityException, IOException {

    tstArgIsType("bodypart", part, MimeBodyPart.class);
    tstObjArg("private-key", key);
    CMSTypedStream cms = null;
    try {
        SMIMEEnveloped env = new SMIMEEnveloped((MimeBodyPart) part);
        cms = smime_decrypt(key, env);
    } catch (CMSException e) {
        throw new GeneralSecurityException(e);
    }
    if (cms == null) {
        throw new GeneralSecurityException("Failed to decrypt: no matching decryption key");
    }
    //else
    return readStream(cms.getContentStream());
}

From source file:com.zotoh.crypto.CryptoUte.java

License:Open Source License

/**
 * @param keys//from w  ww .  jav  a  2s.c  o m
 * @param msg
 * @return
 * @throws GeneralSecurityException
 * @throws MessagingException
 * @throws IOException
 */
public static StreamData smimeDecryptAsStream(PrivateKey[] keys, MimeMessage msg)
        throws GeneralSecurityException, MessagingException, IOException {

    tstObjArg("mime-message", msg);
    tstObjArg("private-key(s)", keys);

    CMSTypedStream cms = null;
    SMIMEEnveloped env;
    try {
        env = new SMIMEEnveloped(msg);
    } catch (CMSException e) {
        throw new GeneralSecurityException(e);
    }

    for (int n = 0; n < keys.length; ++n) {
        cms = smime_decrypt(keys[n], env);
        if (cms != null) {
            break;
        }
        cms = null;
    }

    if (cms == null) {
        throw new GeneralSecurityException("Failed to decrypt: no matching decryption key");
    }
    //else
    return readStream(cms.getContentStream());
}

From source file:com.zotoh.crypto.CryptoUte.java

License:Open Source License

/**
 * @param inp//from w w w  . j a v  a  2 s  .  co m
 * @return
 * @throws GeneralSecurityException
 * @throws IOException
 */
public static StreamData decompressAsStream(InputStream inp) throws GeneralSecurityException, IOException {
    CMSTypedStream cms = null;
    StreamData r = null;

    if (inp != null)
        try {
            cms = new CMSCompressedDataParser(inp).getContent(new ZlibExpanderProvider());
            if (cms == null) {
                throw new GeneralSecurityException("Failed to decompress stream: corrupted content");
            }
            r = readStream(cms.getContentStream());
        } catch (CMSException e) {
            throw new GeneralSecurityException(e);
        }

    return r != null ? r : new StreamData();
}

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  a2s.com
 */
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:org.apache.tika.parser.crypto.Pkcs7Parser.java

License:Apache License

public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {
    try {//from ww w.java2  s .  c  o m
        DigestCalculatorProvider digestCalculatorProvider = new JcaDigestCalculatorProviderBuilder()
                .setProvider("BC").build();
        CMSSignedDataParser parser = new CMSSignedDataParser(digestCalculatorProvider,
                new CloseShieldInputStream(stream));
        try {
            CMSTypedStream content = parser.getSignedContent();
            if (content == null) {
                throw new TikaException("cannot parse detached pkcs7 signature (no signed data to parse)");
            }
            try (InputStream input = content.getContentStream()) {
                Parser delegate = context.get(Parser.class, EmptyParser.INSTANCE);
                delegate.parse(input, handler, metadata, context);
            }
        } finally {
            parser.close();
        }
    } catch (OperatorCreationException e) {
        throw new TikaException("Unable to create DigestCalculatorProvider", e);
    } catch (CMSException e) {
        throw new TikaException("Unable to parse pkcs7 signed data", e);
    }
}

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

License:Open Source License

/**
 * @param is data to be decrypted/*from   ww  w  .jav  a  2s  . com*/
 * @param os decrypted data
 * @param key to be used for the decryption
 * @param providerName the provider that should do the decryption
 * @throws Exception
 */
public static void decrypt(final InputStream is, OutputStream os, PrivateKey key, String providerName)
        throws Exception {
    final InputStream bis = new BufferedInputStream(is, bufferSize);
    final OutputStream bos = new BufferedOutputStream(os, bufferSize);
    @SuppressWarnings("unchecked")
    final Iterator<RecipientInformation> it = new CMSEnvelopedDataParser(bis).getRecipientInfos()
            .getRecipients().iterator();
    if (it.hasNext()) {
        final RecipientInformation recipientInformation = it.next();
        JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(key);
        rec.setProvider(providerName);
        rec.setContentProvider(BouncyCastleProvider.PROVIDER_NAME);
        final CMSTypedStream recData = recipientInformation.getContentStream(rec);
        final InputStream ris = recData.getContentStream();
        fromInToOut(ris, bos);
    }
    os.close();
}

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

License:Open Source License

/**
 * @param is signed data to be verified//from   ww  w .j  a v  a2 s. c o m
 * @param os signature removed from signed data
 * @param cert the certificate with the public key that should do the verification
 * @return true if the signing was to with the private key corresponding to the public key in the certificate.
 * @throws Exception
 */
public static VerifyResult verify(final InputStream is, OutputStream os, X509Certificate cert)
        throws Exception {
    final InputStream bis = new BufferedInputStream(is, bufferSize);
    final OutputStream bos = new BufferedOutputStream(os, bufferSize);
    final CMSSignedDataParser sp = new CMSSignedDataParser(new BcDigestCalculatorProvider(), bis);
    final CMSTypedStream sc = sp.getSignedContent();
    final InputStream ris = sc.getContentStream();
    fromInToOut(ris, bos);
    os.close();
    sc.drain();
    @SuppressWarnings("rawtypes")
    final Iterator it = sp.getSignerInfos().getSigners().iterator();
    if (!it.hasNext()) {
        return null;
    }
    final SignerInformation signerInfo = (SignerInformation) it.next();
    final Attribute attribute = (Attribute) signerInfo.getSignedAttributes().getAll(CMSAttributes.signingTime)
            .get(0);
    final Date date = Time.getInstance(attribute.getAttrValues().getObjectAt(0).toASN1Primitive()).getDate();
    final SignerId id = signerInfo.getSID();
    boolean result = false;
    try {
        JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                .setProvider(BouncyCastleProvider.PROVIDER_NAME);
        JcaSignerInfoVerifierBuilder jcaSignerInfoVerifierBuilder = new JcaSignerInfoVerifierBuilder(
                calculatorProviderBuilder.build()).setProvider(BouncyCastleProvider.PROVIDER_NAME);
        result = signerInfo.verify(jcaSignerInfoVerifierBuilder.build(cert.getPublicKey()));
    } catch (Throwable t) { // NOPMD
        log.debug("Exception when verifying", t);
    }
    return new VerifyResult(date, result, id);
}

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

License:Open Source License

public byte[] decryptCMS(byte[] base64EncryptedData) throws Exception {
    byte[] cmsEncryptedData = Base64.getDecoder().decode(base64EncryptedData);
    CMSEnvelopedDataParser ep = new CMSEnvelopedDataParser(cmsEncryptedData);
    RecipientInformationStore recipients = ep.getRecipientInfos();
    Collection c = recipients.getRecipients();
    Iterator it = c.iterator();/*from w  ww .ja  va  2 s .  c  o  m*/
    byte[] result = null;
    if (it.hasNext()) {
        RecipientInformation recipient = (RecipientInformation) it.next();
        CMSTypedStream recData = recipient.getContentStream(
                new JceKeyTransEnvelopedRecipient(privateKey).setProvider(ContextVS.PROVIDER));
        return FileUtils.getBytesFromStream(recData.getContentStream());
    }
    return result;
}

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

License:Open Source License

public static byte[] decryptCMS(byte[] base64EncryptedData, PrivateKey privateKey)
        throws CMSException, IOException {
    //byte[] cmsEncryptedData = Base64.getDecoder().decode(base64EncryptedData);
    byte[] cmsEncryptedData = org.bouncycastle.util.encoders.Base64.decode(base64EncryptedData);
    CMSEnvelopedDataParser ep = new CMSEnvelopedDataParser(cmsEncryptedData);
    RecipientInformationStore recipients = ep.getRecipientInfos();
    Collection c = recipients.getRecipients();
    Iterator it = c.iterator();//  w  w  w. ja  v  a  2s  .  c  o  m
    byte[] result = null;
    if (it.hasNext()) {
        RecipientInformation recipient = (RecipientInformation) it.next();
        //assertEquals(recipient.getKeyEncryptionAlgOID(), PKCSObjectIdentifiers.rsaEncryption.getId());
        CMSTypedStream recData = recipient.getContentStream(
                new JceKeyTransEnvelopedRecipient(privateKey).setProvider(ContextVS.PROVIDER));
        return FileUtils.getBytesFromStream(recData.getContentStream());
    }
    return result;
}