use of org.bouncycastle.cms.CMSSignedData in project nhin-d by DirectProject.
the class ViewTrustBundlePKCS7 method viewBundle.
@SuppressWarnings({ "rawtypes" })
public boolean viewBundle(File trustDir) {
try {
//System.out.println("File:"+trustDir.getName());
if (!trustDir.getName().endsWith(".p7m")) {
byte[] trustBundleByte = loadFileData(trustDir);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
CMSSignedData dataParser = new CMSSignedData(trustBundleByte);
ContentInfo contentInfo = dataParser.getContentInfo();
SignedData signedData = SignedData.getInstance(contentInfo.getContent());
Enumeration certificates = signedData.getCertificates().getObjects();
StringBuffer output = new StringBuffer();
int counter = 1;
String chk = "Absent";
while (certificates.hasMoreElements()) {
DERObject certObj = (DERObject) certificates.nextElement();
InputStream in = new ByteArrayInputStream(certObj.getDEREncoded());
X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
X500Name x500name = new JcaX509CertificateHolder(cert).getSubject();
RDN cn = x500name.getRDNs(BCStyle.CN)[0];
output.append("Trust Anchor :" + counter + "\n");
output.append("Common Name :" + IETFUtils.valueToString(cn.getFirst().getValue()) + "\n");
output.append("DN :" + cert.getSubjectDN().getName() + "\n\n");
counter++;
}
if (signedData.getEncapContentInfo().getContent() != null) {
//chk = new String(signedData.getEncapContentInfo().getContent().getDERObject().getEncoded(),"UTF-8");
chk = new String(signedData.getEncapContentInfo().getContent().getDERObject().getDEREncoded(), "UTF-8");
}
output.append("Meta Data :\n" + chk);
error = output.toString();
} else //end of if check of file type
{
StringBuffer output = new StringBuffer();
int counter = 1;
String chk = "Absent";
byte[] trustBundleByte = loadFileData(trustDir);
CMSSignedData dataParser = new CMSSignedData(trustBundleByte);
ContentInfo contentInfo = dataParser.getContentInfo();
SignedData signedData = SignedData.getInstance(contentInfo.getContent());
CMSSignedData encapInfoBundle = new CMSSignedData(new CMSProcessableByteArray(signedData.getEncapContentInfo().getContent().getDERObject().getEncoded()), contentInfo);
SignedData encapMetaData = SignedData.getInstance(encapInfoBundle.getContentInfo().getContent());
//System.out.println("ENCAP META DATA"+new String(encapMetaData.getEncapContentInfo().getContent().getDERObject().getEncoded(),"UTF-8"));
CMSProcessableByteArray cin = new CMSProcessableByteArray(((ASN1OctetString) encapMetaData.getEncapContentInfo().getContent()).getOctets());
CertificateFactory ucf = CertificateFactory.getInstance("X.509");
CMSSignedData unsignedParser = new CMSSignedData(cin.getInputStream());
ContentInfo unsginedEncapInfo = unsignedParser.getContentInfo();
SignedData metaData = SignedData.getInstance(unsginedEncapInfo.getContent());
Enumeration certificates = metaData.getCertificates().getObjects();
while (certificates.hasMoreElements()) {
DERObject certObj = (DERObject) certificates.nextElement();
InputStream bin = new ByteArrayInputStream(certObj.getDEREncoded());
X509Certificate cert = (X509Certificate) ucf.generateCertificate(bin);
X500Name x500name = new JcaX509CertificateHolder(cert).getSubject();
RDN cn = x500name.getRDNs(BCStyle.CN)[0];
output.append("Trust Anchor :" + counter + "\n");
output.append("Common Name :" + IETFUtils.valueToString(cn.getFirst().getValue()) + "\n");
output.append("DN :" + cert.getSubjectDN().getName() + "\n\n");
counter++;
}
if (metaData.getEncapContentInfo().getContent() != null) {
//chk = new String(signedData.getEncapContentInfo().getContent().getDERObject().getEncoded(),"UTF-8");
chk = new String(metaData.getEncapContentInfo().getContent().getDERObject().getDEREncoded(), "UTF-8");
}
output.append("Meta Data :\n" + chk);
error = output.toString();
}
//end of .p7m check if
}//end of try
catch (IOException io) {
//io.printStackTrace(System.err);
return false;
} catch (CMSException cm) {
//cm.printStackTrace(System.err);
return false;
} catch (Exception e) {
//e.printStackTrace(System.err);
return false;
}
return true;
}
use of org.bouncycastle.cms.CMSSignedData in project nhin-d by DirectProject.
the class SMIMECryptographerImpl method deserializeSignatureEnvelope.
/**
* Extracts the ASN1 encoded signature data from the signed entity.
* @param entity The entity containing the original signed part and the message signature.
* @return A CMSSignedData object that contains the ASN1 encoded signature data of the message.
*/
public CMSSignedData deserializeSignatureEnvelope(SignedEntity entity) {
if (entity == null) {
throw new NHINDException();
}
CMSSignedData signed = null;
try {
//signed = new SMIMESigned(entity.getMimeMultipart());
byte[] messageBytes = EntitySerializer.Default.serializeToBytes(entity.getContent());
MimeBodyPart signedContent = null;
signedContent = new MimeBodyPart(new ByteArrayInputStream(messageBytes));
signed = new CMSSignedData(new CMSProcessableBodyPart(signedContent), entity.getMimeMultipart().getBodyPart(1).getInputStream());
} catch (Exception e) {
e.printStackTrace();
throw new MimeException(MimeError.Unexpected, e);
}
return signed;
}
use of org.bouncycastle.cms.CMSSignedData 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.CMSSignedData in project nhin-d by DirectProject.
the class SplitProviderDirectSignedDataGenerator_generateTest method testGenerate_safeNetHSMSignatureProvider_assertGenerated.
public void testGenerate_safeNetHSMSignatureProvider_assertGenerated() throws Exception {
/**
* This test is only run if a specific SafeNet eToken Pro HSM is connected to the testing
* system. This can be modified for another specific machine and/or token.
*/
pkcs11ProvName = TestUtils.setupSafeNetToken();
if (!StringUtils.isEmpty(pkcs11ProvName)) {
// get a certificate from the key store
final KeyStore ks = KeyStore.getInstance("PKCS11");
ks.load(null, "1Kingpuff".toCharArray());
final Enumeration<String> aliases = ks.aliases();
while (aliases.hasMoreElements()) {
final String alias = aliases.nextElement();
final KeyStore.Entry entry = ks.getEntry(alias, null);
if (entry instanceof KeyStore.PrivateKeyEntry) {
KeyStore.PrivateKeyEntry ent = (KeyStore.PrivateKeyEntry) entry;
signerCert = X509CertificateEx.fromX509Certificate((X509Certificate) ent.getCertificate(), ent.getPrivateKey());
break;
}
}
final SplitProviderDirectSignedDataGenerator gen = new SplitProviderDirectSignedDataGenerator(pkcs11ProvName, "BC");
setupSigningInfo(gen);
// create the content
final MimeBodyPart signedContent = new MimeBodyPart();
signedContent.addHeader("To:", "me@you.com");
signedContent.addHeader("From", "test.test.com");
signedContent.setText("Some Text To Sign");
final CMSProcessableBodyPart content = new CMSProcessableBodyPart(signedContent);
final CMSSignedData signedData = gen.generate(content);
validateSignature(signedData);
}
}
use of org.bouncycastle.cms.CMSSignedData in project nhin-d by DirectProject.
the class SplitProviderDirectSignedDataGenerator_generateTest method testGenerate_differentDefaultSigAndDigestProvider_assertGenerated.
public void testGenerate_differentDefaultSigAndDigestProvider_assertGenerated() throws Exception {
final SplitProviderDirectSignedDataGenerator gen = new SplitProviderDirectSignedDataGenerator("SunRsaSign", "BC");
setupSigningInfo(gen);
// create the content
final MimeBodyPart signedContent = new MimeBodyPart();
signedContent.addHeader("To:", "me@you.com");
signedContent.addHeader("From", "test.test.com");
signedContent.setText("Some Text To Sign");
final CMSProcessableBodyPart content = new CMSProcessableBodyPart(signedContent);
final CMSSignedData signedData = gen.generate(content);
validateSignature(signedData);
}
Aggregations