List of usage examples for org.bouncycastle.cms CMSEnvelopedDataParser getRecipientInfos
public RecipientInformationStore getRecipientInfos()
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 w w w . j a v a 2 s. co 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: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 2 s.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:no.difi.sdp.client.internal.CreateCMSDocumentTest.java
License:Apache License
@Test public void test_can_be_decrypted_by_recipient() throws Exception { CMSDocument cms = sut.createCMS("message".getBytes(), sertifikat); CMSEnvelopedDataParser cmsEnvelopeParser = new CMSEnvelopedDataParser(cms.getBytes()); JceKeyTransEnvelopedRecipient keyDecoder = new JceKeyTransEnvelopedRecipient(privateKey); RecipientInformation recInfo = (RecipientInformation) cmsEnvelopeParser.getRecipientInfos().getRecipients() .iterator().next();/*from w ww.java 2 s . com*/ byte[] decryptedContent = recInfo.getContent(keyDecoder); assertThat(decryptedContent).isEqualTo("message".getBytes()); }
From source file:org.cryptable.pki.communication.PKICMPMessagesTest.java
License:Open Source License
/** * Check the private key archive control in the certification request * * @throws OperatorCreationException// w w w. j a v a 2s. c o m * @throws PKICMPMessageException * @throws CertificateEncodingException * @throws IOException * @throws CRMFException * @throws CMPException * @throws CMSException */ @Test public void testCertificationWithPrivateKeyControl() throws OperatorCreationException, PKICMPMessageException, CertificateException, IOException, CRMFException, CMPException, CMSException, InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchFieldException, IllegalAccessException, CRLException { String distinguishedName = pki.getTestUser1Cert().getSubjectX500Principal().getName(); KeyPair keyPair = new KeyPair(pki.getTestUser1Cert().getPublicKey(), pki.getTestUser1CertPrivateKey()); PKICMPMessages pkiMessages = new PKICMPMessages(); pkiMessages.setPkiKeyStore(pkiKeyStoreRA); byte[] result = pkiMessages.createCertificateMessageWithLocalKey(distinguishedName, keyPair); ASN1InputStream asn1InputStream = new ASN1InputStream(result); ASN1Primitive asn1Primitive = asn1InputStream.readObject(); PKIMessage pkiMessage = PKIMessage.getInstance(asn1Primitive); CertReqMsg[] certReqMsgs = CertReqMessages.getInstance(pkiMessage.getBody().getContent()) .toCertReqMsgArray(); AttributeTypeAndValue[] attributeTypeAndValues = certReqMsgs[0].getCertReq().getControls() .toAttributeTypeAndValueArray(); GeneratePKI genPKI = new GeneratePKI(); genPKI.createPKI(); boolean bFound = false; for (AttributeTypeAndValue attributeTypeAndValue : attributeTypeAndValues) { if (attributeTypeAndValue.getType().equals(CRMFObjectIdentifiers.id_regCtrl_pkiArchiveOptions)) { PKIArchiveControl pkiArchiveControl = new PKIArchiveControl( PKIArchiveOptions.getInstance(attributeTypeAndValue.getValue())); // Decrypt data CMSEnvelopedDataParser cmsEnvelopedDataParser = new CMSEnvelopedDataParser( pkiArchiveControl.getEnvelopedData().getEncoded()); RecipientInformationStore recipients = cmsEnvelopedDataParser.getRecipientInfos(); Collection c = recipients.getRecipients(); Iterator it = c.iterator(); if (it.hasNext()) { RecipientInformation recipient = (RecipientInformation) it.next(); byte[] recdata = recipient .getContent(new JceKeyTransEnvelopedRecipient(genPKI.getSubCACertPrivateKey()) .setProvider(pkiKeyStoreRA.getProvider())); ASN1InputStream tstAsn1InputStream = new ASN1InputStream(recdata); ASN1Primitive tstAsn1Primitive = tstAsn1InputStream.readObject(); EncKeyWithID encKeyWithID = EncKeyWithID.getInstance(tstAsn1Primitive); Assert.assertArrayEquals(keyPair.getPrivate().getEncoded(), encKeyWithID.getPrivateKey().getEncoded()); Assert.assertTrue(encKeyWithID.hasIdentifier()); GeneralName identifier = GeneralName.getInstance(encKeyWithID.getIdentifier()); Assert.assertEquals(genPKI.getTestUser1Cert().getSubjectDN().getName(), identifier.getName().toString()); bFound = true; } } } Assert.assertTrue(bFound); }
From source file:org.neociclo.odetteftp.util.EnvelopingUtil.java
License:Apache License
/** * /*from ww w . j av a2 s . co m*/ * @param cryptData * InputStream of encapsulated encrypted data * @param cert * user secure certificate used to match the recipient identifier * @param key * user private key used to decrypt the encapsulated data * @return InputStream the original data stream (decrypted) * @throws CMSException * @throws IOException * @throws NoSuchProviderException */ public static InputStream openEnvelopedDataParser(InputStream cryptData, X509Certificate cert, PrivateKey key) throws CMSException, IOException, NoSuchProviderException { installBouncyCastleProviderIfNecessary(); // set up the parser CMSEnvelopedDataParser ep = new CMSEnvelopedDataParser(cryptData); // 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 = ep.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); if (recipient != null) { // return the decrypting parser InputStream InputStream parserStream = recipient.getContentStream(key, BC_PROVIDER).getContentStream(); return parserStream; } // TODO raise a kind of invalid certificate exception instead of null // or recipient not found return null; }
From source file:org.neociclo.odetteftp.util.EnvelopingUtil.java
License:Apache License
public static void parseEnvelopedDataContentStream(InputStream envelopedStream, OutputStream outStream, X509Certificate cert, PrivateKey key) throws NoSuchProviderException, CMSException, IOException { installBouncyCastleProviderIfNecessary(); // use the CMS parser to decrypt the EnvelopedData CMSEnvelopedDataParser parser = new CMSEnvelopedDataParser(envelopedStream); // 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 = parser.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); if (recipient != null) { // decrypt the data InputStream unenveloped = recipient.getContentStream(key, BC_PROVIDER).getContentStream(); IoUtil.copyStream(unenveloped, outStream); }//from w ww .j ava 2s. c o m }
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 ww w . j a v a2 s. c om 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();/*from w w w.ja v a2 s.c om*/ 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; }
From source file:org.votingsystem.signature.util.Encryptor.java
License:Open Source License
public static byte[] decryptCMSStream(PrivateKey privateKey, byte[] cmsEncryptedData) throws Exception { CMSEnvelopedDataParser ep = new CMSEnvelopedDataParser(cmsEncryptedData); RecipientInformationStore recipients = ep.getRecipientInfos(); Collection c = recipients.getRecipients(); Iterator it = c.iterator();/*from www.j a v a2 s . c om*/ 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)); InputStream dataStream = recData.getContentStream(); ByteArrayOutputStream dataOut = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; int len = 0; while ((len = dataStream.read(buf)) >= 0) { dataOut.write(buf, 0, len); } dataOut.close(); result = dataOut.toByteArray(); //assertEquals(true, Arrays.equals(data, dataOut.toByteArray())); } return result; }
From source file:test.integ.be.e_contract.mycarenet.etee.SealTest.java
License:Open Source License
@Test public void testSeal() throws Exception { InputStream sealInputStream = SealTest.class.getResourceAsStream("/seal-fcorneli.der"); assertNotNull(sealInputStream);// ww w . j a v a2 s . c om byte[] cmsData = IOUtils.toByteArray(sealInputStream); // check outer signature byte[] data = getVerifiedContent(cmsData); // decrypt content CMSEnvelopedDataParser cmsEnvelopedDataParser = new CMSEnvelopedDataParser(data); LOG.debug("content encryption algo: " + cmsEnvelopedDataParser.getContentEncryptionAlgorithm().getAlgorithm().getId()); RecipientInformationStore recipientInformationStore = cmsEnvelopedDataParser.getRecipientInfos(); Collection<RecipientInformation> recipients = recipientInformationStore.getRecipients(); RecipientInformation recipientInformation = recipients.iterator().next(); LOG.debug("recipient info type: " + recipientInformation.getClass().getName()); KeyTransRecipientInformation keyTransRecipientInformation = (KeyTransRecipientInformation) recipientInformation; // load eHealth encryption certificate KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12"); FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path()); eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray()); Enumeration<String> aliasesEnum = eHealthKeyStore.aliases(); aliasesEnum.nextElement(); // skip authentication certificate. String alias = aliasesEnum.nextElement(); X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias); PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias, this.config.getEHealthPKCS12Password().toCharArray()); AsymmetricKeyParameter privKeyParams = PrivateKeyFactory.createKey(eHealthPrivateKey.getEncoded()); BcRSAKeyTransEnvelopedRecipient recipient = new BcRSAKeyTransEnvelopedRecipient(privKeyParams); byte[] decryptedContent = recipientInformation.getContent(recipient); assertNotNull(decryptedContent); LOG.debug("decrypted content size: " + decryptedContent.length); byte[] result = getVerifiedContent(decryptedContent); LOG.debug("result: " + new String(result)); }