1   /*
2    * @(#)CertificateExtensions.java   1.22 03/01/23
3    *
4    * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
5    * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6    */
7   
8   package sun.security.x509;
9   
10  import java.io.IOException;
11  import java.io.InputStream;
12  import java.io.OutputStream;
13  import java.lang.reflect.Array;
14  import java.lang.reflect.Constructor;
15  import java.lang.reflect.InvocationTargetException;
16  import java.security.cert.CertificateException;
17  import java.util.Collection;
18  import java.util.Enumeration;
19  import java.util.Hashtable;
20  
21  import sun.security.util.*;
22  
23  /**
24   * This class defines the Extensions attribute for the Certificate.
25   *
26   * @author Amit Kapoor
27   * @author Hemma Prafullchandra
28   * @version 1.22
29   * @see CertAttrSet
30   */
31  public class CertificateExtensions implements CertAttrSet {
32      /**
33       * Identifier for this attribute, to be used with the
34       * get, set, delete methods of Certificate, x509 type.
35       */
36      public static final String IDENT = "x509.info.extensions";
37      /**
38       * name
39       */
40      public static final String NAME = "extensions";
41  
42      private Hashtable map = new Hashtable(11);
43      private boolean unsupportedCritExt = false;
44  
45      /**
46       * Default constructor.
47       */
48      public CertificateExtensions() { }
49  
50      /**
51       * Create the object, decoding the values from the passed DER stream.
52       *
53       * @param in the DerInputStream to read the Extension from.
54       * @exception IOException on decoding errors.
55       */
56      public CertificateExtensions(DerInputStream in) throws IOException {
57          init(in);
58      }
59  
60      /**
61       * Decode the extensions from the InputStream.
62       *
63       * @param in the InputStream to unmarshal the contents from.
64       * @exception IOException on decoding or validity errors.
65       */
66      public void decode(InputStream in) throws IOException {
67          DerValue val = new DerValue(in);
68          init(val.data);
69      }
70  
71      // helper routine
72      private void init(DerInputStream in) throws IOException {
73  
74          DerValue[] exts = in.getSequence(5);
75  
76          for (int i = 0; i < exts.length; i++) {
77              Extension ext = new Extension(exts[i]);
78              parseExtension(ext);
79          }
80      }
81  
82      // Parse the encoded extension
83      private void parseExtension(Extension ext) throws IOException {
84          try {
85              Class extClass = OIDMap.getClass(ext.getExtensionId());
86              if (extClass == null) {   // Unsupported extension
87                  if (ext.isCritical())
88                      unsupportedCritExt = true;
89                  if (map.put(ext.getExtensionId().toString(), ext) == null)
90                      return;
91                  else
92                      throw new IOException("Duplicate extensions not allowed");
93              }
94              Class[] params = { Boolean.class, Object.class };
95              Constructor cons = extClass.getConstructor(params);
96  
97              byte[] extData = ext.getExtensionValue();
98              int extLen = extData.length;
99          Object value = Array.newInstance(byte.class, extLen);
100 
101         for (int i = 0; i < extLen; i++)
102             Array.setByte(value, i, extData[i]);
103         Object[] passed = new Object[] {new Boolean(ext.isCritical()),
104                                                         value};
105             CertAttrSet certExt = (CertAttrSet)cons.newInstance(passed);
106         if (map.put(certExt.getName(), certExt) != null)
107                 throw new IOException("Duplicate extensions not allowed");
108 
109         } catch (InvocationTargetException invk) {
110         Throwable e = invk.getTargetException();
111             throw (IOException)new IOException(e.toString()).initCause(e);
112     } catch (Exception e) {
113             throw (IOException)new IOException(e.toString()).initCause(e);
114         }
115     }
116 
117     /**
118      * Encode the extensions in DER form to the stream, setting
119      * the context specific tag as needed in the X.509 v3 certificate.
120      *
121      * @param out the DerOutputStream to marshal the contents to.
122      * @exception CertificateException on encoding errors.
123      * @exception IOException on errors.
124      */
125     public void encode(OutputStream out)
126     throws CertificateException, IOException {
127         encode(out, false);
128     }
129 
130     /**
131      * Encode the extensions in DER form to the stream.
132      *
133      * @param out the DerOutputStream to marshal the contents to.
134      * @param isCertReq if true then no context specific tag is added.
135      * @exception CertificateException on encoding errors.
136      * @exception IOException on errors.
137      */
138     public void encode(OutputStream out, boolean isCertReq)
139     throws CertificateException, IOException {
140         DerOutputStream extOut = new DerOutputStream();
141         Collection allExts = map.values();
142         Object[] objs = allExts.toArray();
143 
144         for (int i = 0; i < objs.length; i++) {
145             if (objs[i] instanceof CertAttrSet)
146                 ((CertAttrSet)objs[i]).encode(extOut);
147             else if (objs[i] instanceof Extension)
148                 ((Extension)objs[i]).encode(extOut);
149             else
150                 throw new CertificateException("Illegal extension object");
151         }
152 
153         DerOutputStream seq = new DerOutputStream();
154         seq.write(DerValue.tag_Sequence, extOut);
155 
156         DerOutputStream tmp;
157         if (!isCertReq) { // certificate
158             tmp = new DerOutputStream();
159             tmp.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)3),
160                   seq);
161         } else
162             tmp = seq; // pkcs#10 certificateRequest
163 
164         out.write(tmp.toByteArray());
165     }
166 
167     /**
168      * Set the attribute value.
169      * @param name the extension name used in the cache.
170      * @param obj the object to set.
171      * @exception IOException if the object could not be cached.
172      */
173     public void set(String name, Object obj) throws IOException {
174         if (obj instanceof Extension)
175             map.put(name, obj);
176         else
177             throw new IOException("Unknown extension type.");
178     }
179 
180     /**
181      * Get the attribute value.
182      * @param name the extension name used in the lookup.
183      * @exception IOException if named extension is not found.
184      */
185     public Object get(String name) throws IOException {
186         Object obj = map.get(name);
187         if (obj == null) {
188             throw new IOException("No extension found with name " + name);
189         }
190         return (obj);
191     }
192 
193     /**
194      * Delete the attribute value.
195      * @param name the extension name used in the lookup.
196      * @exception IOException if named extension is not found.
197      */
198     public void delete(String name) throws IOException {
199         Object obj = map.get(name);
200         if (obj == null) {
201             throw new IOException("No extension found with name " + name);
202         }
203         map.remove(name);
204     }
205 
206     /**
207      * Return an enumeration of names of attributes existing within this
208      * attribute.
209      */
210     public Enumeration getElements() {
211         return (map.elements());
212     }
213 
214     /**
215      * Return a collection view of the extensions.
216      * @return a collection view of the extensions in this Certificate.
217      */
218     public Collection getAllExtensions() {
219         return (map.values());
220     }
221 
222     /**
223      * Return the name of this attribute.
224      */
225     public String getName() {
226         return (NAME);
227     }
228 
229     /**
230      * Return true if a critical extension is found that is
231      * not supported, otherwise return false.
232      */
233     public boolean hasUnsupportedCriticalExtension() {
234         return (unsupportedCritExt);
235     }
236 
237     /**
238      * Compares this CertificateExtensions for equality with the specified
239      * object. If the <code>other</code> object is an
240      * <code>instanceof</code> <code>CertificateExtensions</code>, then
241      * all the entries are compared with the entries from this.
242      *
243      * @param other the object to test for equality with this CertificateExtensions.
244      * @return true iff all the entries match that of the Other,
245      * false otherwise.
246      */
247     public boolean equals(Object other) {
248         if (this == other)
249             return true;
250         if (!(other instanceof CertificateExtensions))
251             return false;
252         Collection otherC = ((CertificateExtensions)other).getAllExtensions();
253         Object[] objs = otherC.toArray();
254 
255         int len = objs.length;
256         if (len != map.size())
257             return false;
258 
259         Extension otherExt, thisExt;
260         String key = null;
261         for (int i = 0; i < len; i++) {
262             if (objs[i] instanceof CertAttrSet)
263                 key = ((CertAttrSet)objs[i]).getName();
264             otherExt = (Extension)objs[i];
265             if (key == null)
266                 key = otherExt.getExtensionId().toString();
267             thisExt = (Extension)map.get(key);
268             if (thisExt == null)
269                 return false;
270             if (! thisExt.equals(otherExt))
271                 return false;
272         }
273         return true;
274     }
275 
276     /**
277      * Returns a hashcode value for this CertificateExtensions.
278      *
279      * @return the hashcode value.
280      */
281     public int hashCode() {
282         return map.hashCode();
283     }
284 
285     /**
286      * Returns a string representation of this <tt>CertificateExtensions</tt>
287      * object in the form of a set of entries, enclosed in braces and separated
288      * by the ASCII characters "<tt>,&nbsp;</tt>" (comma and space).
289      * <p>Overrides to <tt>toString</tt> method of <tt>Object</tt>.
290      *
291      * @return  a string representation of this CertificateExtensions.
292      */
293     public String toString() {
294         return map.toString();
295     }
296 }
297