use of org.bouncycastle.cms.SignerInformation in project nhin-d by DirectProject.
the class SMIMECryptographerImpl method checkSignature.
//-----------------------------------------------------
//
// Signature Validation
//
//-----------------------------------------------------
/**
* Validates that a signed entity has a valid message and signature. The signer's certificate is validated to ensure authenticity of the message. Message
* tampering is also checked with the message's digest and the signed digest in the message signature.
* @param signedEntity The entity containing the original signed part and the message signature.
* @param signerCertificate The certificate used to sign the message.
* @param anchors A collection of certificate anchors used to determine if the certificates used in the signature can be validated as trusted certificates.
*/
public void checkSignature(SignedEntity signedEntity, X509Certificate signerCertificate, Collection<X509Certificate> anchors) throws SignatureValidationException {
CMSSignedData signatureEnvelope = deserializeSignatureEnvelope(signedEntity);
SignerInformation logSigInfo = null;
try {
// is verified with the signerCertificate
for (SignerInformation sigInfo : (Collection<SignerInformation>) signatureEnvelope.getSignerInfos().getSigners()) {
logSigInfo = sigInfo;
// such as MD5
if (!isAllowedDigestAlgorithm(sigInfo.getDigestAlgOID()))
throw new SignatureValidationException("Digest algorithm " + sigInfo.getDigestAlgOID() + " is not allowed.");
if (sigInfo.verify(signerCertificate, CryptoExtensions.getJCEProviderName())) {
// verified... return
return;
}
}
// at this point the signerCertificate cannot be verified with one of the signing certificates....
throw new SignatureValidationException("Signature validation failure.");
} catch (SignatureValidationException sve) {
throw sve;
} catch (Exception e) {
throw new SignatureValidationException("Signature validation failure.", e);
} finally {
logDigests(logSigInfo);
}
}
use of org.bouncycastle.cms.SignerInformation in project nhin-d by DirectProject.
the class SMIMECryptographerImpl_createSignatureEntityTest method validateSignature.
@SuppressWarnings("unchecked")
protected void validateSignature(CMSSignedData data, X509Certificate signerCert) throws Exception {
assertNotNull(data);
assertEquals(1, data.getSignerInfos().getSigners().size());
for (SignerInformation sigInfo : (Collection<SignerInformation>) data.getSignerInfos().getSigners()) {
assertTrue(sigInfo.verify(signerCert, CryptoExtensions.getJCEProviderName()));
/*
* explicit hash algorithm checking for compliance with Applicability
* Statement v 1.2
*/
assertEquals(DigestAlgorithm.SHA256.getOID(), sigInfo.getDigestAlgOID());
}
}
use of org.bouncycastle.cms.SignerInformation 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;
}
use of org.bouncycastle.cms.SignerInformation in project nhin-d by DirectProject.
the class SigTest method testCreateVerifySig.
public void testCreateVerifySig() throws Exception {
X509CertificateEx internalCert = TestUtils.getInternalCert("user1");
X509Certificate caCert = TestUtils.getExternalCert("cacert");
String testMessage = TestUtils.readResource("MultipartMimeMessage.txt");
MimeMessage entity = EntitySerializer.Default.deserialize(testMessage);
Message message = new Message(entity);
MimeEntity entityToSig = message.extractEntityForSignature(true);
// Serialize message out as ASCII encoded...
byte[] messageBytes = EntitySerializer.Default.serializeToBytes(entityToSig);
MimeBodyPart partToSign = null;
try {
partToSign = new MimeBodyPart(new ByteArrayInputStream(messageBytes));
} catch (Exception e) {
}
SMIMESignedGenerator gen = new SMIMESignedGenerator();
ASN1EncodableVector signedAttrs = new ASN1EncodableVector();
SMIMECapabilityVector caps = new SMIMECapabilityVector();
caps.addCapability(SMIMECapability.dES_EDE3_CBC);
caps.addCapability(SMIMECapability.rC2_CBC, 128);
caps.addCapability(SMIMECapability.dES_CBC);
caps.addCapability(new DERObjectIdentifier("1.2.840.113549.1.7.1"));
caps.addCapability(PKCSObjectIdentifiers.x509Certificate);
signedAttrs.add(new SMIMECapabilitiesAttribute(caps));
List certList = new ArrayList();
gen.addSigner(internalCert.getPrivateKey(), internalCert, SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(signedAttrs), null);
//SMIMESignedGenerator.DIGEST_SHA1, null, null);
certList.add(internalCert);
MimeMultipart retVal = null;
CertStore certsAndcrls = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), CryptoExtensions.getJCEProviderName());
gen.addCertificatesAndCRLs(certsAndcrls);
_certStores.add(certsAndcrls);
_signers.add(new Signer(internalCert.getPrivateKey(), internalCert, SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(signedAttrs), null));
retVal = generate(partToSign, CryptoExtensions.getJCEProviderName());
for (int i = 0; i < 10; ++i) {
ByteArrayOutputStream oStream = new ByteArrayOutputStream();
retVal.writeTo(oStream);
oStream.flush();
byte[] serialzedBytes = oStream.toByteArray();
//System.out.println(new String(serialzedBytes, "ASCII") + "\r\n\r\n\r\n\r\n\r\n");
ByteArrayDataSource dataSource = new ByteArrayDataSource(serialzedBytes, retVal.getContentType());
MimeMultipart verifyMM = new MimeMultipart(dataSource);
CMSSignedData signed = null;
//CMSSignedData signeddata = new CMSSignedData(new CMSProcessableBodyPartInbound(verifyMM.getBodyPart(0)), verifyMM.getBodyPart(1).getInputStream());
CMSSignedData signeddata = new CMSSignedData(new CMSProcessableBodyPartInbound(partToSign), verifyMM.getBodyPart(1).getInputStream());
int verified = 0;
CertStore certs = signeddata.getCertificatesAndCRLs("Collection", CryptoExtensions.getJCEProviderName());
SignerInformationStore signers = signeddata.getSignerInfos();
Collection c = signers.getSigners();
Iterator it = c.iterator();
while (it.hasNext()) {
SignerInformation signer = (SignerInformation) it.next();
Collection certCollection = certs.getCertificates(signer.getSID());
Attribute dig = signer.getSignedAttributes().get(CMSAttributes.messageDigest);
DERObject hashObj = dig.getAttrValues().getObjectAt(0).getDERObject();
byte[] signedHash = ((ASN1OctetString) hashObj).getOctets();
System.out.print("value of signedHash: \r\n\tvalue: ");
for (byte bt : signedHash) {
System.out.print(bt + " ");
}
System.out.println();
Iterator certIt = certCollection.iterator();
try {
assertTrue(signer.verify(internalCert, CryptoExtensions.getJCEProviderName()));
} catch (Exception e) {
e.printStackTrace();
}
byte[] bytes = signer.getContentDigest();
/*
X509Certificate cert = (X509Certificate)certIt.next();
if (signer.verify(cert.getPublicKey()))
{
verified++;
}
*/
verified++;
}
}
}
use of org.bouncycastle.cms.SignerInformation in project nhin-d by DirectProject.
the class CryptoExtensions method findSignerByCert.
/**
* Searches CMS signed data for a specific X509 certificate.
* @param signedData The signed data to search.
* @param name The certificate to search for in the signed data.
* @return A pair consisting of the singer's X509 certificated and signer information that matches the provided certificate. Returns
* null if a signer matching the name cannot be found in the signed data.
*/
public static SignerCertPair findSignerByCert(CMSSignedData signedData, X509Certificate searchCert) {
if (searchCert == null) {
throw new IllegalArgumentException();
}
try {
SignerInformationStore signers = signedData.getSignerInfos();
Collection<SignerInformation> c = signers.getSigners();
for (SignerInformation signer : c) {
//signer.getSID().
SignerId signerId = signer.getSID();
if (signerId.getIssuer().equals(searchCert.getIssuerX500Principal()) && signerId.getSerialNumber().equals(searchCert.getSerialNumber())) {
return new SignerCertPair(signer, searchCert);
}
}
} catch (Exception e) {
}
return null;
}
Aggregations