use of org.bouncycastle.mail.smime.SMIMEEnvelopedParser in project as2-lib by phax.
the class BCCryptoHelper method decrypt.
@Nonnull
public MimeBodyPart decrypt(@Nonnull final MimeBodyPart aPart, @Nonnull final X509Certificate aX509Cert, @Nonnull final PrivateKey aPrivateKey, final boolean bForceDecrypt, @Nonnull final AS2ResourceHelper aResHelper) throws GeneralSecurityException, MessagingException, CMSException, SMIMEException, IOException {
ValueEnforcer.notNull(aPart, "MimeBodyPart");
ValueEnforcer.notNull(aX509Cert, "X509Cert");
ValueEnforcer.notNull(aPrivateKey, "PrivateKey");
ValueEnforcer.notNull(aResHelper, "ResHelper");
if (LOGGER.isDebugEnabled())
LOGGER.debug("BCCryptoHelper.decrypt; X509 subject=" + aX509Cert.getSubjectX500Principal().getName() + "; forceDecrypt=" + bForceDecrypt);
// Make sure the data is encrypted
if (!bForceDecrypt && !isEncrypted(aPart))
throw new GeneralSecurityException("Content-Type '" + aPart.getContentType() + "' indicates data isn't encrypted");
// Get the recipient object for decryption
final RecipientId aRecipientID = new JceKeyTransRecipientId(aX509Cert);
// Parse the MIME body into an SMIME envelope object
RecipientInformation aRecipient = null;
try {
final SMIMEEnvelopedParser aEnvelope = new SMIMEEnvelopedParser(aPart);
aRecipient = aEnvelope.getRecipientInfos().get(aRecipientID);
} catch (final Exception ex) {
LOGGER.error("Error retrieving RecipientInformation", ex);
}
if (aRecipient == null)
throw new GeneralSecurityException("Certificate does not match part signature");
// try to decrypt the data
// Custom file: see #103
final FileBackedMimeBodyPart aDecryptedDataBodyPart = SMIMEUtil.toMimeBodyPart(aRecipient.getContentStream(new JceKeyTransEnvelopedRecipient(aPrivateKey).setProvider(m_sSecurityProviderName)), aResHelper.createTempFile());
if (DUMP_DECRYPTED_DIR_PATH != null) {
// dump decrypted
try (final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream(aDecryptedDataBodyPart.getSize())) {
aDecryptedDataBodyPart.writeTo(aBAOS);
_dumpDecrypted(aBAOS.toByteArray());
}
}
return aDecryptedDataBodyPart;
}
Aggregations