use of org.bouncycastle.cms.SignerInformation in project nhin-d by DirectProject.
the class CryptoExtensions method findSignersByName.
/**
* Searches CMS signed data for a given email name. Signed data may consist of multiple signatures either from the same subject of from multiple
* subjects.
* @param signedData The signed data to search.
* @param name The name to search for in the list of signers.
* @param excludeNames A list of names to exclude from the list. Because the search uses a simple "contains" search, it is possible for the name parameter
* to be a substring of what is requested. The excludeNames contains a super string of the name to remove unwanted names from the returned list. This parameter
* may be null;
* @return A colllection of pairs consisting of the singer's X509 certificated and signer information that matches the provided name. Returns
* an empty collection if a signer matching the name cannot be found in the signed data.
*/
public static Collection<SignerCertPair> findSignersByName(CMSSignedData signedData, String name, Collection<String> excludeNames) {
if (name == null || name.length() == 0) {
throw new IllegalArgumentException();
}
Collection<SignerCertPair> retVal = null;
try {
CertStore certs = signedData.getCertificatesAndCRLs("Collection", CryptoExtensions.getJCEProviderName());
SignerInformationStore signers = signedData.getSignerInfos();
Collection<SignerInformation> c = signers.getSigners();
for (SignerInformation signer : c) {
Collection<? extends Certificate> certCollection = certs.getCertificates(signer.getSID());
if (certCollection != null && certCollection.size() > 0) {
X509Certificate cert = (X509Certificate) certCollection.iterator().next();
if (certSubjectContainsName(cert, name)) {
boolean exclude = false;
// check if we need to exclude anything
if (excludeNames != null)
for (String excludeStr : excludeNames) if (certSubjectContainsName(cert, excludeStr)) {
exclude = true;
break;
}
if (exclude)
// break out and don't include this cert
continue;
if (retVal == null)
retVal = new ArrayList<SignerCertPair>();
retVal.add(new SignerCertPair(signer, convertToProfileProvidedCertImpl(cert)));
}
}
}
} catch (Throwable e) {
}
if (retVal == null)
return Collections.emptyList();
return retVal;
}
use of org.bouncycastle.cms.SignerInformation in project nhin-d by DirectProject.
the class MessageSigInspector method main.
public static void main(String[] args) {
if (args.length == 0) {
//printUsage();
System.exit(-1);
}
String messgefile = null;
for (int i = 0; i < args.length; i++) {
String arg = args[i];
// Options
if (!arg.startsWith("-")) {
System.err.println("Error: Unexpected argument [" + arg + "]\n");
//printUsage();
System.exit(-1);
} else if (arg.equalsIgnoreCase("-msgFile")) {
if (i == args.length - 1 || args[i + 1].startsWith("-")) {
System.err.println("Error: Missing message file");
System.exit(-1);
}
messgefile = args[++i];
} else if (arg.equals("-help")) {
//printUsage();
System.exit(-1);
} else {
System.err.println("Error: Unknown argument " + arg + "\n");
//printUsage();
System.exit(-1);
}
}
if (messgefile == null) {
System.err.println("Error: missing message file\n");
}
InputStream inStream = null;
try {
inStream = FileUtils.openInputStream(new File(messgefile));
MimeMessage message = new MimeMessage(null, inStream);
MimeMultipart mm = (MimeMultipart) message.getContent();
//byte[] messageBytes = EntitySerializer.Default.serializeToBytes(mm.getBodyPart(0).getContent());
//MimeBodyPart signedContent = null;
//signedContent = new MimeBodyPart(new ByteArrayInputStream(messageBytes));
final CMSSignedData signed = new CMSSignedData(new CMSProcessableBodyPart(mm.getBodyPart(0)), mm.getBodyPart(1).getInputStream());
CertStore certs = signed.getCertificatesAndCRLs("Collection", CryptoExtensions.getJCEProviderName());
SignerInformationStore signers = signed.getSignerInfos();
@SuppressWarnings("unchecked") Collection<SignerInformation> c = signers.getSigners();
System.out.println("Found " + c.size() + " signers");
int cnt = 1;
for (SignerInformation signer : c) {
Collection<? extends Certificate> certCollection = certs.getCertificates(signer.getSID());
if (certCollection != null && certCollection.size() > 0) {
X509Certificate cert = (X509Certificate) certCollection.iterator().next();
System.out.println("\r\nInfo for certificate " + cnt++);
System.out.println("\tSubject " + cert.getSubjectDN());
FileUtils.writeByteArrayToFile(new File("SigCert.der"), cert.getEncoded());
byte[] bytes = cert.getExtensionValue("2.5.29.15");
if (bytes != null) {
final DERObject obj = getObject(bytes);
final KeyUsage keyUsage = new KeyUsage((DERBitString) obj);
final byte[] data = keyUsage.getBytes();
final int intValue = (data.length == 1) ? data[0] & 0xff : (data[1] & 0xff) << 8 | (data[0] & 0xff);
System.out.println("\tKey Usage: " + intValue);
} else
System.out.println("\tKey Usage: NONE");
//verify and get the digests
final Attribute digAttr = signer.getSignedAttributes().get(CMSAttributes.messageDigest);
final DERObject hashObj = digAttr.getAttrValues().getObjectAt(0).getDERObject();
final byte[] signedDigest = ((ASN1OctetString) hashObj).getOctets();
final String signedDigestHex = org.apache.commons.codec.binary.Hex.encodeHexString(signedDigest);
System.out.println("\r\nSigned Message Digest: " + signedDigestHex);
try {
signer.verify(cert, "BC");
System.out.println("Signature verified.");
} catch (CMSException e) {
System.out.println("Signature failed to verify.");
}
// should have the computed digest now
final byte[] digest = signer.getContentDigest();
final String digestHex = org.apache.commons.codec.binary.Hex.encodeHexString(digest);
System.out.println("\r\nComputed Message Digest: " + digestHex);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(inStream);
}
}
use of org.bouncycastle.cms.SignerInformation in project nhin-d by DirectProject.
the class SplitProviderDirectSignedDataGenerator_generateTest method validateSignature.
@SuppressWarnings("unchecked")
protected void validateSignature(CMSSignedData data) throws Exception {
assertNotNull(data);
assertEquals(1, data.getSignerInfos().getSigners().size());
for (SignerInformation sigInfo : (Collection<SignerInformation>) data.getSignerInfos().getSigners()) assertTrue(sigInfo.verify(signerCert, CryptoExtensions.getJCEProviderName()));
}
use of org.bouncycastle.cms.SignerInformation in project pdfbox by apache.
the class ShowSignature method verifyPKCS7.
/**
* Verify a PKCS7 signature.
*
* @param byteArray the byte sequence that has been signed
* @param contents the /Contents field as a COSString
* @param sig the PDF signature (the /V dictionary)
* @throws CertificateException
* @throws CMSException
* @throws StoreException
* @throws OperatorCreationException
*/
private void verifyPKCS7(byte[] byteArray, COSString contents, PDSignature sig) throws CMSException, CertificateException, StoreException, OperatorCreationException, NoSuchAlgorithmException, NoSuchProviderException {
// inspiration:
// http://stackoverflow.com/a/26702631/535646
// http://stackoverflow.com/a/9261365/535646
CMSProcessable signedContent = new CMSProcessableByteArray(byteArray);
CMSSignedData signedData = new CMSSignedData(signedContent, contents.getBytes());
Store<X509CertificateHolder> certificatesStore = signedData.getCertificates();
Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners();
SignerInformation signerInformation = signers.iterator().next();
Collection<X509CertificateHolder> matches = certificatesStore.getMatches(signerInformation.getSID());
X509CertificateHolder certificateHolder = matches.iterator().next();
X509Certificate certFromSignedData = new JcaX509CertificateConverter().getCertificate(certificateHolder);
System.out.println("certFromSignedData: " + certFromSignedData);
certFromSignedData.checkValidity(sig.getSignDate().getTime());
if (isSelfSigned(certFromSignedData)) {
System.err.println("Certificate is self-signed, LOL!");
} else {
System.out.println("Certificate is not self-signed");
// todo rest of chain
}
if (signerInformation.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certFromSignedData))) {
System.out.println("Signature verified");
} else {
System.out.println("Signature verification failed");
}
}
use of org.bouncycastle.cms.SignerInformation in project pdfbox by apache.
the class TestCreateSignature method checkSignature.
// This check fails with a file created with the code before PDFBOX-3011 was solved.
private void checkSignature(File file) throws IOException, CMSException, OperatorCreationException, GeneralSecurityException {
try (PDDocument document = PDDocument.load(file)) {
List<PDSignature> signatureDictionaries = document.getSignatureDictionaries();
if (signatureDictionaries.isEmpty()) {
Assert.fail("no signature found");
}
for (PDSignature sig : document.getSignatureDictionaries()) {
COSString contents = (COSString) sig.getCOSObject().getDictionaryObject(COSName.CONTENTS);
byte[] buf;
try (FileInputStream fis = new FileInputStream(file)) {
buf = sig.getSignedContent(fis);
}
// inspiration:
// http://stackoverflow.com/a/26702631/535646
// http://stackoverflow.com/a/9261365/535646
CMSSignedData signedData = new CMSSignedData(new CMSProcessableByteArray(buf), contents.getBytes());
Store certificatesStore = signedData.getCertificates();
Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners();
SignerInformation signerInformation = signers.iterator().next();
Collection matches = certificatesStore.getMatches(signerInformation.getSID());
X509CertificateHolder certificateHolder = (X509CertificateHolder) matches.iterator().next();
X509Certificate certFromSignedData = new JcaX509CertificateConverter().getCertificate(certificateHolder);
Assert.assertEquals(certificate, certFromSignedData);
// CMSVerifierCertificateNotValidException means that the keystore wasn't valid at signing time
if (!signerInformation.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certFromSignedData))) {
Assert.fail("Signature verification failed");
}
break;
}
}
}
Aggregations