Search in sources :

Example 6 with NHINDException

use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.

the class SMIMECryptographerImpl method deserializeSignatureEnvelope.

/**
     * Extracts the ASN1 encoded signature data from the signed entity.
     * @param entity The entity containing the original signed part and the message signature.
     * @return A CMSSignedData object that contains the ASN1 encoded signature data of the message.
     */
public CMSSignedData deserializeSignatureEnvelope(SignedEntity entity) {
    if (entity == null) {
        throw new NHINDException();
    }
    CMSSignedData signed = null;
    try {
        //signed = new SMIMESigned(entity.getMimeMultipart());
        byte[] messageBytes = EntitySerializer.Default.serializeToBytes(entity.getContent());
        MimeBodyPart signedContent = null;
        signedContent = new MimeBodyPart(new ByteArrayInputStream(messageBytes));
        signed = new CMSSignedData(new CMSProcessableBodyPart(signedContent), entity.getMimeMultipart().getBodyPart(1).getInputStream());
    } catch (Exception e) {
        e.printStackTrace();
        throw new MimeException(MimeError.Unexpected, e);
    }
    return signed;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) MimeException(org.nhindirect.stagent.mail.MimeException) MimeBodyPart(javax.mail.internet.MimeBodyPart) NHINDException(org.nhindirect.stagent.NHINDException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) MessagingException(javax.mail.MessagingException) MimeException(org.nhindirect.stagent.mail.MimeException) NHINDException(org.nhindirect.stagent.NHINDException) ParseException(javax.mail.internet.ParseException) IOException(java.io.IOException) SignatureValidationException(org.nhindirect.stagent.SignatureValidationException) CMSProcessableBodyPart(org.bouncycastle.mail.smime.CMSProcessableBodyPart)

Example 7 with NHINDException

use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.

the class TrustChainValidator method downloadCertFromAIA.

/**
	 * Downloads a cert from the AIA URL and returns the result as certificate.
	 * <br>
	 * AIA extensions may refer to collection files such as P7b or P7c.  For this reason, this method
	 * has been deprecated.
	 * @param url The URL of the certificate that will be downloaded.
	 * @return The certificate downloaded from the AIA extension URL
	 * @deprecated As of 2.1, replaced by {@link #downloadCertsFromAIA(String)}
	 */
protected X509Certificate downloadCertFromAIA(String url) throws NHINDException {
    InputStream inputStream = null;
    X509Certificate retVal = null;
    try {
        // in this case the cert is a binary representation
        // of the CERT URL... transform to a string
        final URL certURL = new URL(url);
        final URLConnection connection = certURL.openConnection();
        // the connection is not actually made until the input stream
        // is open, so set the timeouts before getting the stream
        connection.setConnectTimeout(DEFAULT_URL_CONNECTION_TIMEOUT);
        connection.setReadTimeout(DEFAULT_URL_READ_TIMEOUT);
        // open the URL as in input stream
        inputStream = connection.getInputStream();
        retVal = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(inputStream);
    } catch (Exception e) {
        throw new NHINDException("Failed to download certificate from AIA extension.", e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
    return retVal;
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) InputStream(java.io.InputStream) NHINDException(org.nhindirect.stagent.NHINDException) X509Certificate(java.security.cert.X509Certificate) URL(java.net.URL) URLConnection(java.net.URLConnection) CertificateParsingException(java.security.cert.CertificateParsingException) AddressException(javax.mail.internet.AddressException) PolicyProcessException(org.nhindirect.policy.PolicyProcessException) NHINDException(org.nhindirect.stagent.NHINDException)

Example 8 with NHINDException

use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.

the class StripP12Passphrase method certFromData.

/*
	 * Load the exiting p12 file using the provided password and private key passphrase.
	 */
private static X509CertificateEx certFromData(byte[] data) {
    X509CertificateEx retVal = null;
    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        // lets try this a as a PKCS12 data stream first
        try {
            KeyStore localKeyStore = KeyStore.getInstance("PKCS12", CryptoExtensions.getJCEProviderName());
            localKeyStore.load(bais, filePassPhrase.toCharArray());
            Enumeration<String> aliases = localKeyStore.aliases();
            // we are really expecting only one alias 
            if (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                X509Certificate cert = (X509Certificate) localKeyStore.getCertificate(alias);
                // check if there is private key
                Key key = localKeyStore.getKey(alias, keyPassPhrase.toCharArray());
                if (key != null && key instanceof PrivateKey) {
                    retVal = X509CertificateEx.fromX509Certificate(cert, (PrivateKey) key);
                }
            }
        } catch (Exception e) {
            // must not be a PKCS12 stream, go on to next step
            System.out.println("Error decoding p12 input file: " + e.getMessage());
        }
        IOUtils.closeQuietly(bais);
    } catch (Exception e) {
        throw new NHINDException("Data cannot be converted to a valid X.509 Certificate", e);
    }
    return retVal;
}
Also used : PrivateKey(java.security.PrivateKey) X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) ByteArrayInputStream(java.io.ByteArrayInputStream) KeyStore(java.security.KeyStore) NHINDException(org.nhindirect.stagent.NHINDException) X509Certificate(java.security.cert.X509Certificate) Key(java.security.Key) PrivateKey(java.security.PrivateKey) NHINDException(org.nhindirect.stagent.NHINDException)

Example 9 with NHINDException

use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.

the class SMIMECryptographerImpl method decrypt.

/**
     * Decrypts an entity with the provided certificates' private key.
     * @param encryptedEntity The entity that will be decrypted.
     * @param decryptingCertificate The certificates whose private keys will be used to decrypt the message.
     * @return A MimeEntity containing the decrypted part.
     */
public MimeEntity decrypt(MimeEntity encryptedEntity, Collection<X509CertificateEx> decryptingCertificates) {
    if (decryptingCertificates == null || decryptingCertificates.size() == 0) {
        throw new IllegalArgumentException();
    }
    MimeEntity retEntity = null;
    try {
        if (LOGGER.isDebugEnabled()) {
            final byte[] encryptedContent = encryptedEntity.getContentAsBytes();
            writePreDecrypt(encryptedContent);
        }
        final SMIMEEnveloped m = new SMIMEEnveloped(encryptedEntity);
        if (!this.isAllowedEncryptionAlgorithm(m.getEncryptionAlgOID()))
            throw new NHINDException(MimeError.DisallowedEncryptionAlgorithm, "The encryption algorithm " + m.getEncryptionAlgOID() + " is not allowed");
        for (X509CertificateEx decryptCert : decryptingCertificates) {
            final RecipientId recId = generateRecipientSelector(decryptCert);
            final RecipientInformationStore recipients = m.getRecipientInfos();
            final DirectRecipientInformation recipient = decFactory.createInstance(recipients.get(recId), m);
            if (recipient == null)
                continue;
            final byte[] decryptedPayload = recipient.getDecryptedContent(decryptCert.getPrivateKey());
            if (LOGGER.isDebugEnabled()) {
                writePostDecrypt(decryptedPayload);
            }
            final ByteArrayInputStream inStream = new ByteArrayInputStream(decryptedPayload);
            retEntity = new MimeEntity(inStream);
            break;
        }
    } catch (MessagingException e) {
        throw new MimeException(MimeError.InvalidMimeEntity, e);
    } catch (Exception e) {
        throw new MimeException(MimeError.Unexpected, e);
    }
    if (retEntity == null) {
        throw new NHINDException(MimeError.Unexpected, "None of the the provided decryption certs were found in message's RecipientsInfo set.");
    }
    return retEntity;
}
Also used : RecipientId(org.bouncycastle.cms.RecipientId) MessagingException(javax.mail.MessagingException) DirectRecipientInformation(org.nhindirect.stagent.cryptography.activekeyops.DirectRecipientInformation) SMIMEEnveloped(org.bouncycastle.mail.smime.SMIMEEnveloped) NHINDException(org.nhindirect.stagent.NHINDException) MessagingException(javax.mail.MessagingException) MimeException(org.nhindirect.stagent.mail.MimeException) NHINDException(org.nhindirect.stagent.NHINDException) ParseException(javax.mail.internet.ParseException) IOException(java.io.IOException) SignatureValidationException(org.nhindirect.stagent.SignatureValidationException) X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) ByteArrayInputStream(java.io.ByteArrayInputStream) MimeEntity(org.nhindirect.stagent.mail.MimeEntity) RecipientInformationStore(org.bouncycastle.cms.RecipientInformationStore) MimeException(org.nhindirect.stagent.mail.MimeException)

Example 10 with NHINDException

use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.

the class Notification method getNotificationFieldsAsHeaders.

/**
	 * Parses the notification part fields of a MDN MimeMessage message.  The message is expected to conform to the MDN specification
	 * as described in RFC3798.
	 * @return The notification part fields as a set of Internet headers. 
	 */
public static InternetHeaders getNotificationFieldsAsHeaders(MimeMessage message) {
    if (message == null)
        throw new IllegalArgumentException("Message can not be null");
    MimeMultipart mm = null;
    try {
        ByteArrayDataSource dataSource = new ByteArrayDataSource(message.getRawInputStream(), message.getContentType());
        mm = new MimeMultipart(dataSource);
    } catch (Exception e) {
        throw new NHINDException("Failed to parse notification fields.", e);
    }
    return getNotificationFieldsAsHeaders(mm);
}
Also used : MimeMultipart(javax.mail.internet.MimeMultipart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) NHINDException(org.nhindirect.stagent.NHINDException) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) NHINDException(org.nhindirect.stagent.NHINDException)

Aggregations

NHINDException (org.nhindirect.stagent.NHINDException)45 X509Certificate (java.security.cert.X509Certificate)30 ArrayList (java.util.ArrayList)14 ByteArrayInputStream (java.io.ByteArrayInputStream)13 IOException (java.io.IOException)11 Key (java.security.Key)10 PrivateKey (java.security.PrivateKey)10 KeyStore (java.security.KeyStore)9 CacheException (org.apache.jcs.access.exception.CacheException)7 X509CertificateEx (org.nhindirect.stagent.cert.X509CertificateEx)7 MessagingException (javax.mail.MessagingException)6 Collection (java.util.Collection)4 UnknownHostException (java.net.UnknownHostException)3 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)3 Certificate (java.security.cert.Certificate)3 InternetHeaders (javax.mail.internet.InternetHeaders)3 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)3 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)3 MutableKeyStoreProtectionManager (org.nhindirect.common.crypto.MutableKeyStoreProtectionManager)3 File (java.io.File)2