use of org.nhindirect.config.model.utils.CertUtils.CertContainer in project nhin-d by DirectProject.
the class ConfigServiceCertificateStore method certFromData.
private X509Certificate certFromData(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 (this.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());
}
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();
} catch (Exception e) {
throw new NHINDException("Data cannot be converted to a valid X.509 Certificate", e);
}
return retVal;
}
use of org.nhindirect.config.model.utils.CertUtils.CertContainer 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.config.model.utils.CertUtils.CertContainer in project nhin-d by DirectProject.
the class EntityModelConversion method toEntityCertificate.
public static org.nhindirect.config.store.Certificate toEntityCertificate(Certificate cert) throws CertificateException {
if (cert == null)
return null;
final org.nhindirect.config.store.Certificate retVal = new org.nhindirect.config.store.Certificate();
retVal.setOwner(cert.getOwner());
retVal.setCreateTime(cert.getCreateTime());
retVal.setData(cert.getData());
retVal.setId(cert.getId());
if (cert.getStatus() != null)
retVal.setStatus(org.nhindirect.config.store.EntityStatus.valueOf(cert.getStatus().toString()));
final CertContainer cont = CertUtils.toCertContainer(retVal.getData());
final Calendar endDate = Calendar.getInstance(Locale.getDefault());
endDate.setTime(cont.getCert().getNotAfter());
retVal.setValidEndDate(endDate);
final Calendar startDate = Calendar.getInstance(Locale.getDefault());
startDate.setTime(cont.getCert().getNotBefore());
retVal.setValidStartDate(startDate);
return retVal;
}
use of org.nhindirect.config.model.utils.CertUtils.CertContainer in project nhin-d by DirectProject.
the class MainController method refreshModelFromService.
public void refreshModelFromService(Model model) {
// GET A RECORDS
Collection<DNSRecord> arecords = null;
arecords = getDnsRecords(DNSType.A.getValue());
Collection<DNSEntryForm> aform = new ArrayList<DNSEntryForm>();
if (arecords != null) {
for (DNSRecord t : arecords) {
try {
ARecord newrec = (ARecord) Record.newRecord(Name.fromString(t.getName()), t.getType(), t.getDclass(), t.getTtl(), t.getData());
DNSEntryForm tmp = new DNSEntryForm();
tmp.setId(t.getId());
tmp.setDest("" + newrec.getAddress());
tmp.setTtl(newrec.getTTL());
tmp.setName("" + newrec.getName());
aform.add(tmp);
} catch (TextParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
model.addAttribute("dnsARecordResults", aform);
// GET A4 RECORDS
Collection<DNSRecord> a4records = null;
a4records = getDnsRecords(DNSType.AAAA.getValue());
Collection<DNSEntryForm> a4form = new ArrayList<DNSEntryForm>();
if (a4records != null) {
for (Iterator<DNSRecord> iter = a4records.iterator(); iter.hasNext(); ) {
DNSRecord t = (DNSRecord) iter.next();
try {
AAAARecord newrec = (AAAARecord) Record.newRecord(Name.fromString(t.getName()), t.getType(), t.getDclass(), t.getTtl(), t.getData());
DNSEntryForm tmp = new DNSEntryForm();
tmp.setId(t.getId());
tmp.setDest("" + newrec.getAddress());
tmp.setTtl(newrec.getTTL());
tmp.setName("" + newrec.getName());
a4form.add(tmp);
} catch (TextParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
model.addAttribute("dnsA4RecordResults", a4form);
// GET CNAME RECORDS
Collection<DNSRecord> crecords = null;
crecords = getDnsRecords(DNSType.CNAME.getValue());
Collection<DNSEntryForm> cform = new ArrayList<DNSEntryForm>();
if (crecords != null) {
for (Iterator<DNSRecord> iter = crecords.iterator(); iter.hasNext(); ) {
DNSRecord t = (DNSRecord) iter.next();
try {
CNAMERecord newrec = (CNAMERecord) Record.newRecord(Name.fromString(t.getName()), t.getType(), t.getDclass(), t.getTtl(), t.getData());
DNSEntryForm tmp = new DNSEntryForm();
tmp.setId(t.getId());
tmp.setDest("" + newrec.getTarget());
tmp.setTtl(newrec.getTTL());
tmp.setName("" + newrec.getName());
cform.add(tmp);
} catch (TextParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
model.addAttribute("dnsCnameRecordResults", cform);
// GET MX RECORDS
Collection<DNSRecord> mxrecords = null;
mxrecords = getDnsRecords(DNSType.MX.getValue());
Collection<DNSEntryForm> mxform = new ArrayList<DNSEntryForm>();
if (mxrecords != null) {
for (Iterator<DNSRecord> iter = mxrecords.iterator(); iter.hasNext(); ) {
DNSRecord t = (DNSRecord) iter.next();
try {
MXRecord newrec = (MXRecord) Record.newRecord(Name.fromString(t.getName()), t.getType(), t.getDclass(), t.getTtl(), t.getData());
DNSEntryForm tmp = new DNSEntryForm();
tmp.setPriority(newrec.getPriority());
tmp.setId(t.getId());
tmp.setDest("" + newrec.getTarget());
tmp.setTtl(newrec.getTTL());
tmp.setName("" + newrec.getName());
mxform.add(tmp);
} catch (TextParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
model.addAttribute("dnsMxRecordResults", mxform);
// GET Cert RECORDS
Collection<DNSRecord> certrecords = null;
certrecords = getDnsRecords(DNSType.CERT.getValue());
// get the thumbprint and assign
// create a new collection
Collection<SrvRecord> form = new ArrayList<SrvRecord>();
CertContainer cont;
if (certrecords != null) {
for (Iterator<DNSRecord> iter = certrecords.iterator(); iter.hasNext(); ) {
DNSRecord t = (DNSRecord) iter.next();
SrvRecord srv = new SrvRecord();
srv.setCreateTime(t.getCreateTime());
srv.setData(t.getData());
srv.setDclass(t.getDclass());
srv.setId(t.getId());
srv.setName(t.getName());
srv.setTtl(t.getTtl());
srv.setType(t.getType());
srv.setThumb("");
try {
CERTRecord newrec = (CERTRecord) Record.newRecord(Name.fromString(t.getName()), t.getType(), t.getDclass(), t.getTtl(), t.getData());
String thumb = "";
byte[] certData = newrec.getCert();
if (certData != null) {
// get the owner from the certificate information
// first transform into a certificate
cont = CertUtils.toCertContainer(certData);
if (cont != null && cont.getCert() != null) {
Certificate cert2 = new Certificate();
cert2.setData(certData);
thumb = getThumbPrint(cont.getCert());
srv.setThumb(thumb);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
form.add(srv);
}
}
model.addAttribute("dnsCertRecordResults", form);
// GET SRV RECORDS
Collection<DNSRecord> srvrecords = null;
srvrecords = getDnsRecords(DNSType.SRV.getValue());
// create a new collection
Collection<SrvRecord> form2 = new ArrayList<SrvRecord>();
if (srvrecords != null) {
for (Iterator<DNSRecord> iter = srvrecords.iterator(); iter.hasNext(); ) {
DNSRecord t = (DNSRecord) iter.next();
SrvRecord srv = new SrvRecord();
try {
SRVRecord srv4 = (SRVRecord) SRVRecord.newRecord(Name.fromString(t.getName()), t.getType(), t.getDclass(), t.getTtl(), t.getData());
srv.setCreateTime(t.getCreateTime());
srv.setData(t.getData());
srv.setDclass(t.getDclass());
srv.setId(t.getId());
srv.setName(t.getName());
String name = t.getName();
// parse the name to get service, protocol, priority , weight,
// port
int firstpos = name.indexOf("_");
if (firstpos == 0) {
// then this can be parsed as a srv record
// ("_"+SrvdnsForm.getService()+"._"+SrvdnsForm.getProtocol()+"._"+SrvdnsForm.getPriority()+"._"+SrvdnsForm.getWeight()+"._"+SrvdnsForm.getPort()+"._"+SrvdnsForm.getDest()+"."+SrvdnsForm.getName()
int secondpos = name.indexOf("._");
int thirdpos = name.indexOf(".", secondpos + 2);
// from first to second is service
String service_ = name.substring(firstpos + 1, secondpos);
srv.setService(service_);
// from second to third is protocol
String protocol_ = name.substring(secondpos + 2, thirdpos);
;
srv.setProtocol(protocol_);
int last2pos = name.indexOf(".", thirdpos);
String name_ = name.substring(last2pos + 1, name.length());
srv.setName(name_);
}
srv.setTtl(t.getTtl());
srv.setType(t.getType());
srv.setPort(srv4.getPort());
srv.setWeight(srv4.getWeight());
srv.setPriority("" + srv4.getPriority());
srv.setTarget("" + srv4.getTarget().toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
form2.add(srv);
}
}
model.addAttribute("dnsSrvRecordResults", form2);
// GET SOA RECORDS
Collection<DNSRecord> soarecords = null;
soarecords = getDnsRecords(DNSType.SOA.getValue());
Collection<DNSEntryForm> soaform = new ArrayList<DNSEntryForm>();
if (soarecords != null) {
for (Iterator<DNSRecord> iter = soarecords.iterator(); iter.hasNext(); ) {
DNSRecord t = (DNSRecord) iter.next();
try {
SOARecord newrec = (SOARecord) Record.newRecord(Name.fromString(t.getName()), t.getType(), t.getDclass(), t.getTtl(), t.getData());
DNSEntryForm tmp = new DNSEntryForm();
tmp.setId(t.getId());
tmp.setAdmin("" + newrec.getAdmin());
tmp.setExpire(newrec.getExpire());
tmp.setMinimum(newrec.getMinimum());
tmp.setRefresh(newrec.getRefresh());
tmp.setRetry(newrec.getRetry());
tmp.setSerial(newrec.getSerial());
tmp.setDest("" + newrec.getHost());
tmp.setDomain("" + newrec.getHost());
tmp.setTtl(newrec.getTTL());
tmp.setName("" + newrec.getName());
soaform.add(tmp);
} catch (TextParseException e) {
e.printStackTrace();
}
}
}
model.addAttribute("dnsSOARecordResults", soaform);
// GET NS RECORDS
Collection<DNSRecord> nsrecords = null;
nsrecords = getDnsRecords(DNSType.NS.getValue());
Collection<DNSEntryForm> nsform = new ArrayList<DNSEntryForm>();
if (nsrecords != null) {
for (Iterator<DNSRecord> iter = nsrecords.iterator(); iter.hasNext(); ) {
DNSRecord t = (DNSRecord) iter.next();
try {
NSRecord newrec = (NSRecord) Record.newRecord(Name.fromString(t.getName()), t.getType(), t.getDclass(), t.getTtl(), t.getData());
DNSEntryForm tmp = new DNSEntryForm();
tmp.setId(t.getId());
tmp.setDest("" + newrec.getTarget());
tmp.setTtl(newrec.getTTL());
tmp.setName("" + newrec.getName());
nsform.add(tmp);
} catch (TextParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
model.addAttribute("dnsNSRecordResults", nsform);
// *****************
model.addAttribute("NSdnsForm", new DNSEntryForm());
model.addAttribute("SoadnsForm", new DNSEntryForm());
model.addAttribute("AdnsForm", new DNSEntryForm());
model.addAttribute("AAdnsForm", new DNSEntryForm());
model.addAttribute("CdnsForm", new DNSEntryForm());
model.addAttribute("MXdnsForm", new DNSEntryForm());
model.addAttribute("CertdnsForm", new DNSEntryForm());
model.addAttribute("SrvdnsForm", new DNSEntryForm());
}
use of org.nhindirect.config.model.utils.CertUtils.CertContainer in project nhin-d by DirectProject.
the class CertificatesController method toCertDataFormat.
/*
* Converts an incoming P12 format to an appropriate format to be store in the config store. If a keystore protection manager
* has been configured, then the private key is wrapped before sending to the config store.
*/
private byte[] toCertDataFormat(byte[] certOrP12Bytes, byte[] privateKeyBytes, PrivateKeyType privKeyType) throws CryptoException {
try {
// if there is no private key, then just return the encoded certificate
if (privKeyType == PrivateKeyType.NONE)
return certOrP12Bytes;
final CertContainer cont = CertUtils.toCertContainer(certOrP12Bytes);
// if this is a PKCS12 format, then either return the bytes as is, or if there is keystore manager, wrap the private keys
if (privKeyType == PrivateKeyType.PKCS_12_PASSPHRASE | privKeyType == PrivateKeyType.PKCS_12_UNPROTECTED) {
// as PKCS12 file
if (this.keyManager == null) {
this.log.info("Storing PKCS12 file in PKCS12 unprotected format");
return certOrP12Bytes;
} else {
this.log.info("Storing PKCS12 file in wrapped format");
// now wrap the private key
final byte[] wrappedKey = this.keyManager.wrapWithSecretKey((SecretKey) ((KeyStoreProtectionManager) keyManager).getPrivateKeyProtectionKey(), cont.getKey());
// return the wrapped key format
return CertUtils.certAndWrappedKeyToRawByteFormat(wrappedKey, cont.getCert());
}
} else // when there is private key file, then either turn into a PKCS12 file (if there is no key manager), or wrap the key.
{
// cert and wrapped key format
if (privKeyType == PrivateKeyType.PKCS8_WRAPPED) {
this.log.info("Storing already wrapped PKCS8 file");
return CertUtils.certAndWrappedKeyToRawByteFormat(privateKeyBytes, cont.getCert());
}
// get a private key object, the private key is normalized at this point into an unencrypted format
final KeyFactory kf = KeyFactory.getInstance("RSA", CertUtils.getJCEProviderName());
final PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(privateKeyBytes);
final Key privKey = kf.generatePrivate(keysp);
if (this.keyManager == null) {
this.log.info("Storing PKCS8 private key in PKCS12 unprotected format");
// if there is no keystore manager, we can't wrap the keys, so we'll just send them over the wire
// as PKCS12 file. need to turn this into a PKCS12 format
final KeyStore localKeyStore = KeyStore.getInstance("PKCS12", CertUtils.getJCEProviderName());
localKeyStore.load(null, null);
localKeyStore.setKeyEntry("privCert", privKey, "".toCharArray(), new java.security.cert.Certificate[] { cont.getCert() });
final ByteArrayOutputStream outStr = new ByteArrayOutputStream();
localKeyStore.store(outStr, "".toCharArray());
try {
return outStr.toByteArray();
} finally {
IOUtils.closeQuietly(outStr);
}
} else {
this.log.info("Storing PKCS8 private key in wrapped format");
// wrap the key and turn the stream in the wrapped key format
final byte[] wrappedKey = this.keyManager.wrapWithSecretKey((SecretKey) ((KeyStoreProtectionManager) keyManager).getPrivateKeyProtectionKey(), privKey);
return CertUtils.certAndWrappedKeyToRawByteFormat(wrappedKey, cont.getCert());
}
}
} catch (Exception e) {
throw new CryptoException("Failed to conver certificate and key to cert data format: " + e.getMessage(), e);
}
}
Aggregations