summaryrefslogtreecommitdiff
path: root/gnu/java/security/x509/X500DistinguishedName.java
blob: daf746f5dc5f32580983c927fff40bc72ea9420a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
/* X500DistinguishedName.java -- X.500 distinguished name.
   Copyright (C) 2004  Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */


package gnu.java.security.x509;

import gnu.java.security.OID;
import gnu.java.security.der.DER;
import gnu.java.security.der.DERReader;
import gnu.java.security.der.DERValue;

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class X500DistinguishedName implements Principal
{

  // Constants and fields.
  // -------------------------------------------------------------------------

  public static final OID CN         = new OID("2.5.4.3");
  public static final OID C          = new OID("2.5.4.6");
  public static final OID L          = new OID("2.5.4.7");
  public static final OID ST         = new OID("2.5.4.8");
  public static final OID STREET     = new OID("2.5.4.9");
  public static final OID O          = new OID("2.5.4.10");
  public static final OID OU         = new OID("2.5.4.11");
  public static final OID T          = new OID("2.5.4.12");
  public static final OID DNQ        = new OID("2.5.4.46");
  public static final OID NAME       = new OID("2.5.4.41");
  public static final OID GIVENNAME  = new OID("2.5.4.42");
  public static final OID INITIALS   = new OID("2.5.4.43");
  public static final OID GENERATION = new OID("2.5.4.44");
  public static final OID EMAIL      = new OID("1.2.840.113549.1.9.1");
  public static final OID DC         = new OID("0.9.2342.19200300.100.1.25");
  public static final OID UID        = new OID("0.9.2342.19200300.100.1.1");

  private List components;
  private Map currentRdn;
  private boolean fixed;
  private String stringRep;
  private byte[] encoded;

  // Constructors.
  // -------------------------------------------------------------------------

  public X500DistinguishedName()
  {
    components = new LinkedList();
    currentRdn = new LinkedHashMap();
    components.add(currentRdn);
  }

  public X500DistinguishedName(String name)
  {
    this();
    try
      {
        parseString(name);
      }
    catch (IOException ioe)
      {
        throw new IllegalArgumentException(ioe.toString());
      }
  }

  public X500DistinguishedName(byte[] encoded) throws IOException
  {
    this();
    parseDer(new DERReader(encoded));
  }

  public X500DistinguishedName(InputStream encoded) throws IOException
  {
    this();
    parseDer(new DERReader(encoded));
  }

  // Instance methods.
  // -------------------------------------------------------------------------

  public String getName()
  {
    return toString();
  }

  public void newRelativeDistinguishedName()
  {
    if (fixed || currentRdn.isEmpty()) return;
    currentRdn = new LinkedHashMap();
    components.add(currentRdn);
  }

  public int size()
  {
    return components.size();
  }

  public int countComponents()
  {
    int count = 0;
    for (Iterator it = components.iterator(); it.hasNext(); )
      {
        count += ((Map) it.next()).size();
      }
    return count;
  }

  public boolean containsComponent(OID oid, String value)
  {
    for (Iterator it = components.iterator(); it.hasNext(); )
      {
        Map rdn = (Map) it.next();
        String s = (String) rdn.get(oid);
        if (s == null)
          continue;
        if (compressWS(value).equalsIgnoreCase(compressWS(s)))
          return true;
      }
    return false;
  }

  public String getComponent(OID oid)
  {
    for (Iterator it = components.iterator(); it.hasNext(); )
      {
        Map rdn = (Map) it.next();
        if (rdn.containsKey(oid))
          return (String) rdn.get(oid);
      }
    return null;
  }

  public String getComponent(OID oid, int rdn)
  {
    if (rdn >= size())
      return null;
    return (String) ((Map) components.get(rdn)).get(oid);
  }

  public void putComponent(OID oid, String value)
  {
    currentRdn.put(oid, value);
  }

  public void putComponent(String name, String value)
  {
    name = name.trim().toLowerCase();
    if (name.equals("cn"))
      putComponent(CN, value);
    else if (name.equals("c"))
      putComponent(C, value);
    else if (name.equals("l"))
      putComponent(L, value);
    else if (name.equals("street"))
      putComponent(STREET, value);
    else if (name.equals("st"))
      putComponent(ST, value);
    else if (name.equals("t"))
      putComponent(T, value);
    else if (name.equals("dnq"))
      putComponent(DNQ, value);
    else if (name.equals("name"))
      putComponent(NAME, value);
    else if (name.equals("givenname"))
      putComponent(GIVENNAME, value);
    else if (name.equals("initials"))
      putComponent(INITIALS, value);
    else if (name.equals("generation"))
      putComponent(GENERATION, value);
    else if (name.equals("email"))
      putComponent(EMAIL, value);
    else if (name.equals("dc"))
      putComponent(DC, value);
    else if (name.equals("uid"))
      putComponent(UID, value);
    else
      putComponent(new OID(name), value);
  }

  public void setUnmodifiable()
  {
    if (fixed) return;
    fixed = true;
    List newComps = new ArrayList(components.size());
    for (Iterator it = components.iterator(); it.hasNext(); )
      {
        Map rdn = (Map) it.next();
        rdn = Collections.unmodifiableMap(rdn);
        newComps.add(rdn);
      }
    components = Collections.unmodifiableList(newComps);
    currentRdn = Collections.EMPTY_MAP;
  }

  public int hashCode()
  {
    int sum = 0;
    for (Iterator it = components.iterator(); it.hasNext(); )
      {
        Map m = (Map) it.next();
        for (Iterator it2 = m.entrySet().iterator(); it2.hasNext(); )
          {
            Map.Entry e = (Map.Entry) it2.next();
            sum += e.getKey().hashCode();
            sum += e.getValue().hashCode();
          }
      }
    return sum;
  }

  public boolean equals(Object o)
  {
    if (!(o instanceof X500DistinguishedName))
      return false;
    if (size() != ((X500DistinguishedName) o).size())
      return false;
    for (int i = 0; i < size(); i++)
      {
        Map m = (Map) components.get(i);
        for (Iterator it2 = m.entrySet().iterator(); it2.hasNext(); )
          {
            Map.Entry e = (Map.Entry) it2.next();
            OID oid = (OID) e.getKey();
            String v1 = (String) e.getValue();
            String v2 = ((X500DistinguishedName) o).getComponent(oid, i);
            if (!compressWS(v1).equalsIgnoreCase(compressWS(v2)))
              return false;
          }
      }
    return true;
  }

  public String toString()
  {
    if (fixed && stringRep != null)
      return stringRep;
    StringBuffer str = new StringBuffer();
    for (Iterator it = components.iterator(); it.hasNext(); )
      {
        Map m = (Map) it.next();
        for (Iterator it2 = m.entrySet().iterator(); it2.hasNext(); )
          {
            Map.Entry entry = (Map.Entry) it2.next();
            OID oid = (OID) entry.getKey();
            String value = (String) entry.getValue();
            if (oid.equals(CN))
              str.append("CN");
            else if (oid.equals(C))
              str.append("C");
            else if (oid.equals(L))
              str.append("L");
            else if (oid.equals(ST))
              str.append("ST");
            else if (oid.equals(STREET))
              str.append("STREET");
            else if (oid.equals(O))
              str.append("O");
            else if (oid.equals(OU))
              str.append("OU");
            else if (oid.equals(T))
              str.append("T");
            else if (oid.equals(DNQ))
              str.append("DNQ");
            else if (oid.equals(NAME))
              str.append("NAME");
            else
              str.append(oid.toString());
            str.append('=');
            str.append(value);
            if (it2.hasNext())
              str.append("+");
          }
        if (it.hasNext())
          str.append(',');
      }
    return (stringRep = str.toString());
  }

  public byte[] getDer()
  {
    if (fixed && encoded != null)
      return (byte[]) encoded.clone();
    ArrayList name = new ArrayList(components.size());
    for (Iterator it = components.iterator(); it.hasNext(); )
      {
        Map m = (Map) it.next();
        if (m.isEmpty())
          continue;
        Set rdn = new HashSet();
        for (Iterator it2 = m.entrySet().iterator(); it2.hasNext(); )
          {
            Map.Entry e = (Map.Entry) it.next();
            ArrayList atav = new ArrayList(2);
            atav.add(new DERValue(DER.OBJECT_IDENTIFIER, e.getKey()));
            atav.add(new DERValue(DER.UTF8_STRING, e.getValue()));
            rdn.add(new DERValue(DER.SEQUENCE|DER.CONSTRUCTED, atav));
          }
        name.add(new DERValue(DER.SET|DER.CONSTRUCTED, rdn));
      }
    DERValue val = new DERValue(DER.SEQUENCE|DER.CONSTRUCTED, name);
    return (byte[]) (encoded = val.getEncoded()).clone();
  }

  // Own methods.
  // -------------------------------------------------------------------------

  private int sep;

  private void parseString(String str) throws IOException
  {
    Reader in = new StringReader(str);
    while (true)
      {
        String key = readAttributeType(in);
        if (key == null)
          break;
        String value = readAttributeValue(in);
        putComponent(key, value);
        if (sep == ',')
          newRelativeDistinguishedName();
      }
    setUnmodifiable();
  }

  private String readAttributeType(Reader in) throws IOException
  {
    StringBuffer buf = new StringBuffer();
    int ch;
    while ((ch = in.read()) != '=')
      {
        if (ch == -1)
          {
            if (buf.length() > 0)
              throw new EOFException();
            return null;
          }
        if (ch > 127)
          throw new IOException("Invalid char: " + (char) ch);
        if (Character.isLetterOrDigit((char) ch) || ch == '-' || ch == '.')
          buf.append((char) ch);
        else
          throw new IOException("Invalid char: " + (char) ch);
      }
    return buf.toString();
  }

  private String readAttributeValue(Reader in) throws IOException
  {
    StringBuffer buf = new StringBuffer();
    int ch = in.read();
    if (ch == '#')
      {
        while (true)
          {
            ch = in.read();
            if (('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F')
                || Character.isDigit((char) ch))
              buf.append((char) ch);
            else if (ch == '+' || ch == ',')
              {
                sep = ch;
                String hex = buf.toString();
                return new String(Util.toByteArray(hex));
              }
            else
              throw new IOException("illegal character: " + (char) ch);
          }
      }
    else if (ch == '"')
      {
        while (true)
          {
            ch = in.read();
            if (ch == '"')
              break;
            else if (ch == '\\')
              {
                ch = in.read();
                if (ch == -1)
                  throw new EOFException();
                if (('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F')
                    || Character.isDigit((char) ch))
                  {
                    int i = Character.digit((char) ch, 16) << 4;
                    ch = in.read();
                    if (!(('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F')
                          || Character.isDigit((char) ch)))
                      throw new IOException("illegal hex char");
                    i |= Character.digit((char) ch, 16);
                    buf.append((char) i);
                  }
                else
                  buf.append((char) ch);
              }
            else
              buf.append((char) ch);
          }
        sep = in.read();
        if (sep != '+' || sep != ',')
          throw new IOException("illegal character: " + (char) ch);
        return buf.toString();
      }
    else
      {
        while (true)
          {
            switch (ch)
              {
              case '+':
              case ',':
                sep = ch;
                return buf.toString();
              case '\\':
                ch = in.read();
                if (ch == -1)
                  throw new EOFException();
                if (('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F')
                    || Character.isDigit((char) ch))
                  {
                    int i = Character.digit((char) ch, 16) << 4;
                    ch = in.read();
                    if (!(('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F')
                          || Character.isDigit((char) ch)))
                      throw new IOException("illegal hex char");
                    i |= Character.digit((char) ch, 16);
                    buf.append((char) i);
                  }
                else
                  buf.append((char) ch);
                break;
              case '=':
              case '<':
              case '>':
              case '#':
              case ';':
                throw new IOException("illegal character: " + (char) ch);
              case -1:
                throw new EOFException();
              default:
                buf.append((char) ch);
              }
          }
      }
  }

  private void parseDer(DERReader der) throws IOException
  {
    DERValue name = der.read();
    if (!name.isConstructed())
      throw new IOException("malformed Name");
    encoded = name.getEncoded();
    int len = 0;
    while (len < name.getLength())
      {
        DERValue rdn = der.read();
        if (!rdn.isConstructed())
          throw new IOException("badly formed RDNSequence");
        int len2 = 0;
        while (len2 < rdn.getLength())
          {
            DERValue atav = der.read();
            if (!atav.isConstructed())
              throw new IOException("badly formed AttributeTypeAndValue");
            DERValue val = der.read();
            if (val.getTag() != DER.OBJECT_IDENTIFIER)
              throw new IOException("badly formed AttributeTypeAndValue");
            OID oid = (OID) val.getValue();
            val = der.read();
            if (!(val.getValue() instanceof String))
              throw new IOException("badly formed AttributeTypeAndValue");
            String value = (String) val.getValue();
            putComponent(oid, value);
            len2 += atav.getEncodedLength();
          }
        len += rdn.getEncodedLength();
        if (len < name.getLength())
          newRelativeDistinguishedName();
      }
    setUnmodifiable();
  }

  private static String compressWS(String str)
  {
    StringBuffer buf = new StringBuffer();
    char lastChar = 0;
    for (int i = 0; i < str.length(); i++)
      {
        char c = str.charAt(i);
        if (Character.isWhitespace(c))
          {
            if (!Character.isWhitespace(lastChar))
              buf.append(' ');
          }
        else
          buf.append(c);
        lastChar = c;
      }
    return buf.toString().trim();
  }
}