List of usage examples for org.bouncycastle.cms RecipientId RecipientId
RecipientId
From source file:com.cordys.coe.ac.emailio.keymanager.BCKeyManagerImpl.java
License:Apache License
/** * Adapter method that is called after the parameters are parsed. * * @param ecConfiguration The Email IO Connector configuration * @param iConfigurationNode The XML containing the configuration of the key manager. * @param xmi The XPath meta info to use. The prefix ns should be mapped to * the proper namespace. * @param cvValidator The certificate validator to use. * * @throws KeyManagerException In case of any exceptions. * * @see com.cordys.coe.ac.emailio.keymanager.AbstractKeyManager#postInit(com.cordys.coe.ac.emailio.config.IEmailIOConfiguration, * int, com.eibus.xml.xpath.XPathMetaInfo, * com.cordys.coe.ac.emailio.keymanager.ICertificateValidator) *//* w ww.j ava 2s . c o m*/ @Override protected void postInit(IEmailIOConfiguration ecConfiguration, int iConfigurationNode, XPathMetaInfo xmi, ICertificateValidator cvValidator) throws KeyManagerException { m_keyStore = null; File keyStoreFile = new File(getLocation()); // Check the parameters. if (keyStoreFile == null) { throw new KeyManagerException(KeyManagerExceptionMessages.KME_KEYSTORE_MUST_BE_PRESENT); } if (!keyStoreFile.exists()) { throw new KeyManagerException(KeyManagerExceptionMessages.KME_KEYSTORE_0_COULD_NOT_BE_FOUND, keyStoreFile); } if (Security.getProvider(PROVIDER_BOUNCY_CASTLE) == null) { throw new KeyManagerException(KeyManagerExceptionMessages.KME_THE_BOUNCY_CASTLE_PROVIDER_WAS_NOT_FOUND); } // Load the Keystore try { if ("PKCS12".equals(getType())) { m_keyStore = KeyStore.getInstance(getType(), PROVIDER_BOUNCY_CASTLE); } else { m_keyStore = KeyStore.getInstance(getType()); } } catch (Exception e) { throw new KeyManagerException(e, KeyManagerExceptionMessages.KME_ERROR_CREATING_KEYSTORE_OF_TYPE_0_FOR_PROVIDER_1, getType(), PROVIDER_BOUNCY_CASTLE); } // Now load the actual keystore. try { char[] password = new char[0]; if (getPassword() != null) { password = getPassword().toCharArray(); } m_keyStore.load(new FileInputStream(keyStoreFile), password); } catch (Exception e) { throw new KeyManagerException(e, KeyManagerExceptionMessages.KME_ERROR_LOADING_THE_KEYSTORE_0, keyStoreFile.getPath()); } // Load the optional individual certificate passwords Map<String, String> certificatePasswords = getCertificatePasswords(xmi); // Now load all certificates in this keystore. try { Enumeration<String> e = m_keyStore.aliases(); while (e.hasMoreElements()) { String alias = e.nextElement(); if (LOG.isDebugEnabled()) { LOG.debug("Processing key with alias: " + alias); } MailIdentityInfo mii = new MailIdentityInfo(); mii.setAlias(alias); // This is a key pair, so this can be used for encryption. X509Certificate cert = (X509Certificate) m_keyStore.getCertificate(alias); mii.setX509Certificate(cert); // Do the recipient ID RecipientId recipientID = new RecipientId(); recipientID.setSerialNumber(cert.getSerialNumber()); recipientID.setIssuer(cert.getIssuerX500Principal().getEncoded()); mii.setRecipientId(recipientID); Map<String, ICertificateInfo> storage = null; if (m_keyStore.isKeyEntry(alias)) { // It could be that this key has another password. char[] certPassword = null; if (certificatePasswords.containsKey(alias)) { certPassword = certificatePasswords.get(alias).toCharArray(); } mii.setKey((PrivateKey) m_keyStore.getKey(alias, certPassword)); storage = m_encryptionCertificates; } else { storage = m_verificationCertificates; } String storageKey = alias; // Get the email address from the certificate. For now we'll assume it has to be in // the subject. Map<ESubjectDNField, String> fields = CertificateUtil.getSubjectFields(cert); String emailAddress = fields.get(ESubjectDNField.EMAIL_ADDRESS); if (emailAddress != null) { mii.setEmailAddress(emailAddress); storageKey = emailAddress; } // Validate the certificate for the current usage if (((m_validator != null) && m_validator.isValid()) || (m_validator == null)) { if (LOG.isDebugEnabled()) { LOG.debug("Storing certificate with alias " + alias + " under email address " + storageKey); } storage.put(storageKey, mii); m_recipientCertificates.put(recipientID, mii); } else if (LOG.isDebugEnabled()) { LOG.debug("Certificate " + alias + " is invalid."); } } } catch (Exception e) { throw new KeyManagerException(e, KeyManagerExceptionMessages.KME_ERROR_GETTING_ALL_CERTIFICATES_IN_THE_KEYSTORE); } }
From source file:com.cordys.coe.ac.emailio.sample.GenLDAPConnectorKeyManager.java
License:Apache License
/** * @see com.cordys.coe.ac.emailio.keymanager.IKeyManager#getCertificateInfo(java.lang.String) */// ww w. j ava2 s .c o m @Override public ICertificateInfo getCertificateInfo(String sEmailAddress) throws KeyManagerException { ICertificateInfo ciReturn = null; // First see if we are caching certs and if the cert is available if (getCacheCertificates() && m_mLocalCache.containsKey(sEmailAddress)) { if (LOG.isDebugEnabled()) { LOG.debug("Using certificate which is already in the cache."); } ciReturn = m_mLocalCache.get(sEmailAddress); } else { // It's not in the cache, so we need to get it from LDAP. byte[] baCertificate = getProperCertificate(sEmailAddress); if ((baCertificate != null) && (baCertificate.length > 0)) { // Load the certificate ByteArrayInputStream bais = new ByteArrayInputStream(baCertificate); X509Certificate xcCertificate = CertificateUtil.loadCertificate(bais); // Create the certificate info object MailIdentityInfo mii = new MailIdentityInfo(); mii.setAlias(sEmailAddress); mii.setEmailAddress(sEmailAddress); mii.setX509Certificate(xcCertificate); // Do the recipient ID RecipientId recipientID = new RecipientId(); recipientID.setSerialNumber(xcCertificate.getSerialNumber()); try { recipientID.setIssuer(xcCertificate.getIssuerX500Principal().getEncoded()); } catch (IOException e) { throw new KeyManagerException(e, KeyManagerExceptionMessages.KME_ERROR_SETTING_THE_ISSUER_FOR_CERTIFICATE_WITH_SUBJECT_0, xcCertificate.getSubjectDN().toString()); } mii.setRecipientId(recipientID); if (getCacheCertificates()) { // Cache the certificate m_mLocalCache.put(sEmailAddress, mii); } ciReturn = mii; } } return ciReturn; }
From source file:gov.nih.nci.cacis.nav.DecryptMail.java
License:BSD License
/** * Decrypts the encrypted MimeMessage based on supplied key * /* ww w.j ava2 s . c o m*/ * @param msg - encrypte MimeMessage * @param keystorepath - keystore to be used * @param storepass - keystore password (same as key) * @param keyAlias - alias for the key to be used * @return - Decrypted MimeBodyPart * @throws Exception - exception thrown, if any */ public MimeBodyPart decrypt(MimeMessage msg, String keystorepath, String storepass, String keyAlias) throws Exception { // NOPMD // // Open the key store // final KeyStore ks = KeyStore.getInstance(STORE_TYPE, PROVIDER_TYPE); // final InputStream is = getClass().getClassLoader().getResourceAsStream(keystorePath); final InputStream is = new FileInputStream(keystorepath); ks.load(is, storepass.toCharArray()); // // find the certificate for the private key and generate a // suitable recipient identifier. // final X509Certificate cert = (X509Certificate) ks.getCertificate(keyAlias); final RecipientId recId = new RecipientId(); recId.setSerialNumber(cert.getSerialNumber()); recId.setIssuer(cert.getIssuerX500Principal().getEncoded()); final SMIMEEnveloped m = new SMIMEEnveloped(msg); final RecipientInformationStore recipients = m.getRecipientInfos(); final RecipientInformation recipient = recipients.get(recId); final MimeBodyPart res = SMIMEUtil .toMimeBodyPart(recipient.getContent(ks.getKey(keyAlias, null), PROVIDER_TYPE)); LOG.debug("Message Contents"); LOG.debug("----------------"); LOG.debug(res.getContent()); return res; }
From source file:hk.hku.cecid.edi.as2.module.test.OutgoingMessageProcessorTest.java
License:Open Source License
@Test public void testEncrytedAS2Message() throws Exception { InputStream ins = FIXTURE_LOADER.getResourceAsStream(MOCK_AS2_MSG); ByteArrayInputStream bIns = new ByteArrayInputStream(IOHandler.readBytes(ins)); String mid = RANDOM.toString(); partnershipDVO.setIsOutboundEncryptRequired(true); AS2Message as2Msg = TARGET.storeOutgoingMessage(mid, //MessageID "xml", partnershipDVO, new InputStreamDataSource(bIns, "xml", MOCK_AS2_MSG)); // Decrypt Message SMIMEEnveloped crypted = new SMIMEEnveloped(as2Msg.getBodyPart()); RecipientId recId = new RecipientId(); recId.setSerialNumber(partnershipDVO.getEncryptX509Certificate().getSerialNumber()); recId.setIssuer(partnershipDVO.getEncryptX509Certificate().getIssuerX500Principal().getEncoded()); RecipientInformationStore recipients = crypted.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); KeyStoreManager keyMan = (KeyStoreManager) TARGET.getSystemModule().getComponent("keystore-manager"); MimeBodyPart decrpted = SMIMEUtil.toMimeBodyPart(recipient.getContent(keyMan.getPrivateKey(), "BC")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOHandler.pipe(decrpted.getDataHandler().getInputStream(), baos); byte[] decrptedBA = baos.toByteArray(); byte[] originalBA = IOHandler.readBytes(FIXTURE_LOADER.getResourceAsStream(MOCK_AS2_MSG)); Assert.assertTrue(Arrays.equals(decrptedBA, originalBA)); //Assert the filename String filenameHdr = decrpted.getHeader("Content-Disposition")[0]; Assert.assertEquals("Filename value lost in BodyPartHeader", MOCK_AS2_MSG, getFileName(filenameHdr)); //Verify MIC/*from w w w.j av a 2 s .co m*/ ByteArrayOutputStream contentStream = new ByteArrayOutputStream(); decrpted.writeTo(contentStream); byte[] content = (contentStream.toByteArray()); String mic = calculateMIC(content); Assert.assertEquals("MIC Value is not valid.", mic, getStoredMessage(mid).getMicValue()); }
From source file:hk.hku.cecid.edi.as2.module.test.OutgoingMessageProcessorTest.java
License:Open Source License
@Test public void testSignedEncryptedAS2Message() throws Exception { InputStream ins = FIXTURE_LOADER.getResourceAsStream(MOCK_AS2_MSG); ByteArrayInputStream bIns = new ByteArrayInputStream(IOHandler.readBytes(ins)); // Prepare Data String mid = RANDOM.toString(); partnershipDVO.setIsOutboundEncryptRequired(true); partnershipDVO.setIsOutboundSignRequired(true); //Encrypt message AS2Message as2Msg = TARGET.storeOutgoingMessage(mid, //MessageID "xml", partnershipDVO, new InputStreamDataSource(bIns, "xml", MOCK_AS2_MSG)); // Decrypt Message SMIMEEnveloped crypted = new SMIMEEnveloped(as2Msg.getBodyPart()); RecipientId recId = new RecipientId(); recId.setSerialNumber(partnershipDVO.getEncryptX509Certificate().getSerialNumber()); recId.setIssuer(partnershipDVO.getEncryptX509Certificate().getIssuerX500Principal().getEncoded()); RecipientInformationStore recipients = crypted.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); KeyStoreManager keyMan = (KeyStoreManager) TARGET.getSystemModule().getComponent("keystore-manager"); MimeBodyPart decrpted = SMIMEUtil.toMimeBodyPart(recipient.getContent(keyMan.getPrivateKey(), "BC")); //Verify Signature try {// w ww . jav a 2 s .co m SMIMESigned signed = new SMIMESigned((MimeMultipart) decrpted.getContent()); SignerInformationStore signers = signed.getSignerInfos(); Iterator signerInfos = signers.getSigners().iterator(); while (signerInfos.hasNext()) { SignerInformation signerInfo = (SignerInformation) signerInfos.next(); if (!signerInfo.verify(partnershipDVO.getEffectiveVerifyCertificate(), "BC")) { Assert.fail("Signature Verfifcation Failed"); } } //Assert the filename value MimeBodyPart signedPart = signed.getContent(); String filenameHdr = signedPart.getHeader("Content-Disposition")[0]; Assert.assertEquals("Lost Filename Header Information", MOCK_AS2_MSG, getFileName(filenameHdr)); // Verify MIC Value ByteArrayOutputStream baos = new ByteArrayOutputStream(); signedPart.writeTo(baos); byte[] content = (baos.toByteArray()); String mic = calculateMIC(content); MessageDVO msgDVO = getStoredMessage(mid); Assert.assertEquals("MIC Value is not valid.", mic, msgDVO.getMicValue()); } catch (Exception exp) { Assert.fail("Signature Verfifcation Failed"); } Assert.assertTrue(true); }
From source file:hk.hku.cecid.piazza.commons.security.SMimeMessage.java
License:Open Source License
/** * Decrypts the encapsulated MIME body part. * /* w w w .ja v a 2s .co m*/ * @param privateKey the private key for decryption. * @return an S/MIME message encapsulating the decrypted MIME body part. * @throws SMimeException if unable to decrpyt the body part. */ public SMimeMessage decrypt(PrivateKey privateKey) throws SMimeException { if (privateKey == null) { throw new SMimeException("Private key not found"); } try { setDefaults(); SMIMEEnveloped m = new SMIMEEnveloped(bodyPart); RecipientId recId = new RecipientId(); recId.setSerialNumber(cert.getSerialNumber()); recId.setIssuer(cert.getIssuerX500Principal().getEncoded()); RecipientInformationStore recipients = m.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); if (recipient == null) { throw new SMimeException("Invalid encrypted content"); } ByteArrayInputStream ins = new ByteArrayInputStream(recipient.getContent(privateKey, "BC")); MimeBodyPart decryptedPart = new MimeBodyPart(ins); return new SMimeMessage(decryptedPart, this); } catch (Exception e) { throw new SMimeException("Unable to decrypt body part", e); } }
From source file:org.identityconnectors.racf.BouncyCastlePEUtilities.java
License:Open Source License
private RecipientId getRecipientId(X509Certificate certificate) throws IOException { RecipientId recId = new RecipientId(); recId.setSerialNumber(certificate.getSerialNumber()); recId.setIssuer(certificate.getIssuerX500Principal().getEncoded()); return recId; }
From source file:org.mailster.core.crypto.smime.SmimeUtilities.java
License:Open Source License
/** * Try to decrypt the provided envelope with the provided certificate * and private key. //from w w w . j ava 2s . c o m */ public static MimeBodyPart decryptEnvelope(SMIMEEnveloped enveloped, Key key, X509Certificate cert) throws Exception { // look for our recipient identifier RecipientId recId = new RecipientId(); recId.setSerialNumber(cert.getSerialNumber()); recId.setIssuer(cert.getIssuerX500Principal().getEncoded()); RecipientInformationStore recipients = enveloped.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); // decryption step if (recipient != null) return SMIMEUtil.toMimeBodyPart(recipient.getContent(key, "BC")); else return null; }
From source file:org.openhealthtools.openatna.net.MailConnection.java
License:Apache License
public MimeBodyPart decryptMessage(Message message) throws MessagingException { try {//from www .j a v a 2 s . c o m /* Add BC */ Security.addProvider(new BouncyCastleProvider()); // Open the key store KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(new FileInputStream(getSenderKeystoreFile()), getSenderKeystorePassword().toCharArray()); // find the certificate for the private key and generate a // suitable recipient identifier. X509Certificate cert = (X509Certificate) ks.getCertificate(getSenderKeyAlias()); RecipientId recId = new RecipientId(); recId.setSerialNumber(cert.getSerialNumber()); recId.setIssuer(cert.getIssuerX500Principal().getEncoded()); SMIMEEnveloped m = new SMIMEEnveloped((MimeMessage) message); RecipientInformationStore recipients = m.getRecipientInfos(); // TODO figure out why this doesn't work... //RecipientInformation recipient = recipients.get(recId); RecipientInformation recipient = (RecipientInformation) recipients.getRecipients().iterator().next(); Key key = ks.getKey(getSenderKeyAlias(), getSenderKeystorePassword().toCharArray()); byte[] byteContent = recipient.getContent(key, "BC"); MimeBodyPart res = SMIMEUtil.toMimeBodyPart(byteContent); return res; } catch (Exception e) { log.error("Problem decrypting message: ", e); throw new MessagingException(e.getMessage()); } }