use of org.bouncycastle.cms.CMSSignedData in project nhin-d by DirectProject.
the class DefaultNHINDAgent method decryptSignedContent.
/*
* Decrypts the signed message
*/
@SuppressWarnings("unchecked")
protected void decryptSignedContent(IncomingMessage message) {
MimeEntity decryptedEntity = this.decryptMessage(message);
CMSSignedData signatures;
MimeEntity payload;
try {
if (SMIMEStandard.isContentEnvelopedSignature(new ContentType(decryptedEntity.getContentType()))) {
signatures = cryptographer.deserializeEnvelopedSignature(decryptedEntity);
payload = new MimeEntity(new ByteArrayInputStream(signatures.getContentInfo().getEncoded()));
} else if (SMIMEStandard.isContentMultipartSignature(new ContentType(decryptedEntity.getContentType()))) {
//
// Extract the signature envelope. That contains both the signature and the actual message content
//
ByteArrayDataSource dataSource = new ByteArrayDataSource(decryptedEntity.getRawInputStream(), decryptedEntity.getContentType());
MimeMultipart verifyMM = new MimeMultipart(dataSource);
SignedEntity signedEntity = SignedEntity.load(verifyMM);
signatures = cryptographer.deserializeSignatureEnvelope(signedEntity);
payload = signedEntity.getContent();
} else {
throw new AgentException(AgentError.UnsignedMessage);
}
message.setSignature(signatures);
//
// Alter body to contain actual content. Also clean up mime headers on the message that were there to support
// signatures etc
//
InternetHeaders headers = new InternetHeaders();
// remove all mime headers
Enumeration<Header> eHeaders = message.getMessage().getAllHeaders();
while (eHeaders.hasMoreElements()) {
Header hdr = (Header) eHeaders.nextElement();
if (!MimeStandard.startsWith(hdr.getName(), MimeStandard.HeaderPrefix))
headers.setHeader(hdr.getName(), hdr.getValue());
}
// add back in headers from original message
eHeaders = payload.getAllHeaders();
while (eHeaders.hasMoreElements()) {
Header hdr = (Header) eHeaders.nextElement();
headers.setHeader(hdr.getName(), hdr.getValue());
}
Message msg = new Message(headers, payload.getContentAsBytes());
message.setMessage(msg);
} catch (MessagingException e) {
throw new MimeException(MimeError.InvalidBody, e);
} catch (IOException e) {
throw new MimeException(MimeError.InvalidBody, e);
}
}
use of org.bouncycastle.cms.CMSSignedData in project nhin-d by DirectProject.
the class CryptographerTest method testvalidateSignature.
public void testvalidateSignature() throws Exception {
final String str = FileUtils.readFileToString(new File("./src/test/resources/org/nhindirect/stagent/msgSig.txt"));
byte[] byteData = Base64.decode(str);
CMSSignedData signed = new CMSSignedData(byteData);
CertStore certs = signed.getCertificatesAndCRLs("Collection", CryptoExtensions.getJCEProviderName());
Collection<? extends Certificate> certCollection = certs.getCertificates(null);
for (Certificate cert : certCollection) {
FileUtils.writeByteArrayToFile(new File("./testCert.der"), cert.getEncoded());
}
}
use of org.bouncycastle.cms.CMSSignedData in project nhin-d by DirectProject.
the class SMIMECryptographerImpl_createSignatureEntityTest method deserializeSignatureEnvelope.
protected CMSSignedData deserializeSignatureEnvelope(MimeMultipart mm) throws Exception {
final MimeEntity contentEntity = contentToMimeEntity(mm.getBodyPart(0));
byte[] messageBytes = EntitySerializer.Default.serializeToBytes(contentEntity);
MimeBodyPart signedContent = null;
signedContent = new MimeBodyPart(new ByteArrayInputStream(messageBytes));
return new CMSSignedData(new CMSProcessableBodyPart(signedContent), mm.getBodyPart(1).getInputStream());
}
use of org.bouncycastle.cms.CMSSignedData in project nhin-d by DirectProject.
the class TrustModel_findTrustedSignatureTest method setUp.
@Override
public void setUp() throws Exception {
CryptoExtensions.registerJCEProviders();
// load sigCert A
sigUser1 = TestUtils.getInternalCert("user1");
// load sigCert A private certificate
sigUser1CA = TestUtils.getInternalCACert("cacert");
// load other anchor
otherCert = TestUtils.loadCertificate("gm2552.der");
// load the message that will be encrypted
String testMessage = TestUtils.readResource("MultipartMimeMessage.txt");
cryptographer = new SMIMECryptographerImpl();
inMessage = new IncomingMessage(new Message(new ByteArrayInputStream(testMessage.getBytes())));
signedEntity = cryptographer.sign(inMessage.getMessage(), sigUser1);
CMSSignedData signatures = cryptographer.deserializeSignatureEnvelope(signedEntity);
inMessage.setSignature(signatures);
}
use of org.bouncycastle.cms.CMSSignedData in project nhin-d by DirectProject.
the class DefaultBundleRefreshProcessorImpl method convertRawBundleToAnchorCollection.
/**
* Converts a trust raw trust bundle byte array into a collection of {@link X509Certificate} objects.
* @param rawBundle The raw representation of the bundle. This generally the raw byte string downloaded from the bundle's URL.
* @param existingBundle The configured bundle object in the DAO. This object may contain the signing certificate
* used for bundle authenticity checking.
* @param processAttempStart The time that the update process started.
* @return
*/
@SuppressWarnings("unchecked")
protected Collection<X509Certificate> convertRawBundleToAnchorCollection(byte[] rawBundle, final TrustBundle existingBundle, final Calendar processAttempStart) {
Collection<? extends Certificate> bundleCerts = null;
InputStream inStream = null;
// check to see if its an unsigned PKCS7 container
try {
inStream = new ByteArrayInputStream(rawBundle);
bundleCerts = CertificateFactory.getInstance("X.509").generateCertificates(inStream);
// if its null and has no anchors, then try again as a signed bundle
if (bundleCerts != null && bundleCerts.size() == 0)
bundleCerts = null;
} catch (Exception e) {
/* no-op for now.... this may not be a p7b, so try it as a signed message*/
} finally {
IOUtils.closeQuietly(inStream);
}
// didnt work... try again as a CMS signed message
if (bundleCerts == null) {
try {
final CMSSignedData signed = new CMSSignedData(rawBundle);
// then verify the signature
if (existingBundle.getSigningCertificateData() != null) {
boolean sigVerified = false;
final X509Certificate signingCert = existingBundle.toSigningCertificate();
for (SignerInformation sigInfo : (Collection<SignerInformation>) signed.getSignerInfos().getSigners()) {
try {
if (sigInfo.verify(signingCert, CryptoExtensions.getJCEProviderName())) {
sigVerified = true;
break;
}
} catch (Exception e) {
/* no-op... can't verify */
}
}
if (!sigVerified) {
dao.updateLastUpdateError(existingBundle.getId(), processAttempStart, BundleRefreshError.UNMATCHED_SIGNATURE);
log.warn("Downloaded bundle signature did not match configured signing certificate.");
return null;
}
}
final CMSProcessableByteArray signedContent = (CMSProcessableByteArray) signed.getSignedContent();
inStream = new ByteArrayInputStream((byte[]) signedContent.getContent());
bundleCerts = CertificateFactory.getInstance("X.509").generateCertificates(inStream);
} catch (Exception e) {
dao.updateLastUpdateError(existingBundle.getId(), processAttempStart, BundleRefreshError.INVALID_BUNDLE_FORMAT);
log.warn("Failed to extract anchors from downloaded bundle at URL " + existingBundle.getBundleURL());
} finally {
IOUtils.closeQuietly(inStream);
}
}
return (Collection<X509Certificate>) bundleCerts;
}
Aggregations