Search in sources :

Example 11 with X509CertificateEx

use of org.nhindirect.stagent.cert.X509CertificateEx 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 12 with X509CertificateEx

use of org.nhindirect.stagent.cert.X509CertificateEx 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 13 with X509CertificateEx

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

the class CryptographerTest method testEncryptAndDecryptMimeEntity.

private void testEncryptAndDecryptMimeEntity(EncryptionAlgorithm encAlg, boolean enforceStrongEncryption, boolean expectDecException) throws Exception {
    X509Certificate cert = TestUtils.getExternalCert("user1");
    SMIMECryptographerImpl cryptographer = new SMIMECryptographerImpl();
    if (encAlg != null)
        cryptographer.setEncryptionAlgorithm(encAlg);
    cryptographer.setStrongEncryptionEnforced(enforceStrongEncryption);
    MimeEntity entity = new MimeEntity();
    entity.setText("Hello world.");
    entity.setHeader(MimeStandard.ContentTypeHeader, "text/plain");
    entity.setHeader(MimeStandard.ContentTransferEncodingHeader, "7bit");
    MimeEntity encEntity = cryptographer.encrypt(entity, cert);
    assertNotNull(encEntity);
    /*
		 * explicit header checking for compliance with Applicability
		 * Statement v 1.2
		 */
    final ContentType type = new ContentType(encEntity.getContentType());
    assertTrue(type.match(SMIMEStandard.CmsEnvelopeMediaType));
    assertFalse(type.match(SMIMEStandard.CmsEnvelopeMediaTypeAlt));
    X509CertificateEx certex = TestUtils.getInternalCert("user1");
    if (expectDecException) {
        boolean exceptionOccured = false;
        try {
            cryptographer.decrypt(encEntity, certex);
        } catch (Exception e) {
            exceptionOccured = true;
        }
        assertTrue(exceptionOccured);
    } else {
        MimeEntity decryEntity = cryptographer.decrypt(encEntity, certex);
        assertNotNull(decryEntity);
        byte[] decryEntityBytes = EntitySerializer.Default.serializeToBytes(decryEntity);
        byte[] entityBytes = EntitySerializer.Default.serializeToBytes(entity);
        assertTrue(Arrays.equals(decryEntityBytes, entityBytes));
    }
}
Also used : ContentType(javax.mail.internet.ContentType) SMIMECryptographerImpl(org.nhindirect.stagent.cryptography.SMIMECryptographerImpl) X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) MimeEntity(org.nhindirect.stagent.mail.MimeEntity) X509Certificate(java.security.cert.X509Certificate) NHINDException(org.nhindirect.stagent.NHINDException) SignatureValidationException(org.nhindirect.stagent.SignatureValidationException)

Example 14 with X509CertificateEx

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

the class CryptographerTest method testSignMimeEntity_MD5Digest_forceStrongDigest_assertRejectValidation.

public void testSignMimeEntity_MD5Digest_forceStrongDigest_assertRejectValidation() throws Exception {
    X509CertificateEx certex = TestUtils.getInternalCert("user1");
    SMIMECryptographerImpl cryptographer = new SMIMECryptographerImpl();
    cryptographer.setDigestAlgorithm(DigestAlgorithm.MD5);
    MimeEntity entity = new MimeEntity();
    entity.setText("Hello world.");
    entity.setHeader(MimeStandard.ContentTypeHeader, "text/plain");
    entity.setHeader(MimeStandard.ContentTransferEncodingHeader, "7bit");
    SignedEntity signedEnt = cryptographer.sign(entity, certex);
    assertNotNull(signedEnt);
    byte[] signedEntityBytes = EntitySerializer.Default.serializeToBytes(signedEnt.getContent());
    byte[] entityBytes = EntitySerializer.Default.serializeToBytes(entity);
    assertTrue(Arrays.equals(signedEntityBytes, entityBytes));
    assertNotNull(signedEnt.getSignature());
    X509Certificate cert = TestUtils.getExternalCert("user1");
    boolean exceptionOccured = false;
    try {
        cryptographer.checkSignature(signedEnt, cert, new ArrayList<X509Certificate>());
    } catch (SignatureValidationException e) {
        exceptionOccured = true;
    }
    assertTrue(exceptionOccured);
}
Also used : X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) SMIMECryptographerImpl(org.nhindirect.stagent.cryptography.SMIMECryptographerImpl) MimeEntity(org.nhindirect.stagent.mail.MimeEntity) SignatureValidationException(org.nhindirect.stagent.SignatureValidationException) SignedEntity(org.nhindirect.stagent.cryptography.SignedEntity) X509Certificate(java.security.cert.X509Certificate)

Example 15 with X509CertificateEx

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

the class CryptographerTest method testEncryptAndDecryptMultipartEntity.

private void testEncryptAndDecryptMultipartEntity(EncryptionAlgorithm encAlgo, boolean enforceStrongEncryption) throws Exception {
    X509Certificate cert = TestUtils.getExternalCert("user1");
    SMIMECryptographerImpl cryptographer = new SMIMECryptographerImpl();
    cryptographer.setEncryptionAlgorithm(encAlgo);
    cryptographer.setStrongEncryptionEnforced(enforceStrongEncryption);
    MimeEntity entityText = new MimeEntity();
    entityText.setText("Hello world.");
    entityText.setHeader(MimeStandard.ContentTypeHeader, "text/plain");
    entityText.setHeader(MimeStandard.ContentTransferEncodingHeader, "7bit");
    MimeEntity entityXML = new MimeEntity();
    entityXML.setText("<Test></Test>");
    entityXML.setHeader(MimeStandard.ContentTypeHeader, "text/xml");
    MimeMultipart mpEntity = new MimeMultipart();
    mpEntity.addBodyPart(entityText);
    mpEntity.addBodyPart(entityXML);
    MimeEntity encEntity = cryptographer.encrypt(mpEntity, cert);
    assertNotNull(encEntity);
    X509CertificateEx certex = TestUtils.getInternalCert("user1");
    MimeEntity decryEntity = cryptographer.decrypt(encEntity, certex);
    assertNotNull(decryEntity);
    ByteArrayOutputStream oStream = new ByteArrayOutputStream();
    mpEntity.writeTo(oStream);
    InternetHeaders hdrs = new InternetHeaders();
    hdrs.addHeader(MimeStandard.ContentTypeHeader, mpEntity.getContentType());
    MimeEntity orgEntity = new MimeEntity(hdrs, oStream.toByteArray());
    byte[] decryEntityBytes = EntitySerializer.Default.serializeToBytes(decryEntity);
    byte[] entityBytes = EntitySerializer.Default.serializeToBytes(orgEntity);
    System.out.println("Original:\r\n" + new String(entityBytes));
    System.out.println("\r\n\r\n\r\nNew:\r\n" + new String(decryEntityBytes));
    assertTrue(Arrays.equals(decryEntityBytes, entityBytes));
}
Also used : InternetHeaders(javax.mail.internet.InternetHeaders) SMIMECryptographerImpl(org.nhindirect.stagent.cryptography.SMIMECryptographerImpl) MimeMultipart(javax.mail.internet.MimeMultipart) X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) MimeEntity(org.nhindirect.stagent.mail.MimeEntity) ByteArrayOutputStream(java.io.ByteArrayOutputStream) X509Certificate(java.security.cert.X509Certificate)

Aggregations

X509CertificateEx (org.nhindirect.stagent.cert.X509CertificateEx)51 X509Certificate (java.security.cert.X509Certificate)39 MimeEntity (org.nhindirect.stagent.mail.MimeEntity)18 SMIMECryptographerImpl (org.nhindirect.stagent.cryptography.SMIMECryptographerImpl)13 IOException (java.io.IOException)11 KeyStore (java.security.KeyStore)11 NHINDException (org.nhindirect.stagent.NHINDException)9 ByteArrayInputStream (java.io.ByteArrayInputStream)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 Key (java.security.Key)6 PrivateKey (java.security.PrivateKey)6 File (java.io.File)5 Certificate (java.security.cert.Certificate)5 MimeMultipart (javax.mail.internet.MimeMultipart)5 SMIMEEnveloped (org.bouncycastle.mail.smime.SMIMEEnveloped)5 LdapCertificateStoreProvider (org.nhindirect.stagent.cert.impl.provider.LdapCertificateStoreProvider)5 SignedEntity (org.nhindirect.stagent.cryptography.SignedEntity)5 ArrayList (java.util.ArrayList)4 MessagingException (javax.mail.MessagingException)4 RecipientInformation (org.bouncycastle.cms.RecipientInformation)4