package net.deterlab.abac; import java.io.*; import java.util.*; import java.security.*; import java.security.cert.*; import org.bouncycastle.asn1.*; import org.bouncycastle.asn1.util.*; import org.bouncycastle.asn1.x509.*; import org.bouncycastle.x509.*; import org.bouncycastle.jce.provider.X509AttrCertParser; import org.bouncycastle.jce.provider.X509CertificateObject; import org.bouncycastle.openssl.PEMReader; public class Identity { private X509CertificateObject m_cert; private String m_keyid; private String m_cn; public void init(String filename) throws CertificateException, NoSuchAlgorithmException,InvalidKeyException, NoSuchProviderException, SignatureException, FileNotFoundException, IOException { PEMReader pr = new PEMReader(new FileReader(filename)); Object c = pr.readObject(); if (c instanceof X509CertificateObject) { m_cert = (X509CertificateObject) c; m_cert.verify(m_cert.getPublicKey()); // Cert is valid, fill in the CN and keyid // // This little rigamarole is to get to the SHA1 hash of the // key. PublicKey k = m_cert.getPublicKey(); ASN1Sequence seq = (ASN1Sequence) new ASN1InputStream( k.getEncoded()).readObject(); SubjectPublicKeyInfo ki = new SubjectPublicKeyInfo(seq); SubjectKeyIdentifier id = SubjectKeyIdentifier.createSHA1KeyIdentifier(ki); // Now format it into a string for keeps Formatter fmt = new Formatter(new StringWriter()); for (byte b: id.getKeyIdentifier()) fmt.format("%02x", b); m_keyid = fmt.out().toString(); m_cn = m_cert.getSubjectDN().getName(); /// XXX: better parse if (m_cn.startsWith("CN=")) m_cn = m_cn.substring(3); } else throw new CertificateException("Not an identity certificate"); } public Identity(String filename) throws CertificateException, NoSuchAlgorithmException,InvalidKeyException, NoSuchProviderException, SignatureException, FileNotFoundException, IOException { init(filename); } public Identity(File file) throws CertificateException, NoSuchAlgorithmException,InvalidKeyException, NoSuchProviderException, SignatureException, FileNotFoundException, IOException { init(file.getPath()); } public String getKeyID() { return m_keyid; } public String getName() { return m_cn; } public String toString() { return m_keyid + " (" + m_cn + ")"; } public X509CertificateObject getCertificate() { return m_cert; } };