Example usage for org.bouncycastle.cms CMSEnvelopedData getRecipientInfos

List of usage examples for org.bouncycastle.cms CMSEnvelopedData getRecipientInfos

Introduction

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

Prototype

public RecipientInformationStore getRecipientInfos() 

Source Link

Document

return a store of the intended recipients for this message

Usage

From source file:org.ejbca.core.protocol.scep.ScepRequestMessage.java

License:Open Source License

private void decrypt() throws CMSException, NoSuchProviderException, GeneralSecurityException, IOException {
    if (log.isTraceEnabled()) {
        log.trace(">decrypt");
    }/*from ww  w. j  a  v  a  2 s . c o  m*/
    // Now we are getting somewhere (pheew),
    // Now we just have to get the damn key...to decrypt the PKCS10
    if (privateKey == null) {
        errorText = "Need private key to decrypt!";
        error = 5;
        log.error(errorText);
        return;
    }

    if (envEncData == null) {
        errorText = "No enveloped data to decrypt!";
        error = 6;
        log.error(errorText);
        return;
    }

    CMSEnvelopedData ed = new CMSEnvelopedData(envEncData);
    RecipientInformationStore recipients = ed.getRecipientInfos();
    @SuppressWarnings("unchecked")
    Collection<RecipientInformation> c = recipients.getRecipients();
    Iterator<RecipientInformation> it = c.iterator();
    byte[] decBytes = null;

    while (it.hasNext()) {
        RecipientInformation recipient = (RecipientInformation) it.next();
        if (log.isDebugEnabled()) {
            log.debug("Privatekey : " + privateKey.getAlgorithm());
        }
        JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(privateKey);
        rec.setProvider(jceProvider); // Use the crypto token provides for asymmetric key operations
        rec.setContentProvider(BouncyCastleProvider.PROVIDER_NAME); // Use BC for the symmetric key operations
        decBytes = recipient.getContent(rec);
        break;
    }

    if (messageType == ScepRequestMessage.SCEP_TYPE_PKCSREQ) {
        pkcs10 = new JcaPKCS10CertificationRequest(decBytes);
        if (log.isDebugEnabled()) {
            log.debug("Successfully extracted PKCS10:" + new String(Base64.encode(pkcs10.getEncoded())));
        }
    }
    if (messageType == ScepRequestMessage.SCEP_TYPE_GETCRL) {
        ASN1InputStream derAsn1InputStream = new ASN1InputStream(new ByteArrayInputStream(decBytes));
        ASN1Primitive derobj = null;
        try {
            derobj = derAsn1InputStream.readObject();
        } finally {
            derAsn1InputStream.close();
        }
        issuerAndSerno = IssuerAndSerialNumber.getInstance(derobj);
        log.debug("Successfully extracted IssuerAndSerialNumber.");
    }
    if (log.isTraceEnabled()) {
        log.trace("<decrypt");
    }
}

From source file:org.ejbca.extra.db.ExtRAMsgHelper.java

License:Open Source License

/**
 * Method that should be used to decrypt data in a message.
 * // w  w w  .j  a v  a2s .c o m
 * Uses the algorithm specified in the init method.
 * 
 * @param decKey, the recipients private key.
 * @param encData, the encrypted data
 * @return encrypted byte[] or null if decryption failed.
 */
public static byte[] decryptData(PrivateKey decKey, byte[] encData) {
    byte[] retdata = null;
    try {
        CMSEnvelopedData ed = new CMSEnvelopedData(encData);

        RecipientInformationStore recipients = ed.getRecipientInfos();
        Iterator it = recipients.getRecipients().iterator();
        RecipientInformation recipient = (RecipientInformation) it.next();
        retdata = recipient.getContent(decKey, provider);
    } catch (Exception e) {
        log.error("Error decypting data : ", e);
    }

    return retdata;
}

From source file:org.ejbca.extra.ra.ProtocolScepHttpTest.java

License:Open Source License

private void checkScepResponse(byte[] retMsg, String senderNonce, String transId, boolean crlRep,
        String digestOid, boolean noca, ResponseStatus expectedResponseStatus)
        throws CMSException, NoSuchProviderException, NoSuchAlgorithmException, CertStoreException,
        InvalidKeyException, CertificateException, SignatureException, CRLException, IOException {
    ///*  w w w .j a va2s . c  o  m*/
    // Parse response message
    //
    CMSSignedData s = new CMSSignedData(retMsg);
    // The signer, i.e. the CA, check it's the right CA
    SignerInformationStore signers = s.getSignerInfos();
    Collection col = signers.getSigners();
    assertTrue(col.size() > 0);
    Iterator iter = col.iterator();
    SignerInformation signerInfo = (SignerInformation) iter.next();
    // Check that the message is signed with the correct digest alg
    assertEquals(signerInfo.getDigestAlgOID(), digestOid);
    SignerId sinfo = signerInfo.getSID();
    // Check that the signer is the expected CA
    assertEquals(CertTools.stringToBCDNString(racert.getIssuerDN().getName()),
            CertTools.stringToBCDNString(sinfo.getIssuerAsString()));
    // Verify the signature
    boolean ret = signerInfo.verify(racert.getPublicKey(), "BC");
    assertTrue(ret);
    // Get authenticated attributes
    AttributeTable tab = signerInfo.getSignedAttributes();
    // --Fail info
    Attribute attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_failInfo));
    // No failInfo on this success message
    if (expectedResponseStatus == ResponseStatus.SUCCESS) {
        assertNull(attr);
    }

    // --Message type
    attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_messageType));
    assertNotNull(attr);
    ASN1Set values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    DERString str = DERPrintableString.getInstance((values.getObjectAt(0)));
    String messageType = str.getString();
    assertEquals("3", messageType);
    // --Success status
    attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_pkiStatus));
    assertNotNull(attr);
    values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    str = DERPrintableString.getInstance((values.getObjectAt(0)));
    String responsestatus = str.getString();
    assertEquals(expectedResponseStatus.getValue(), responsestatus);
    // --SenderNonce
    attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_senderNonce));
    assertNotNull(attr);
    values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    ASN1OctetString octstr = ASN1OctetString.getInstance(values.getObjectAt(0));
    // SenderNonce is something the server came up with, but it should be 16 chars
    assertTrue(octstr.getOctets().length == 16);
    // --Recipient Nonce
    attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_recipientNonce));
    assertNotNull(attr);
    values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    octstr = ASN1OctetString.getInstance(values.getObjectAt(0));
    // recipient nonce should be the same as we sent away as sender nonce
    assertEquals(senderNonce, new String(Base64.encode(octstr.getOctets())));
    // --Transaction ID
    attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_transId));
    assertNotNull(attr);
    values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    str = DERPrintableString.getInstance((values.getObjectAt(0)));
    // transid should be the same as the one we sent
    assertEquals(transId, str.getString());

    //
    // Check different message types
    //        
    if (!responsestatus.equals(ResponseStatus.PENDING.getValue()) && messageType.equals("3")) {
        // First we extract the encrypted data from the CMS enveloped data contained
        // within the CMS signed data
        CMSProcessable sp = s.getSignedContent();
        byte[] content = (byte[]) sp.getContent();
        CMSEnvelopedData ed = new CMSEnvelopedData(content);
        RecipientInformationStore recipients = ed.getRecipientInfos();
        Collection c = recipients.getRecipients();
        assertEquals(c.size(), 1);
        Iterator it = c.iterator();
        byte[] decBytes = null;
        RecipientInformation recipient = (RecipientInformation) it.next();
        decBytes = recipient.getContent(keys.getPrivate(), "BC");
        // This is yet another CMS signed data
        CMSSignedData sd = new CMSSignedData(decBytes);
        // Get certificates from the signed data
        CertStore certstore = sd.getCertificatesAndCRLs("Collection", "BC");
        if (crlRep) {
            // We got a reply with a requested CRL
            Collection crls = certstore.getCRLs(null);
            assertEquals(crls.size(), 1);
            it = crls.iterator();
            X509CRL retCrl = null;
            // CRL is first (and only)
            retCrl = (X509CRL) it.next();
            log.info("Got CRL with DN: " + retCrl.getIssuerDN().getName());
            //                try {
            //                    FileOutputStream fos = new FileOutputStream("sceptest.der");
            //                    fos.write(retCrl.getEncoded());
            //                    fos.close();
            //                } catch (Exception e) {}
            // check the returned CRL
            assertEquals(cacert.getSubjectDN().getName(), retCrl.getIssuerDN().getName());
            retCrl.verify(cacert.getPublicKey());
        } else {
            // We got a reply with a requested certificate 
            Collection certs = certstore.getCertificates(null);
            log.info("Got certificate reply with certchain of length: " + certs.size());
            // EJBCA returns the issued cert and the CA cert (cisco vpn client requires that the ca cert is included)
            if (noca) {
                assertEquals(certs.size(), 1);
            } else {
                assertEquals(certs.size(), 2);
            }
            it = certs.iterator();
            // Issued certificate must be first
            boolean verified = false;
            boolean gotcacert = false;
            String mysubjectdn = CertTools.stringToBCDNString("C=SE,O=PrimeKey,CN=sceptest");
            X509Certificate usercert = null;
            while (it.hasNext()) {
                X509Certificate retcert = (X509Certificate) it.next();
                //                    try {
                //                        FileOutputStream fos = new FileOutputStream("sceptest.der");
                //                        fos.write(retcert.getEncoded());
                //                        fos.close();
                //                    } catch (Exception e) {}

                // check the returned certificate
                String subjectdn = CertTools.stringToBCDNString(retcert.getSubjectDN().getName());
                if (mysubjectdn.equals(subjectdn)) {
                    System.out.println("Got user cert with DN: " + retcert.getSubjectDN().getName());
                    // issued certificate
                    assertEquals(CertTools.stringToBCDNString("C=SE,O=PrimeKey,CN=sceptest"), subjectdn);
                    //System.out.println(retcert);
                    //System.out.println(cacert);
                    retcert.verify(cacert.getPublicKey());
                    assertTrue(checkKeys(keys.getPrivate(), retcert.getPublicKey()));
                    verified = true;
                    String altName = CertTools.getSubjectAlternativeName(retcert);
                    assertEquals("iPAddress=10.0.0.1, dNSName=foo.bar.com", altName);
                    usercert = retcert;
                } else {
                    log.info("Got CA cert with DN: " + retcert.getSubjectDN().getName());
                    // ca certificate
                    assertEquals(cacert.getSubjectDN().getName(), retcert.getSubjectDN().getName());
                    gotcacert = true;
                    usercert.verify(retcert.getPublicKey());
                }
            }
            assertTrue(verified);
            if (noca) {
                assertFalse(gotcacert);
            } else {
                assertTrue(gotcacert);
            }
        }
    }

}

From source file:org.identityconnectors.racf.BouncyCastlePEUtilities.java

License:Open Source License

protected byte[] decrypt(byte[] encrypted, X509Certificate certificate, PrivateKey key) {
    byte[] decrypted;
    try {//ww  w  . j  a v  a2s  . c  om
        CMSEnvelopedData enveloped = new CMSEnvelopedData(encrypted);

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

        decrypted = recipient.getContent(getPrivateKey(), "BC");
    } catch (NoSuchProviderException e) {
        throw ConnectorException.wrap(e);
    } catch (IOException e) {
        throw ConnectorException.wrap(e);
    } catch (CMSException e) {
        throw ConnectorException.wrap(e);
    }

    return decrypted;
}

From source file:org.jpedal.io.CertificateReader.java

License:Open Source License

public static byte[] readCertificate(final byte[][] recipients, final Certificate certificate, final Key key) {

    byte[] envelopedData = null;

    /**//from  ww w . ja v a2  s  . com
     * values for BC
     */
    final String provider = "BC";

    /**
     * loop through all and get data if match found
     */
    for (final byte[] recipient : recipients) {

        try {
            final CMSEnvelopedData recipientEnvelope = new CMSEnvelopedData(recipient);

            final Object[] recipientList = recipientEnvelope.getRecipientInfos().getRecipients().toArray();
            final int listCount = recipientList.length;

            for (int ii = 0; ii < listCount; ii++) {
                final RecipientInformation recipientInfo = (RecipientInformation) recipientList[ii];

                if (recipientInfo.getRID().match(certificate)) {
                    envelopedData = recipientInfo.getContent(key, provider);
                    ii = listCount;
                }
            }
        } catch (final Exception e) {
            //tell user and log
            if (LogWriter.isOutput()) {
                LogWriter.writeLog("Exception: " + e.getMessage());
            }
            //
        }
    }

    return envelopedData;
}

From source file:org.jpedal.io.security.BouncyCastleDecryption.java

License:Open Source License

@Override
public byte[] readCertificate(final byte[][] recipients, final Certificate certificate, final Key key) {

    byte[] envelopedData = null;

    final String provider = "BC";

    /*/*from  w  w  w .  j a  v a 2 s  .c om*/
     * loop through all and get data if match found
     */
    for (final byte[] recipient : recipients) {

        try {
            final CMSEnvelopedData recipientEnvelope = new CMSEnvelopedData(recipient);

            final Object[] recipientList = recipientEnvelope.getRecipientInfos().getRecipients().toArray();
            final int listCount = recipientList.length;

            for (int ii = 0; ii < listCount; ii++) {
                final RecipientInformation recipientInfo = (RecipientInformation) recipientList[ii];

                if (recipientInfo.getRID().match(certificate)) {
                    envelopedData = recipientInfo.getContent(key, provider);
                    ii = listCount;
                }
            }
        } catch (final Exception e) {
            LogWriter.writeLog("Exception: " + e.getMessage());
        }
    }

    return envelopedData;
}

From source file:org.neociclo.odetteftp.util.EnvelopingUtil.java

License:Apache License

/**
 * Return null if certificate's recipientId could not be found within the
 * encoded envelope - typically when using a bad certificate to decrypt the
 * authentication challenge encrypted using other public certificate.
 * /*from w  w w .  j ava2  s .  c o  m*/
 * @param encoded
 * @param cert
 * @param key
 * @return
 * @throws NoSuchProviderException
 * @throws CMSException
 * @throws IOException
 */
public static byte[] parseEnvelopedData(byte[] encoded, X509Certificate cert, PrivateKey key)
        throws NoSuchProviderException, CMSException, IOException {

    installBouncyCastleProviderIfNecessary();

    byte[] data = null;

    CMSEnvelopedData enveloped = new CMSEnvelopedData(encoded);

    // TODO validate the receiving enveloped-data against supported
    // algorithms

    // look for our recipient identifier
    RecipientId recId = new org.bouncycastle.cms.KeyTransRecipientId(
            new X500Name(cert.getIssuerX500Principal().getName()), cert.getSerialNumber());

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

    if (recipient != null) {
        // decrypt the data
        data = recipient.getContent(key, BC_PROVIDER);
    }

    return data;

}

From source file:org.sejda.sambox.pdmodel.encryption.PublicKeySecurityHandler.java

License:Apache License

/**
 * Prepares everything to decrypt the document.
 *
 * @param encryption encryption dictionary, can be retrieved via
 * {@link PDDocument#getEncryption()}/*from   www.ja  va 2 s .  c o  m*/
 * @param documentIDArray document id which is returned via
 * {@link org.apache.pdfbox.cos.COSDocument#getDocumentID()} (not used by
 * this handler)
 * @param decryptionMaterial Information used to decrypt the document.
 *
 * @throws IOException If there is an error accessing data. If verbose mode
 * is enabled, the exception message will provide more details why the
 * match wasn't successful.
 */
@Override
public void prepareForDecryption(PDEncryption encryption, COSArray documentIDArray,
        DecryptionMaterial decryptionMaterial) throws IOException {
    if (!(decryptionMaterial instanceof PublicKeyDecryptionMaterial)) {
        throw new IOException("Provided decryption material is not compatible with the document");
    }

    setDecryptMetadata(encryption.isEncryptMetaData());
    if (encryption.getLength() != 0) {
        this.keyLength = encryption.getLength();
    }

    PublicKeyDecryptionMaterial material = (PublicKeyDecryptionMaterial) decryptionMaterial;

    try {
        boolean foundRecipient = false;

        // the decrypted content of the enveloped data that match
        // the certificate in the decryption material provided
        byte[] envelopedData = null;

        // the bytes of each recipient in the recipients array
        byte[][] recipientFieldsBytes = new byte[encryption.getRecipientsLength()][];

        int recipientFieldsLength = 0;
        int i = 0;
        StringBuilder extraInfo = new StringBuilder();
        for (; i < encryption.getRecipientsLength(); i++) {
            COSString recipientFieldString = encryption.getRecipientStringAt(i);
            byte[] recipientBytes = recipientFieldString.getBytes();
            CMSEnvelopedData data = new CMSEnvelopedData(recipientBytes);
            Iterator<?> recipCertificatesIt = data.getRecipientInfos().getRecipients().iterator();
            int j = 0;
            while (recipCertificatesIt.hasNext()) {
                RecipientInformation ri = (RecipientInformation) recipCertificatesIt.next();
                // Impl: if a matching certificate was previously found it is an error,
                // here we just don't care about it
                X509Certificate certificate = material.getCertificate();
                X509CertificateHolder materialCert = null;
                if (null != certificate) {
                    materialCert = new X509CertificateHolder(certificate.getEncoded());
                }
                RecipientId rid = ri.getRID();
                if (rid.match(materialCert) && !foundRecipient) {
                    foundRecipient = true;
                    PrivateKey privateKey = (PrivateKey) material.getPrivateKey();
                    envelopedData = ri
                            .getContent(new JceKeyTransEnvelopedRecipient(privateKey).setProvider("BC"));
                    break;
                }
                j++;
                if (certificate != null) {
                    extraInfo.append('\n');
                    extraInfo.append(j);
                    extraInfo.append(": ");
                    if (rid instanceof KeyTransRecipientId) {
                        appendCertInfo(extraInfo, (KeyTransRecipientId) rid, certificate, materialCert);
                    }
                }
            }
            recipientFieldsBytes[i] = recipientBytes;
            recipientFieldsLength += recipientBytes.length;
        }
        if (!foundRecipient || envelopedData == null) {
            throw new IOException(
                    "The certificate matches none of " + i + " recipient entries" + extraInfo.toString());
        }
        if (envelopedData.length != 24) {
            throw new IOException("The enveloped data does not contain 24 bytes");
        }
        // now envelopedData contains:
        // - the 20 bytes seed
        // - the 4 bytes of permission for the current user

        byte[] accessBytes = new byte[4];
        System.arraycopy(envelopedData, 20, accessBytes, 0, 4);

        AccessPermission currentAccessPermission = new AccessPermission(accessBytes);
        currentAccessPermission.setReadOnly();
        setCurrentAccessPermission(currentAccessPermission);

        // what we will put in the SHA1 = the seed + each byte contained in the recipients array
        byte[] sha1Input = new byte[recipientFieldsLength + 20];

        // put the seed in the sha1 input
        System.arraycopy(envelopedData, 0, sha1Input, 0, 20);

        // put each bytes of the recipients array in the sha1 input
        int sha1InputOffset = 20;
        for (byte[] recipientFieldsByte : recipientFieldsBytes) {
            System.arraycopy(recipientFieldsByte, 0, sha1Input, sha1InputOffset, recipientFieldsByte.length);
            sha1InputOffset += recipientFieldsByte.length;
        }

        MessageDigest md = MessageDigests.getSHA1();
        byte[] mdResult = md.digest(sha1Input);

        // we have the encryption key ...
        encryptionKey = new byte[this.keyLength / 8];
        System.arraycopy(mdResult, 0, encryptionKey, 0, this.keyLength / 8);
    } catch (CMSException e) {
        throw new IOException(e);
    } catch (KeyStoreException e) {
        throw new IOException(e);
    } catch (CertificateEncodingException e) {
        throw new IOException(e);
    }
}

From source file:org.silverpeas.core.security.encryption.cipher.CMSCipher.java

License:Open Source License

/**
 * Decrypt the specified code or cipher by using the specified cryptographic key.
 * <p>/*from   ww  w . j a v  a 2s  .c om*/
 * The String objects handled by the encryption is done according the UTF-8 charset.
 * @param encryptedData the data in bytes that was encrypted by this cipher.
 * @param keyFilePath the file in which is stored the secret key to use in the decryption.
 * @return the decrypted data.
 */
@Override
public String decrypt(byte[] encryptedData, CipherKey keyFilePath) throws CryptoException {
    try {
        // Dchiffrement de la chaine
        CMSEnvelopedData ced = new CMSEnvelopedData(encryptedData);
        @SuppressWarnings("unchecked")
        Collection<RecipientInformation> recip = ced.getRecipientInfos().getRecipients();

        RecipientInformation rinfo = recip.iterator().next();
        // privatekey est la cl prive permettant de dchiffrer la cl
        // secrte (symtrique)
        if (!keyFilePath.isInFile()) {
            throw new FileNotFoundException("The PKS#12 file '" + keyFilePath + "' doesn't exist!");
        }
        PKS12KeyStoreWallet wallet = PKS12KeyStoreWallet.getInstance();
        PKS12KeyStore keyStore = wallet.getKeyStore(keyFilePath.getKeyFilePath());
        byte[] contents = rinfo.getContent(new JceKeyTransEnvelopedRecipient(keyStore.getPrivatekey()));
        return byteArrayToString(contents);
    } catch (CryptoException e) {
        throw e;
    } catch (Exception e) {
        throw new CryptoException(CryptoException.DECRYPTION_FAILURE, e);
    }
}

From source file:org.silverpeas.util.crypto.CMSCipher.java

License:Open Source License

/**
 * Decrypt the specified code or cipher by using the specified cryptographic key.
 * <p/>/*from   ww  w. j  a va2  s . c o m*/
 * The String objects handled by the encryption is done according the UTF-8 charset.
 * @param encryptedData the data in bytes that was encrypted by this cipher.
 * @param keyFilePath the file in which is stored the secret key to use in the decryption.
 * @return the decrypted data.
 */
@Override
public String decrypt(byte[] encryptedData, CipherKey keyFilePath) throws CryptoException {
    try {
        // Dchiffrement de la chaine
        CMSEnvelopedData ced = new CMSEnvelopedData(encryptedData);
        @SuppressWarnings("unchecked")
        Collection<KeyTransRecipientInformation> recip = ced.getRecipientInfos().getRecipients();

        KeyTransRecipientInformation rinfo = recip.iterator().next();
        // privatekey est la cl prive permettant de dchiffrer la cl
        // secrte (symtrique)
        if (!keyFilePath.isInFile()) {
            throw new FileNotFoundException("The PKS#12 file '" + keyFilePath + "' doesn't exist!");
        }
        PKS12KeyStoreWallet wallet = PKS12KeyStoreWallet.getInstance();
        PKS12KeyStore keyStore = wallet.getKeyStore(keyFilePath.getKeyFilePath());
        byte[] contents = rinfo.getContent(new JceKeyTransEnvelopedRecipient(keyStore.getPrivatekey()));
        return byteArrayToString(contents);
    } catch (CryptoException e) {
        throw e;
    } catch (Exception e) {
        throw new CryptoException(CryptoException.DECRYPTION_FAILURE, e);
    }
}