use of org.bouncycastle.asn1.cms.Attribute in project nhin-d by DirectProject.
the class TrustChainValidator method getIssuerAddress.
private String getIssuerAddress(X509Certificate certificate) {
String address = "";
// check alternative names first
Collection<List<?>> altNames = null;
try {
altNames = certificate.getIssuerAlternativeNames();
} catch (CertificateParsingException ex) {
/* no -op */
}
if (altNames != null) {
for (List<?> entries : altNames) {
if (// should always be the case according the altNames spec, but checking to be defensive
entries.size() >= 2) {
Integer nameType = (Integer) entries.get(0);
// prefer email over over domain?
if (nameType == RFC822Name_TYPE)
address = (String) entries.get(1);
else if (nameType == DNSName_TYPE && address.isEmpty())
address = (String) entries.get(1);
}
}
}
if (!address.isEmpty())
return address;
// can't find issuer address in alt names... try the principal
X500Principal issuerPrin = certificate.getIssuerX500Principal();
// get the domain name
Map<String, String> oidMap = new HashMap<String, String>();
// OID for email address
oidMap.put("1.2.840.113549.1.9.1", "EMAILADDRESS");
String prinName = issuerPrin.getName(X500Principal.RFC1779, oidMap);
// see if there is an email address first in the DN
String searchString = "EMAILADDRESS=";
int index = prinName.indexOf(searchString);
if (index == -1) {
searchString = "CN=";
// no Email.. check the CN
index = prinName.indexOf(searchString);
if (index == -1)
// no CN... nothing else that can be done from here
return "";
}
// look for a "," to find the end of this attribute
int endIndex = prinName.indexOf(",", index);
if (endIndex > -1)
address = prinName.substring(index + searchString.length(), endIndex);
else
address = prinName.substring(index + searchString.length());
return address;
}
use of org.bouncycastle.asn1.cms.Attribute 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.asn1.cms.Attribute in project nhin-d by DirectProject.
the class SMIMECryptographerImpl method createAttributeTable.
/*
* Construct an attribute table. Added private function to support multiple versions of BC libraries.
*/
public static AttributeTable createAttributeTable(ASN1EncodableVector signedAttrs) {
// Support for BC 146.... has a different constructor signature from 140
AttributeTable retVal = null;
try {
/*
* 140 version first
*/
Constructor<AttributeTable> constr = AttributeTable.class.getConstructor(DEREncodableVector.class);
retVal = constr.newInstance(signedAttrs);
} catch (Throwable t) {
if (LOGGER.isDebugEnabled()) {
StringBuilder builder = new StringBuilder("bcmail-jdk15-140 AttributeTable(DERObjectIdentifier) constructor could not be loaded..");
builder.append("\r\n\tAttempt to use to bcmail-jdk15-146 DERObjectIdentifier(ASN1EncodableVector)");
LOGGER.debug(builder.toString());
}
}
if (retVal == null) {
try {
/*
* 146 version
*/
Constructor<AttributeTable> constr = AttributeTable.class.getConstructor(ASN1EncodableVector.class);
retVal = constr.newInstance(signedAttrs);
} catch (Throwable t) {
LOGGER.error("Attempt to use to bcmail-jdk15-146 DERObjectIdentifier(ASN1EncodableVector constructor failed.", t);
}
}
return retVal;
}
use of org.bouncycastle.asn1.cms.Attribute in project ddf by codice.
the class PkiTools method makeDistinguishedName.
/**
* Create an X500 name with a single populated attribute, the "common name". An X500 name object details the
* identity of a machine, person, or organization. The name object is used as the "subject" of a certificate.
* SSL/TLS typically uses a subject's common name as the DNS name for a machine and this name must be correct
* or SSl/TLS will not trust the machine's certificate.
* <p>
* TLS can use a different set of attributes to, the Subject Alternative Names. SANs are extensions to the
* X509 specification and can include IP addresses, DNS names and other machine information. This package does
* not use SANs.
*
* @param commonName the fully qualified host name of the end entity
* @return X500 name object with common name attribute set
* @see <a href="https://www.ietf.org/rfc/rfc4514.txt">RFC 4514, section 'LDAP: Distinguished Names'</a>
* @see <a href="https://tools.ietf.org/html/rfc4519">RFC 4519 details the exact construction of distinguished names</a>
* @see <a href="https://en.wikipedia.org/wiki/SubjectAltName">Subject Alternative Names on Wikipedia'</a>
*/
public static X500Name makeDistinguishedName(String commonName) {
Validate.isTrue(commonName != null, "Certificate common name cannot be null");
assert commonName != null;
if (commonName.isEmpty()) {
LOGGER.warn("Setting certificate common name to empty string. This could result in an unusable TLS certificate.");
}
X500NameBuilder nameBuilder = new X500NameBuilder(RFC4519Style.INSTANCE);
//Add more nameBuilder.addRDN(....) statements to support more X500 attributes.
nameBuilder.addRDN(RFC4519Style.cn, commonName);
return nameBuilder.build();
}
use of org.bouncycastle.asn1.cms.Attribute in project ddf by codice.
the class SubjectUtils method getAttribute.
/**
* Get any attribute from a subject by key.
*
* @param subject
* @param key
* @return attribute values or an empty list if not found.
*/
public static List<String> getAttribute(@Nullable Subject subject, String key) {
Validate.notNull(key);
if (subject == null) {
LOGGER.debug("Incoming subject was null, cannot look up {}.", key);
return Collections.emptyList();
}
PrincipalCollection principals = subject.getPrincipals();
if (principals == null) {
LOGGER.debug("No principals located in the incoming subject, cannot look up {}.", key);
return Collections.emptyList();
}
SecurityAssertion assertion = principals.oneByType(SecurityAssertion.class);
if (assertion == null) {
LOGGER.debug("Could not find Security Assertion, cannot look up {}.", key);
return Collections.emptyList();
}
return assertion.getAttributeStatements().stream().flatMap(as -> as.getAttributes().stream()).filter(a -> a.getName().equals(key)).flatMap(a -> a.getAttributeValues().stream()).filter(o -> o instanceof XSString).map(o -> (XSString) o).map(XSString::getValue).collect(Collectors.toList());
}
Aggregations