use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.
the class CertStoreUtils method certFromData.
public static X509Certificate certFromData(KeyStoreProtectionManager mgr, byte[] data) {
X509Certificate retVal = null;
try {
// first check for wrapped data
final CertContainer container = CertUtils.toCertContainer(data);
if (container.getWrappedKeyData() != null) {
// make sure we have a KeyStoreManager configured
if (mgr == null) {
throw new NHINDException(AgentError.Unexpected, "Resolved certifiate has wrapped data, but resolver has not been configured to unwrap it.");
}
// create a new wrapped certificate object
retVal = WrappedOnDemandX509CertificateEx.fromX509Certificate(mgr, container.getCert(), container.getWrappedKeyData());
return retVal;
}
ByteArrayInputStream bais = new ByteArrayInputStream(data);
// lets try this a as a PKCS12 data stream first
try {
KeyStore localKeyStore = KeyStore.getInstance("PKCS12", CryptoExtensions.getJCEProviderName());
localKeyStore.load(bais, "".toCharArray());
Enumeration<String> aliases = localKeyStore.aliases();
// we are really expecting only one alias
if (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
X509Certificate cert = (X509Certificate) localKeyStore.getCertificate(alias);
// check if there is private key
Key key = localKeyStore.getKey(alias, "".toCharArray());
if (key != null && key instanceof PrivateKey) {
retVal = X509CertificateEx.fromX509Certificate(cert, (PrivateKey) key);
} else
retVal = cert;
}
} catch (Exception e) {
// must not be a PKCS12 stream, go on to next step
}
if (retVal == null) {
//try X509 certificate factory next
bais.reset();
bais = new ByteArrayInputStream(data);
retVal = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(bais);
}
bais.close();
// look in the keystore manager to check if they private key is store in the token
if (mgr != null && !(retVal instanceof X509CertificateEx)) {
// make sure this a mutable manager
if (mgr instanceof MutableKeyStoreProtectionManager) {
try {
final KeyStore ks = ((MutableKeyStoreProtectionManager) mgr).getKS();
// check to see if this certificate exists in the key store
final String alias = ks.getCertificateAlias(retVal);
if (!StringUtils.isEmpty(alias)) {
// get the private key if it exits
final PrivateKey pKey = (PrivateKey) ks.getKey(alias, "".toCharArray());
if (pKey != null)
retVal = X509CertificateEx.fromX509Certificate(retVal, pKey);
}
} catch (Exception e) {
LOGGER.warn("Could not retrieve the private key from the PKCS11 token: " + e.getMessage(), e);
}
}
}
} catch (Exception e) {
throw new NHINDException("Data cannot be converted to a valid X.509 Certificate", e);
}
return retVal;
}
use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.
the class ConfigServiceCertificateStore method getAllCertificates.
/**
* {@inheritDoc}
*/
@Override
public Collection<X509Certificate> getAllCertificates() {
// get everything from the configuration service.... no caching here
org.nhind.config.Certificate[] certificates;
try {
// hard code to get everything
certificates = proxy.listCertificates(0L, 0x8FFF, null);
} catch (Exception e) {
throw new NHINDException("WebService error getting all certificates: " + e.getMessage(), e);
}
// purge everything
this.flush(true);
if (certificates == null || certificates.length == 0)
return Collections.emptyList();
// convert to X509Certificates and store
Collection<X509Certificate> retVal = new ArrayList<X509Certificate>();
for (org.nhind.config.Certificate cert : certificates) {
X509Certificate storeCert = CertStoreUtils.certFromData(mgr, cert.getData());
retVal.add(storeCert);
// add to JCS and cache
try {
if (cache != null)
cache.put(cert.getOwner(), retVal);
} catch (CacheException e) {
/*
* TODO: handle exception
*/
}
if (localStoreDelegate != null) {
if (localStoreDelegate.contains(storeCert))
localStoreDelegate.update(storeCert);
else
localStoreDelegate.add(storeCert);
}
}
return retVal;
}
use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.
the class ConfigServiceRESTCertificateStore method getAllCertificates.
/**
* {@inheritDoc}
*/
@Override
public Collection<X509Certificate> getAllCertificates() {
// get everything from the configuration service.... no caching here
Collection<org.nhindirect.config.model.Certificate> certificates;
try {
certificates = certService.getAllCertificates();
} catch (Exception e) {
throw new NHINDException("WebService error getting all certificates: " + e.getMessage(), e);
}
// purge everything
this.flush(true);
if (certificates == null || certificates.isEmpty())
return Collections.emptyList();
// convert to X509Certificates and store
Collection<X509Certificate> retVal = new ArrayList<X509Certificate>();
for (org.nhindirect.config.model.Certificate cert : certificates) {
X509Certificate storeCert = CertStoreUtils.certFromData(mgr, cert.getData());
retVal.add(storeCert);
// add to JCS and cache
try {
if (cache != null)
cache.put(cert.getOwner(), retVal);
} catch (CacheException e) {
/*
* TODO: handle exception
*/
}
}
return retVal;
}
use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.
the class SMIMECryptographerImpl method createSignatureEntity.
protected MimeMultipart createSignatureEntity(byte[] entity, Collection<X509Certificate> signingCertificates) {
MimeMultipart retVal = null;
try {
final MimeBodyPart signedContent = new MimeBodyPart(new ByteArrayInputStream(entity));
final ASN1EncodableVector signedAttrs = new ASN1EncodableVector();
final 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(x509CertificateObjectsIdent);
signedAttrs.add(new SMIMECapabilitiesAttribute(caps));
final List<X509Certificate> certList = new ArrayList<X509Certificate>();
final DirectSignedDataGenerator generator = sigFactory.createInstance();
for (X509Certificate signer : signingCertificates) {
if (signer instanceof X509CertificateEx) {
generator.addSigner(((X509CertificateEx) signer).getPrivateKey(), signer, this.m_digestAlgorithm.getOID(), createAttributeTable(signedAttrs), null);
certList.add(signer);
}
}
final CertStore certsAndcrls = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), CryptoExtensions.getJCEProviderNameForTypeAndAlgorithm("CertStore", "Collection"));
generator.addCertificatesAndCRLs(certsAndcrls);
final CMSProcessableBodyPart content = new CMSProcessableBodyPart(signedContent);
final CMSSignedData signedData = generator.generate(content);
final String header = "signed; protocol=\"application/pkcs7-signature\"; micalg=" + CryptoAlgorithmsHelper.toDigestAlgorithmMicalg(this.m_digestAlgorithm);
//String encodedSig = Base64.encodeBase64String(signedData.getEncoded());
final String encodedSig = StringUtils.newStringUtf8(Base64.encodeBase64(signedData.getEncoded(), true));
retVal = new MimeMultipart(header.toString());
final MimeBodyPart sig = new MimeBodyPart(new InternetHeaders(), encodedSig.getBytes("ASCII"));
sig.addHeader("Content-Type", "application/pkcs7-signature; name=smime.p7s; smime-type=signed-data");
sig.addHeader("Content-Disposition", "attachment; filename=\"smime.p7s\"");
sig.addHeader("Content-Description", "S/MIME Cryptographic Signature");
sig.addHeader("Content-Transfer-Encoding", "base64");
retVal.addBodyPart(signedContent);
retVal.addBodyPart(sig);
} catch (MessagingException e) {
throw new MimeException(MimeError.InvalidMimeEntity, e);
} catch (IOException e) {
throw new SignatureException(SignatureError.InvalidMultipartSigned, e);
} catch (Exception e) {
throw new NHINDException(MimeError.Unexpected, e);
}
return retVal;
}
use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.
the class TrustChainValidator method downloadCertsFromAIA.
/**
* Downloads certificates from the AIA URL and returns the result as a collection of certificates.
* @param url The URL listed in the AIA extension to locate the certificates.
* @return The certificates downloaded from the AIA extension URL
*/
@SuppressWarnings("unchecked")
protected Collection<X509Certificate> downloadCertsFromAIA(String url) throws NHINDException {
InputStream inputStream = null;
Collection<? extends Certificate> 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();
// download the
retVal = CertificateFactory.getInstance("X.509").generateCertificates(inputStream);
} catch (Exception e) {
throw new NHINDException("Failed to download certificates from AIA extension.", e);
} finally {
IOUtils.closeQuietly(inputStream);
}
return (Collection<X509Certificate>) retVal;
}
Aggregations