use of org.bouncycastle.asn1.x509.Certificate 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.x509.Certificate in project nhin-d by DirectProject.
the class TrustChainValidator method downloadCertFromAIA.
/**
* Downloads a cert from the AIA URL and returns the result as certificate.
* <br>
* AIA extensions may refer to collection files such as P7b or P7c. For this reason, this method
* has been deprecated.
* @param url The URL of the certificate that will be downloaded.
* @return The certificate downloaded from the AIA extension URL
* @deprecated As of 2.1, replaced by {@link #downloadCertsFromAIA(String)}
*/
protected X509Certificate downloadCertFromAIA(String url) throws NHINDException {
InputStream inputStream = null;
X509Certificate retVal = null;
try {
// in this case the cert is a binary representation
// of the CERT URL... transform to a string
final URL certURL = new URL(url);
final URLConnection connection = certURL.openConnection();
// the connection is not actually made until the input stream
// is open, so set the timeouts before getting the stream
connection.setConnectTimeout(DEFAULT_URL_CONNECTION_TIMEOUT);
connection.setReadTimeout(DEFAULT_URL_READ_TIMEOUT);
// open the URL as in input stream
inputStream = connection.getInputStream();
retVal = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(inputStream);
} catch (Exception e) {
throw new NHINDException("Failed to download certificate from AIA extension.", e);
} finally {
IOUtils.closeQuietly(inputStream);
}
return retVal;
}
use of org.bouncycastle.asn1.x509.Certificate 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.x509.Certificate in project XobotOS by xamarin.
the class CertPathValidatorUtilities method getNextWorkingKey.
/**
* Return the next working key inheriting DSA parameters if necessary.
* <p>
* This methods inherits DSA parameters from the indexed certificate or
* previous certificates in the certificate chain to the returned
* <code>PublicKey</code>. The list is searched upwards, meaning the end
* certificate is at position 0 and previous certificates are following.
* </p>
* <p>
* If the indexed certificate does not contain a DSA key this method simply
* returns the public key. If the DSA key already contains DSA parameters
* the key is also only returned.
* </p>
*
* @param certs The certification path.
* @param index The index of the certificate which contains the public key
* which should be extended with DSA parameters.
* @return The public key of the certificate in list position
* <code>index</code> extended with DSA parameters if applicable.
* @throws AnnotatedException if DSA parameters cannot be inherited.
*/
protected static PublicKey getNextWorkingKey(List certs, int index) throws CertPathValidatorException {
Certificate cert = (Certificate) certs.get(index);
PublicKey pubKey = cert.getPublicKey();
if (!(pubKey instanceof DSAPublicKey)) {
return pubKey;
}
DSAPublicKey dsaPubKey = (DSAPublicKey) pubKey;
if (dsaPubKey.getParams() != null) {
return dsaPubKey;
}
for (int i = index + 1; i < certs.size(); i++) {
X509Certificate parentCert = (X509Certificate) certs.get(i);
pubKey = parentCert.getPublicKey();
if (!(pubKey instanceof DSAPublicKey)) {
throw new CertPathValidatorException("DSA parameters cannot be inherited from previous certificate.");
}
DSAPublicKey prevDSAPubKey = (DSAPublicKey) pubKey;
if (prevDSAPubKey.getParams() == null) {
continue;
}
DSAParams dsaParams = prevDSAPubKey.getParams();
DSAPublicKeySpec dsaPubKeySpec = new DSAPublicKeySpec(dsaPubKey.getY(), dsaParams.getP(), dsaParams.getQ(), dsaParams.getG());
try {
KeyFactory keyFactory = KeyFactory.getInstance("DSA", BouncyCastleProvider.PROVIDER_NAME);
return keyFactory.generatePublic(dsaPubKeySpec);
} catch (Exception exception) {
throw new RuntimeException(exception.getMessage());
}
}
throw new CertPathValidatorException("DSA parameters cannot be inherited from previous certificate.");
}
use of org.bouncycastle.asn1.x509.Certificate in project XobotOS by xamarin.
the class CertPathValidatorUtilities method findCertificates.
/**
* Return a Collection of all certificates or attribute certificates found
* in the X509Store's that are matching the certSelect criteriums.
*
* @param certSelect a {@link Selector} object that will be used to select
* the certificates
* @param certStores a List containing only {@link X509Store} objects. These
* are used to search for certificates.
*
* @return a Collection of all found {@link X509Certificate} or
* {@link org.bouncycastle.x509.X509AttributeCertificate} objects.
* May be empty but never <code>null</code>.
*/
protected static Collection findCertificates(X509CertStoreSelector certSelect, List certStores) throws AnnotatedException {
Set certs = new HashSet();
Iterator iter = certStores.iterator();
while (iter.hasNext()) {
Object obj = iter.next();
if (obj instanceof X509Store) {
X509Store certStore = (X509Store) obj;
try {
certs.addAll(certStore.getMatches(certSelect));
} catch (StoreException e) {
throw new AnnotatedException("Problem while picking certificates from X.509 store.", e);
}
} else {
CertStore certStore = (CertStore) obj;
try {
certs.addAll(certStore.getCertificates(certSelect));
} catch (CertStoreException e) {
throw new AnnotatedException("Problem while picking certificates from certificate store.", e);
}
}
}
return certs;
}
Aggregations