source: java/net/deterlab/abac/Context.java @ e36ea1d

abac0-leakabac0-meicompt_changesgec13mei-idmei-rt0-nmei_rt0mei_rt2mei_rt2_fix_1meiyap-rt1meiyap1rt2tvf-new-xml
Last change on this file since e36ea1d was e36ea1d, checked in by Ted Faber <faber@…>, 13 years ago

Initial javadocs

  • Property mode set to 100644
File size: 25.4 KB
Line 
1package net.deterlab.abac;
2
3import edu.uci.ics.jung.graph.*;
4import edu.uci.ics.jung.graph.util.*;
5
6import java.io.*;
7import java.util.*;
8import java.util.zip.*;
9import java.security.*;
10import java.security.cert.*;
11
12import org.bouncycastle.asn1.*;
13import org.bouncycastle.asn1.x509.*;
14import org.bouncycastle.x509.*;
15import org.bouncycastle.openssl.*;
16
17/**
18 * Represents a global graph of credentials in the form of principals and
19 * attributes.  Contains the identities and credentials that can be used in a
20 * proof.
21 * @author <a href="http://abac.deterlab.net">ISI ABAC team</a>
22 * @version 1.3
23 */
24public class Context {
25    /** Certificate imported successfully */
26    public static final int ABAC_CERT_SUCCESS = 0;
27    /** Certificate import failed, invalid certificate */
28    public static final int ABAC_CERT_INVALID = -1;
29    /** Certificate import failed, signature filed */
30    public static final int ABAC_CERT_BAD_SIG = -2;
31    /** Certificate import failed, unknown issuer */
32    public static final int ABAC_CERT_MISSING_ISSUER = -3;
33
34    /** Internal graph representation */
35    protected Graph<Role,Credential> g;
36    /** Set of edges in the graph that were added by the logic.  */
37    protected Set<Credential> derived_edges;
38    /** Internal persistent query object */
39    protected Query pq;
40    /** True when the graph has been changed since the last set of implied
41     * edges were calculated. */
42    protected boolean dirty;
43    /** Set of identities known to this Context. */
44    protected Set<Identity> identities;
45
46    /** Translation from issuer CN to issuer pubkey identifier */
47    protected Map<String, String> nicknames;
48    /** Translation from issuer pubkey identifier to issuer CN */
49    protected Map<String, String> keys;
50
51    /**
52     * The result of a query on this context.  The credentials form a partial
53     * or total proof, and success indicates whether the proof succeeded.
54     * @author <a href="http://abac.deterlab.net">ISI ABAC team</a>
55     * @version 1.3
56     */
57    public class QueryResult {
58        /** Credentials returned */
59        protected Collection<Credential> creds;
60        /** True if the proof succeeded. */
61        protected boolean success;
62
63        /**
64         * Construct a result from components.
65         * @param c the collection of credentials in the proof
66         * @param s a boolean, true if the query succeeded.
67         */
68        QueryResult(Collection<Credential> c, boolean s) {
69            creds = c;
70            success = s;
71        }
72
73        /**
74         * Empty constructor
75         */
76        public QueryResult() { 
77            creds = new TreeSet<Credential>();
78            success = false;
79        }
80
81        /**
82         * Return the credentials in the proof.
83         * @return the collection of credentials
84         */
85        public Collection<Credential> getCredentials() { return creds; }
86        /**
87         * Return the success in the proof.
88         * @return the boolean, true on success
89         */
90        public boolean getSuccess() { return success; }
91    }
92
93
94    /**
95     * Create an empty Context.
96     */
97    public Context() {
98        /* create the graph */
99        g = Graphs.<Role,Credential>synchronizedDirectedGraph(
100                new DirectedSparseGraph<Role,Credential>());
101        derived_edges = new HashSet<Credential>();
102        pq = new Query(g);
103        dirty = false;
104        identities = new TreeSet<Identity>();
105        nicknames = new TreeMap<String, String>();
106        keys = new TreeMap<String, String>();
107    }
108
109    /**
110     * Create a context from another context.
111     * @param c the Context to copy
112     */
113    public Context(Context c) {
114        this();
115        for (Identity i: c.identities) 
116            loadIDChunk(i);
117        for (Credential cr: c.credentials()) 
118            loadAttributeChunk(cr);
119        derive_implied_edges();
120    }
121
122    /**
123     * Load an Identity from a file.
124     * @param fn a String containing the file name.
125     * @return one of the static int return codes.
126     */
127    public int loadIDFile(String fn) { return loadIDChunk(new File(fn)); }
128    /**
129     * Load an Identity from a file.
130     * @param fn a File containing the file name.
131     * @return one of the static int return codes.
132     */
133    public int loadIDFile(File fn) { return loadIDChunk(fn); }
134    /**
135     * Load an Identity from an object.  Supported objects are an Identity, a
136     * String, a File, or a java.security.cert.X509Certificate.  A string
137     * creates an new identity, and the others are derived from the contents of
138     * the data or file.
139     * @param c an object convertable to an identity as above.
140     * @return one of the static int return codes.
141     */
142    public int loadIDChunk(Object c) {
143        try {
144            if (c instanceof Identity)
145                addIdentity((Identity) c);
146            else if (c instanceof String) 
147                addIdentity(new Identity((String) c));
148            else if (c instanceof File) 
149                addIdentity(new Identity((File) c));
150            else if (c instanceof X509Certificate) 
151                addIdentity(new Identity((X509Certificate) c));
152            else 
153                return ABAC_CERT_INVALID;
154        }
155        catch (SignatureException sig) {
156            return ABAC_CERT_BAD_SIG;
157        }
158        catch (Exception e) {
159            return ABAC_CERT_INVALID;
160        }
161        return ABAC_CERT_SUCCESS;
162    }
163
164    /**
165     * Load an attribute certificate from a file.
166     * @param fn a String containing the file name.
167     * @return one of the static int return codes.
168     */
169    public int loadAttributeFile(String fn) { 
170        return loadAttributeChunk(new File(fn));
171    }
172
173    /**
174     * Load an attribute certificate from a file.
175     * @param fn a File containing the file name.
176     * @return one of the static int return codes.
177     */
178    public int loadAttributeFile(File fn) { return loadAttributeChunk(fn); }
179
180    /**
181     * Load an Identity from an object.  Supported objects are a Credential, a
182     * String, a File, or an org.bouncycastle.x509.X509V2AttributeCertificate.
183     * A string creates an new Credential, and the others are derived from the
184     * contents of the data or file.
185     * @param c an object convertable to a Credential as above.
186     * @return one of the static int return codes.
187     */
188    public int loadAttributeChunk(Object c) {
189        try {
190            if (c instanceof Credential)
191                add_credential((Credential) c);
192            else if (c instanceof String) 
193                add_credential(new Credential((String) c, identities));
194            else if (c instanceof File) 
195                add_credential(new Credential((File) c, identities));
196            else if ( c instanceof X509V2AttributeCertificate) 
197                add_credential(new Credential((X509V2AttributeCertificate)c,
198                            identities));
199            else 
200                return ABAC_CERT_INVALID;
201        }
202        catch (SignatureException sig) {
203            return ABAC_CERT_BAD_SIG;
204        }
205        catch (Exception e) {
206            return ABAC_CERT_INVALID;
207        }
208        return ABAC_CERT_SUCCESS;
209    }
210
211    /**
212     * Determine if prinicpal possesses role in the current context.  If so,
213     * return a proof of that, otherwise return a partial proof of it.
214     * @param role a String encoding the role to check for.
215     * @param principal a String with the principal ID in it.
216     * @return a Context.QueryResult containing the result.
217     */
218    public QueryResult query(String role, String principal) {
219        derive_implied_edges();
220
221        Query q = new Query(g);
222        Graph<Role, Credential> rg = q.run(role, principal);
223
224        return new QueryResult(rg.getEdges(), q.successful());
225    }
226
227    /**
228     * Return a collection of the credentials in the graph.s
229     * @return a collection of the credentials in the graph.
230     */
231    public Collection<Credential> credentials() {
232        Collection<Credential> creds = new HashSet<Credential>();
233
234        // only return creds with a cert: all others are derived edges
235        for (Credential cred : g.getEdges())
236            if (cred.cert() != null)
237                creds.add(cred);
238
239        return creds;
240    }
241
242    /**
243     * Returns true if the given Identity is known in this Context.  A jabac
244     * extension.
245     * @param i the Identity to look for
246     * @return a boolean, true if the Identity is known.
247     */
248    public boolean knowsIdentity(Identity i) { return identities.contains(i); }
249    /**
250     * Returns true if an Identity with the given string representation is
251     * known in this Context.  A jabac extension.
252     * @param k the string representing the Identity to look for
253     * @return a boolean, true if the Identity is known.
254     */
255    public boolean knowsKeyID(String k) {
256        boolean known = false;
257        for (Identity i: identities)
258            if (k.equals(i.getKeyID())) return true;
259        return false;
260    }
261
262
263    /**
264     * Add a credential to the graph.
265     * @param cred the Credential to add
266     */
267    protected void add_credential(Credential cred) {
268        Role tail = cred.tail();
269        Role head = cred.head();
270
271        // explicitly add the vertices, to avoid a null pointer exception
272        if ( !g.containsVertex(head)) 
273            g.addVertex(head);
274        if ( !g.containsVertex(tail)) 
275            g.addVertex(tail);
276
277        if (!g.containsEdge(cred))
278            g.addEdge(cred, tail, head);
279
280        // add the prereqs of an intersection to the graph
281        if (tail.is_intersection())
282            for (Role prereq : tail.prereqs())
283                g.addVertex(prereq);
284
285        dirty = true;
286    }
287
288    /**
289     * Remove a credential from the graph.
290     * @param cred the Credential to remove
291     */
292    protected void remove_credential(Credential cred) {
293        if (g.containsEdge(cred))
294            g.removeEdge(cred);
295        dirty = true;
296    }
297
298    /**
299     * Add a role w/o an edge
300     * @param v the Role to add
301     */
302    protected void add_vertex(Role v) {
303        if (!g.containsVertex(v)) {
304            g.addVertex(v);
305            dirty = true;
306        }
307    }
308
309    /**
310     * Remove a role and connected edges.
311     * @param v the Role to remove
312     */
313    protected void remove_vertex(Role v) {
314        if (g.containsVertex(v)) {
315            g.removeVertex(v);
316            dirty = true;
317        }
318    }
319
320    /**
321     * Derive the implied edges in the graph, according to RT0 derivation rules.
322     * They are added to this graph. See "Distributed Credential Chain Discovery
323     * in Trust Management" by Ninghui Li et al. for details. Note that a
324     * derived linking edge can imply a new intersection edge and vice versa.
325     * Therefore we iteratively derive edges, giving up when an iteration
326     * produces 0 new edges.
327     */
328    protected synchronized void derive_implied_edges() {
329        // nothing to do on a clean graph
330        if (!dirty)
331            return;
332
333        clear_old_edges();
334
335        // iteratively derive links. continue as long as new links are added
336        while (derive_links_iter() > 0)
337            ;
338        dirty = false;
339    }
340
341    /**
342     * Single iteration of deriving implied edges. Returns the number of new
343     * links added.
344     * @return the number of new links added.
345     */
346    protected int derive_links_iter() {
347        int count = 0;
348
349        /* for every node in the graph.. */
350        for (Role vertex : g.getVertices()) {
351            if (vertex.is_intersection()) {
352                // for each prereq edge:
353                //     find set of principals that have the prereq
354                // find the intersection of all sets (i.e., principals
355                //     that satisfy all prereqs)
356                // for each principal in intersection:
357                //     add derived edge
358
359                Set<Role> principals = null;
360
361                for (Role prereq : vertex.prereqs()) {
362                    Set<Role> cur_principals = pq.find_principals(prereq);
363
364                    if (principals == null)
365                        principals = cur_principals;
366                    else
367                        // no, they couldn't just call it "intersection"
368                        principals.retainAll(cur_principals);
369
370                    if (principals.size() == 0)
371                        break;
372                }
373
374                // add em
375                for (Role principal : principals)
376                    if (add_derived_edge(vertex, principal))
377                        ++count;
378            }
379
380            else if (vertex.is_linking()) {
381                // make the rest of the code a bit clearer
382                Role A_r1_r2 = vertex;
383
384                Role A_r1 = new Role(A_r1_r2.A_r1());
385                String r2 = A_r1_r2.r2();
386
387                /* locate the node A.r1 */
388                if (!g.containsVertex(A_r1)) continue; 
389
390                /* for each B that satisfies A_r1 */
391                for (Role principal : pq.find_principals(A_r1)) {
392                    Role B_r2 = new Role(principal + "." + r2);
393                    if (!g.containsVertex(B_r2)) continue;
394
395                    if (add_derived_edge(A_r1_r2, B_r2))
396                        ++count;
397                }
398            }
399        }
400
401        return count;
402    }
403
404    /**
405     * Add a derived edge in the graph. Returns true only if the edge does not
406     * exist.
407     * @return a boolean, true if an edge has been added
408     */
409    protected boolean add_derived_edge(Role head, Role tail) {
410        // edge exists: return false
411        if (g.findEdge(tail, head) != null)
412            return false;
413
414        // add the new edge
415        Credential derived_edge = new Credential(head, tail);
416        derived_edges.add(derived_edge);
417        g.addEdge(derived_edge, tail, head);
418
419        return true;
420    }
421
422    /**
423     * Clear the derived edges that currently exist in the graph. This is done
424     * before the edges are rederived. The derived edges in filtered graphs are
425     * also cleared.
426     */
427    protected void clear_old_edges() { 
428        for (Credential i: derived_edges) 
429            g.removeEdge(i);
430        derived_edges = new HashSet<Credential>();
431    }
432    /**
433     * Put the Identity into the set of ids used to validate certificates.
434     * Also put the keyID and name into the translation mappings used by Roles
435     * to pretty print.  In the role mapping, if multiple ids use the same
436     * common name they are disambiguated.  Only one entry for keyid is
437     * allowed.
438     * @param i the Identity to add
439     */
440    protected void addIdentity(Identity id) { 
441        identities.add(id);
442        if (id.getName() != null && id.getKeyID() != null) {
443            if ( !keys.containsKey(id.getKeyID()) ) {
444                String name = id.getName();
445                int n= 1;
446
447                while (nicknames.containsKey(name)) {
448                    name = id.getName() + n++;
449                }
450                nicknames.put(name, id.getKeyID());
451                keys.put(id.getKeyID(), name);
452            }
453        }
454    }
455    /**
456     * Translate either keys to nicknames or vice versa.  Break the string into
457     * space separated tokens and then each of them into period separated
458     * strings.  If any of the smallest strings is in the map, replace it with
459     * the value.
460     * @param is the string to manipulate
461     * @param m the Map containing translations
462     * @return the string after modification
463     */
464    protected String replace(String is, Map<String, String> m) {
465        String rv = "";
466        for (String tok: is.split(" ")) {
467            String term = "";
468            for (String s: tok.split("\\.")) {
469                String next = m.containsKey(s) ? m.get(s) : s;
470
471                if (term.isEmpty()) term = next;
472                else term += "." + next;
473            }
474            if (rv.isEmpty()) rv = term;
475            else rv += " " + term;
476        }
477        return rv;
478    }
479
480    /**
481     * Expand menmonic names in a Role string, e.g. the CN of the issuer
482     * certificate, into the full key ID.  Used internally by Roles to provide
483     * transparent use of mnemonics
484     * @param s the string to expand
485     * @return the String after expansion.
486     */
487    String expandKeyID(String s) { return replace(s, nicknames); }
488    /**
489     * Convert key IDs to  menmonic names in a Role string.  The inverse of
490     * expandKeyID.
491     * @param s the string to expand
492     * @return the String after expansion.
493     */
494    String expandNickname(String s) { return replace(s, keys); }
495
496    /**
497     * Import a zip file.  First import all the identities
498     * (pem), then the credentials (der) into the credential graph then any
499     * alias files into the two maps.  If keys is not null, any key pairs in
500     * PEM files are put in there.  If errors is not null, errors reading files
501     * are added indexed by filename.
502     * @param zf the File to read
503     * @param keys a Collection into which to insert unmatched keys
504     * @param errors a Map from entry name to generated exception
505     * @throws IOException if the file is unreadable.  Per entry exceptions are
506     *                     returned in the errors parameter.
507     */
508    public void readZipFile(File zf, Collection<KeyPair> keys, 
509            Map<String, Exception> errors) throws IOException {
510        Vector<ZipEntry> derEntries = new Vector<ZipEntry>();
511        Map<String, Identity> ids = new TreeMap<String, Identity>();
512        Map<String, KeyPair> kps = new TreeMap<String, KeyPair>();
513
514        ZipFile z = new ZipFile(zf);
515
516        for (Enumeration<? extends ZipEntry> ze = z.entries(); 
517                ze.hasMoreElements();) {
518            ZipEntry  f = ze.nextElement();
519            try {
520                PEMReader r = new PEMReader(
521                        new InputStreamReader(z.getInputStream(f)));
522                Object o = readPEM(r);
523
524                if ( o != null ) {
525                    if (o instanceof Identity) {
526                        Identity i = (Identity) o;
527                        String kid = i.getKeyID();
528
529                        if (kps.containsKey(kid) ) {
530                            i.setKeyPair(kps.get(kid));
531                            kps.remove(kid);
532                        }
533                        else if (i.getKeyPair() == null ) 
534                            ids.put(i.getKeyID(), i);
535
536                        loadIDChunk(i);
537                    }
538                    else if (o instanceof KeyPair ) {
539                        KeyPair kp = (KeyPair) o;
540                        String kid = extractKeyID(kp.getPublic());
541
542                        if (ids.containsKey(kid)) {
543                            Identity i = ids.get(kid);
544
545                            i.setKeyPair(kp);
546                            ids.remove(kid);
547                        }
548                        else {
549                            kps.put(kid, kp);
550                        }
551                    }
552                }
553                else {
554                    // Not a PEM file
555                    derEntries.add(f);
556                    continue;
557                }
558            }
559            catch (Exception e ) {
560                if (errors != null ) errors.put(f.getName(), e);
561            }
562        }
563
564        for ( ZipEntry f : derEntries ) {
565            try {
566                add_credential(new Credential(z.getInputStream(f), identities));
567            }
568            catch (Exception e ) {
569                if (errors != null ) errors.put(f.getName(), e);
570            }
571        }
572    }
573    /**
574     * Equivalent to readZipFile(d, null, null).
575     * @param d the File to read
576     * @throws IOException if the file is unreadable. To see per-entry
577     *                      exceptions use a signature with the errors parameter
578     */
579    public void readZipFile(File d) 
580            throws IOException {
581        readZipFile(d, null, null);
582    }
583    /**
584     * Equivalent to readZipFile(d, null, errors).
585     * @param d the File to read
586     * @param errors a Map from entry name to generated exception
587     * @throws IOException if the file is unreadable.  Per entry exceptions are
588     *                     returned in the errors parameter.
589     */
590    public void readZipFile(File d, 
591            Map<String, Exception> errors) throws IOException {
592        readZipFile(d, null, errors);
593    }
594    /**
595     * Equivalent to readZipFile(d, keys, null).
596     * @param d the File to read
597     * @param keys a Collection into which to insert unmatched keys
598     * @throws IOException if the file is unreadable. To see per-entry
599     *                      exceptions use a signature with the errors parameter
600     */
601    public void readZipFile(File d, 
602            Collection<KeyPair> keys) throws IOException {
603        readZipFile(d, keys, null);
604    }
605
606    /**
607     * Read a PEM file that contains an X509 Certificate, a key pair, or both.
608     * If a cert is present it is converted into an Identity.  A key pair is
609     * returned as a java.security.KeyPair and both are returned as an Identity
610     * with an associated key pair.
611     * @param r a PEMReader from which to read
612     * @return an object encoding the contents (as above)
613     * @throws IOException for an unreadable or badly formated input
614     */
615    protected Object readPEM(PEMReader r) throws IOException {
616        Identity i = null;
617        KeyPair keys = null;
618        Object o = null;
619
620        while ( (o = r.readObject()) != null ) {
621            if (o instanceof X509Certificate) {
622                if ( i == null ) {
623                    try {
624                        i = new Identity((X509Certificate)o);
625                    }
626                    catch (Exception e) {
627                        // Translate Idenitiy exceptions to IOException
628                        throw new IOException(e);
629                    }
630                    if (keys != null ) {
631                        i.setKeyPair(keys);
632                        keys = null;
633                    }
634                }
635                else throw new IOException("Two certificates");
636            }
637            else if (o instanceof KeyPair ) {
638                if ( i != null ) i.setKeyPair((KeyPair) o);
639                else keys = (KeyPair) o;
640            }
641            else {
642                throw new IOException("Unexpected PEM object: " + 
643                        o.getClass().getName());
644            }
645        }
646
647        if ( i != null ) return i;
648        else if ( keys != null) return keys;
649        else return null;
650    }
651
652    /**
653     * Import a directory full of files.  First import all the identities
654     * (pem), then the credentials (der) into the credential graph then any
655     * alias files into the two maps.  If keys is not null, any key pairs in
656     * PEM files are put in there.  If errors is not null, errors reading files
657     * are added indexed by filename.
658     * @param d the File to read.  If it is a directory its contents are read
659     * @param keys a Collection into which to insert unmatched keys
660     * @param errors a Map from entry name to generated exception
661     * @throws IOException if the file is unreadable.  Per file exceptions are
662     *                     returned in the errors parameter.
663     */
664    public void readDirectory(File d, Collection<KeyPair> keys, 
665            Map<String, Exception> errors) {
666        Vector<File> derFiles = new Vector<File>();
667        Collection<File> files = new Vector<File>();
668        Map<String, Identity> ids = new TreeMap<String, Identity>();
669        Map<String, KeyPair> kps = new TreeMap<String, KeyPair>();
670
671        if (d.isDirectory() ) 
672            for (File f : d.listFiles()) 
673                files.add(f);
674        else files.add(d);
675
676        for (File f: files ) {
677            try {
678                PEMReader r = new PEMReader(new FileReader(f));
679                Object o = readPEM(r);
680
681                if ( o != null ) {
682                    if (o instanceof Identity) {
683                        Identity i = (Identity) o;
684                        String kid = i.getKeyID();
685
686                        if (kps.containsKey(kid) ) {
687                            i.setKeyPair(kps.get(kid));
688                            kps.remove(kid);
689                        }
690                        else if (i.getKeyPair() == null ) 
691                            ids.put(i.getKeyID(), i);
692
693                        loadIDChunk(i);
694                    }
695                    else if (o instanceof KeyPair ) {
696                        KeyPair kp = (KeyPair) o;
697                        String kid = extractKeyID(kp.getPublic());
698
699                        if (ids.containsKey(kid)) {
700                            Identity i = ids.get(kid);
701
702                            i.setKeyPair(kp);
703                            ids.remove(kid);
704                        }
705                        else {
706                            kps.put(kid, kp);
707                        }
708                    }
709                }
710                else {
711                    // Not a PEM file
712                    derFiles.add(f);
713                    continue;
714                }
715            }
716            catch (Exception e ) {
717                if (errors != null ) errors.put(f.getName(), e);
718            }
719        }
720
721        for ( File f : derFiles ) {
722            try {
723                add_credential(new Credential(f, identities));
724            }
725            catch (Exception e ) {
726                if (errors != null ) errors.put(f.getName(), e);
727            }
728        }
729    }
730    /**
731     * Equivalent to readDirectory(d, null, null).
732     * @param d the File to read.  If it is a directory its contents are read
733     * @throws IOException if the file is unreadable.  To see per-file
734     *                     exceptions use a signature with the errors parameter.
735     */
736    public void readDirectory(File d) {
737        readDirectory(d, null, null);
738    }
739    /**
740     * Equivalent to readDirectory(d, null, null).
741     * @param d the File to read.  If it is a directory its contents are read
742     * @param errors a Map from entry name to generated exception
743     * @throws IOException if the file is unreadable.  Per file exceptions are
744     *                     returned in the errors parameter.
745     */
746    public void readDirectory(File d, Map<String, Exception> errors) {
747        readDirectory(d, null, errors);
748    }
749    /**
750     * Equivalent to readDirectory(d, null, null).
751     * @param d the File to read.  If it is a directory its contents are read
752     * @param keys a Collection into which to insert unmatched keys
753     * @throws IOException if the file is unreadable.  To see per-file
754     *                     exceptions use a signature with the errors parameter.
755     */
756    public void readDirectory(File d, Collection<KeyPair> keys) {
757        readDirectory(d, keys, null);
758    }
759
760    /**
761     * Write the certificates that make up the context as a zip file, with an
762     * entry for each credential or identity.
763     * @param f the File to write
764     * @param allIDs a boolean, if true write certificates for all Identities,
765     * whether used in signing a credential or not.
766     * @param withPrivateKeys a boolean, if true write the Identities as PEM
767     * file containing both the certificate and the private keys.
768     * @throws IOException if there is a problem writhing the file.
769     */
770    public void writeZipFile(File f, boolean allIDs, boolean withPrivateKeys) 
771            throws IOException {
772        ZipOutputStream z = new ZipOutputStream(new FileOutputStream(f));
773        Set<Identity> ids = allIDs ?  identities : new TreeSet<Identity>();
774
775        int n = 0;
776        for (Credential c: credentials()) {
777            z.putNextEntry(new ZipEntry("attr" + n++  + ".der"));
778            c.write(z);
779            z.closeEntry();
780            if ( c.issuer() != null && !allIDs) ids.add(c.issuer());
781        }
782        for (Identity i: ids) {
783            z.putNextEntry(new ZipEntry(i.getName() + ".pem"));
784            i.write(z);
785            if (withPrivateKeys)
786                i.writePrivateKey(z);
787            z.closeEntry();
788        }
789        z.close();
790    }
791
792    /**
793     * Get to the SHA1 hash of the key.  Used by Roles and Identities to get a
794     * key ID.
795     * @param k the PublicKey to get the ID from.
796     * @return a String with the key identifier
797     */
798    static String extractKeyID(PublicKey k) {
799        SubjectPublicKeyInfo ki = extractSubjectPublicKeyInfo(k);
800        SubjectKeyIdentifier id = 
801            SubjectKeyIdentifier.createSHA1KeyIdentifier(ki);
802
803        // Now format it into a string for keeps
804        Formatter fmt = new Formatter(new StringWriter());
805        for (byte b: id.getKeyIdentifier())
806            fmt.format("%02x", b);
807        return fmt.out().toString();
808    }
809
810    /**
811     * Extratct the SubjectPublicKeyInfo.  Useful for some other encryptions,
812     * notably Certificate.make_cert().
813     * @param k the PublicKey to get the ID from.
814     * @return a String with the key identifier
815     */
816    static SubjectPublicKeyInfo extractSubjectPublicKeyInfo(
817            PublicKey k) {
818        ASN1Sequence seq = null;
819        try {
820            seq = (ASN1Sequence) new ASN1InputStream(
821                    k.getEncoded()).readObject();
822        }
823        catch (IOException ie) {
824            // Badly formatted key??
825            return null;
826        }
827        return new SubjectPublicKeyInfo(seq);
828    }
829
830
831}
Note: See TracBrowser for help on using the repository browser.