blob: 9a6b7a59d1a41c58d958e0e6bf0fc00dd08ff6ae [file] [log] [blame]
J. Duke319a3b92007-12-01 00:00:00 +00001/*
2 * Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any questions.
24 */
25
26package sun.security.x509;
27
28import java.io.ByteArrayOutputStream;
29import java.io.IOException;
30import java.io.OutputStream;
31import java.io.Reader;
32import java.security.AccessController;
33import java.text.Normalizer;
34import java.util.*;
35
36import sun.security.action.GetBooleanAction;
37import sun.security.util.*;
38import sun.security.pkcs.PKCS9Attribute;
39
40
41/**
42 * X.500 Attribute-Value-Assertion (AVA): an attribute, as identified by
43 * some attribute ID, has some particular value. Values are as a rule ASN.1
44 * printable strings. A conventional set of type IDs is recognized when
45 * parsing (and generating) RFC 1779 or RFC 2253 syntax strings.
46 *
47 * <P>AVAs are components of X.500 relative names. Think of them as being
48 * individual fields of a database record. The attribute ID is how you
49 * identify the field, and the value is part of a particular record.
50 * <p>
51 * Note that instances of this class are immutable.
52 *
53 * @see X500Name
54 * @see RDN
55 *
56 *
57 * @author David Brownell
58 * @author Amit Kapoor
59 * @author Hemma Prafullchandra
60 */
61public class AVA implements DerEncoder {
62
63 private static final Debug debug = Debug.getInstance("x509", "\t[AVA]");
64 // See CR 6391482: if enabled this flag preserves the old but incorrect
65 // PrintableString encoding for DomainComponent. It may need to be set to
66 // avoid breaking preexisting certificates generated with sun.security APIs.
67 private static final boolean PRESERVE_OLD_DC_ENCODING =
68 AccessController.doPrivileged(new GetBooleanAction
69 ("com.sun.security.preserveOldDCEncoding"));
70
71 /**
72 * DEFAULT format allows both RFC1779 and RFC2253 syntax and
73 * additional keywords.
74 */
75 final static int DEFAULT = 1;
76 /**
77 * RFC1779 specifies format according to RFC1779.
78 */
79 final static int RFC1779 = 2;
80 /**
81 * RFC2253 specifies format according to RFC2253.
82 */
83 final static int RFC2253 = 3;
84
85 // currently not private, accessed directly from RDN
86 final ObjectIdentifier oid;
87 final DerValue value;
88
89 /*
90 * If the value has any of these characters in it, it must be quoted.
91 * Backslash and quote characters must also be individually escaped.
92 * Leading and trailing spaces, also multiple internal spaces, also
93 * call for quoting the whole string.
94 */
95 private static final String specialChars = ",+=\n<>#;";
96
97 /*
98 * In RFC2253, if the value has any of these characters in it, it
99 * must be quoted by a preceding \.
100 */
101 private static final String specialChars2253 = ",+\"\\<>;";
102
103 /*
104 * includes special chars from RFC1779 and RFC2253, as well as ' '
105 */
106 private static final String specialCharsAll = ",=\n+<>#;\\\" ";
107
108 /*
109 * Values that aren't printable strings are emitted as BER-encoded
110 * hex data.
111 */
112 private static final String hexDigits = "0123456789ABCDEF";
113
114 public AVA(ObjectIdentifier type, DerValue val) {
115 if ((type == null) || (val == null)) {
116 throw new NullPointerException();
117 }
118 oid = type;
119 value = val;
120 }
121
122 /**
123 * Parse an RFC 1779 or RFC 2253 style AVA string: CN=fee fie foe fum
124 * or perhaps with quotes. Not all defined AVA tags are supported;
125 * of current note are X.400 related ones (PRMD, ADMD, etc).
126 *
127 * This terminates at unescaped AVA separators ("+") or RDN
128 * separators (",", ";"), or DN terminators (">"), and removes
129 * cosmetic whitespace at the end of values.
130 */
131 AVA(Reader in) throws IOException {
132 this(in, DEFAULT);
133 }
134
135 /**
136 * Parse an RFC 1779 or RFC 2253 style AVA string: CN=fee fie foe fum
137 * or perhaps with quotes. Additional keywords can be specified in the
138 * keyword/OID map.
139 *
140 * This terminates at unescaped AVA separators ("+") or RDN
141 * separators (",", ";"), or DN terminators (">"), and removes
142 * cosmetic whitespace at the end of values.
143 */
144 AVA(Reader in, Map<String, String> keywordMap) throws IOException {
145 this(in, DEFAULT, keywordMap);
146 }
147
148 /**
149 * Parse an AVA string formatted according to format.
150 *
151 * XXX format RFC1779 should only allow RFC1779 syntax but is
152 * actually DEFAULT with RFC1779 keywords.
153 */
154 AVA(Reader in, int format) throws IOException {
155 this(in, format, Collections.<String, String>emptyMap());
156 }
157
158 /**
159 * Parse an AVA string formatted according to format.
160 *
161 * XXX format RFC1779 should only allow RFC1779 syntax but is
162 * actually DEFAULT with RFC1779 keywords.
163 *
164 * @param in Reader containing AVA String
165 * @param format parsing format
166 * @param keywordMap a Map where a keyword String maps to a corresponding
167 * OID String. Each AVA keyword will be mapped to the corresponding OID.
168 * If an entry does not exist, it will fallback to the builtin
169 * keyword/OID mapping.
170 * @throws IOException if the AVA String is not valid in the specified
171 * standard or an OID String from the keywordMap is improperly formatted
172 */
173 AVA(Reader in, int format, Map<String, String> keywordMap)
174 throws IOException {
175 // assume format is one of DEFAULT, RFC1779, RFC2253
176
177 StringBuilder temp = new StringBuilder();
178 int c;
179
180 /*
181 * First get the keyword indicating the attribute's type,
182 * and map it to the appropriate OID.
183 */
184 while (true) {
185 c = readChar(in, "Incorrect AVA format");
186 if (c == '=') {
187 break;
188 }
189 temp.append((char)c);
190 }
191
192 oid = AVAKeyword.getOID(temp.toString(), format, keywordMap);
193
194 /*
195 * Now parse the value. "#hex", a quoted string, or a string
196 * terminated by "+", ",", ";", ">". Whitespace before or after
197 * the value is stripped away unless format is RFC2253.
198 */
199 temp.setLength(0);
200 if (format == RFC2253) {
201 // read next character
202 c = in.read();
203 if (c == ' ') {
204 throw new IOException("Incorrect AVA RFC2253 format - " +
205 "leading space must be escaped");
206 }
207 } else {
208 // read next character skipping whitespace
209 do {
210 c = in.read();
211 } while ((c == ' ') || (c == '\n'));
212 }
213 if (c == -1) {
214 // empty value
215 value = new DerValue("");
216 return;
217 }
218
219 if (c == '#') {
220 value = parseHexString(in, format);
221 } else if ((c == '"') && (format != RFC2253)) {
222 value = parseQuotedString(in, temp);
223 } else {
224 value = parseString(in, c, format, temp);
225 }
226 }
227
228 /**
229 * Get the ObjectIdentifier of this AVA.
230 */
231 public ObjectIdentifier getObjectIdentifier() {
232 return oid;
233 }
234
235 /**
236 * Get the value of this AVA as a DerValue.
237 */
238 public DerValue getDerValue() {
239 return value;
240 }
241
242 /**
243 * Get the value of this AVA as a String.
244 *
245 * @exception RuntimeException if we could not obtain the string form
246 * (should not occur)
247 */
248 public String getValueString() {
249 try {
250 String s = value.getAsString();
251 if (s == null) {
252 throw new RuntimeException("AVA string is null");
253 }
254 return s;
255 } catch (IOException e) {
256 // should not occur
257 throw new RuntimeException("AVA error: " + e, e);
258 }
259 }
260
261 private static DerValue parseHexString
262 (Reader in, int format) throws IOException {
263
264 int c;
265 ByteArrayOutputStream baos = new ByteArrayOutputStream();
266 byte b = 0;
267 int cNdx = 0;
268 while (true) {
269 c = in.read();
270
271 if (isTerminator(c, format)) {
272 break;
273 }
274
275 int cVal = hexDigits.indexOf(Character.toUpperCase((char)c));
276
277 if (cVal == -1) {
278 throw new IOException("AVA parse, invalid hex " +
279 "digit: "+ (char)c);
280 }
281
282 if ((cNdx % 2) == 1) {
283 b = (byte)((b * 16) + (byte)(cVal));
284 baos.write(b);
285 } else {
286 b = (byte)(cVal);
287 }
288 cNdx++;
289 }
290
291 // throw exception if no hex digits
292 if (cNdx == 0) {
293 throw new IOException("AVA parse, zero hex digits");
294 }
295
296 // throw exception if odd number of hex digits
297 if (cNdx % 2 == 1) {
298 throw new IOException("AVA parse, odd number of hex digits");
299 }
300
301 return new DerValue(baos.toByteArray());
302 }
303
304 private DerValue parseQuotedString
305 (Reader in, StringBuilder temp) throws IOException {
306
307 // RFC1779 specifies that an entire RDN may be enclosed in double
308 // quotes. In this case the syntax is any sequence of
309 // backslash-specialChar, backslash-backslash,
310 // backslash-doublequote, or character other than backslash or
311 // doublequote.
312 int c = readChar(in, "Quoted string did not end in quote");
313
314 List<Byte> embeddedHex = new ArrayList<Byte>();
315 boolean isPrintableString = true;
316 while (c != '"') {
317 if (c == '\\') {
318 c = readChar(in, "Quoted string did not end in quote");
319
320 // check for embedded hex pairs
321 Byte hexByte = null;
322 if ((hexByte = getEmbeddedHexPair(c, in)) != null) {
323
324 // always encode AVAs with embedded hex as UTF8
325 isPrintableString = false;
326
327 // append consecutive embedded hex
328 // as single string later
329 embeddedHex.add(hexByte);
330 c = in.read();
331 continue;
332 }
333
334 if (c != '\\' && c != '"' &&
335 specialChars.indexOf((char)c) < 0) {
336 throw new IOException
337 ("Invalid escaped character in AVA: " +
338 (char)c);
339 }
340 }
341
342 // add embedded hex bytes before next char
343 if (embeddedHex.size() > 0) {
344 String hexString = getEmbeddedHexString(embeddedHex);
345 temp.append(hexString);
346 embeddedHex.clear();
347 }
348
349 // check for non-PrintableString chars
350 isPrintableString &= DerValue.isPrintableStringChar((char)c);
351 temp.append((char)c);
352 c = readChar(in, "Quoted string did not end in quote");
353 }
354
355 // add trailing embedded hex bytes
356 if (embeddedHex.size() > 0) {
357 String hexString = getEmbeddedHexString(embeddedHex);
358 temp.append(hexString);
359 embeddedHex.clear();
360 }
361
362 do {
363 c = in.read();
364 } while ((c == '\n') || (c == ' '));
365 if (c != -1) {
366 throw new IOException("AVA had characters other than "
367 + "whitespace after terminating quote");
368 }
369
370 // encode as PrintableString unless value contains
371 // non-PrintableString chars
372 if (this.oid.equals(PKCS9Attribute.EMAIL_ADDRESS_OID) ||
373 (this.oid.equals(X500Name.DOMAIN_COMPONENT_OID) &&
374 PRESERVE_OLD_DC_ENCODING == false)) {
375 // EmailAddress and DomainComponent must be IA5String
376 return new DerValue(DerValue.tag_IA5String,
377 temp.toString().trim());
378 } else if (isPrintableString) {
379 return new DerValue(temp.toString().trim());
380 } else {
381 return new DerValue(DerValue.tag_UTF8String,
382 temp.toString().trim());
383 }
384 }
385
386 private DerValue parseString
387 (Reader in, int c, int format, StringBuilder temp) throws IOException {
388
389 List<Byte> embeddedHex = new ArrayList<Byte>();
390 boolean isPrintableString = true;
391 boolean escape = false;
392 boolean leadingChar = true;
393 int spaceCount = 0;
394 do {
395 escape = false;
396 if (c == '\\') {
397 escape = true;
398 c = readChar(in, "Invalid trailing backslash");
399
400 // check for embedded hex pairs
401 Byte hexByte = null;
402 if ((hexByte = getEmbeddedHexPair(c, in)) != null) {
403
404 // always encode AVAs with embedded hex as UTF8
405 isPrintableString = false;
406
407 // append consecutive embedded hex
408 // as single string later
409 embeddedHex.add(hexByte);
410 c = in.read();
411 leadingChar = false;
412 continue;
413 }
414
415 // check if character was improperly escaped
416 if ((format == DEFAULT &&
417 specialCharsAll.indexOf((char)c) == -1) ||
418 (format == RFC1779 &&
419 specialChars.indexOf((char)c) == -1 &&
420 c != '\\' && c != '\"')) {
421
422 throw new IOException
423 ("Invalid escaped character in AVA: '" +
424 (char)c + "'");
425
426 } else if (format == RFC2253) {
427 if (c == ' ') {
428 // only leading/trailing space can be escaped
429 if (!leadingChar && !trailingSpace(in)) {
430 throw new IOException
431 ("Invalid escaped space character " +
432 "in AVA. Only a leading or trailing " +
433 "space character can be escaped.");
434 }
435 } else if (c == '#') {
436 // only leading '#' can be escaped
437 if (!leadingChar) {
438 throw new IOException
439 ("Invalid escaped '#' character in AVA. " +
440 "Only a leading '#' can be escaped.");
441 }
442 } else if (specialChars2253.indexOf((char)c) == -1) {
443 throw new IOException
444 ("Invalid escaped character in AVA: '" +
445 (char)c + "'");
446
447 }
448 }
449
450 } else {
451 // check if character should have been escaped
452 if (format == RFC2253) {
453 if (specialChars2253.indexOf((char)c) != -1) {
454 throw new IOException
455 ("Character '" + (char)c +
456 "' in AVA appears without escape");
457 }
458 }
459 }
460
461 // add embedded hex bytes before next char
462 if (embeddedHex.size() > 0) {
463 // add space(s) before embedded hex bytes
464 for (int i = 0; i < spaceCount; i++) {
465 temp.append(" ");
466 }
467 spaceCount = 0;
468
469 String hexString = getEmbeddedHexString(embeddedHex);
470 temp.append(hexString);
471 embeddedHex.clear();
472 }
473
474 // check for non-PrintableString chars
475 isPrintableString &= DerValue.isPrintableStringChar((char)c);
476 if (c == ' ' && escape == false) {
477 // do not add non-escaped spaces yet
478 // (non-escaped trailing spaces are ignored)
479 spaceCount++;
480 } else {
481 // add space(s)
482 for (int i = 0; i < spaceCount; i++) {
483 temp.append(" ");
484 }
485 spaceCount = 0;
486 temp.append((char)c);
487 }
488 c = in.read();
489 leadingChar = false;
490 } while (isTerminator(c, format) == false);
491
492 if (format == RFC2253 && spaceCount > 0) {
493 throw new IOException("Incorrect AVA RFC2253 format - " +
494 "trailing space must be escaped");
495 }
496
497 // add trailing embedded hex bytes
498 if (embeddedHex.size() > 0) {
499 String hexString = getEmbeddedHexString(embeddedHex);
500 temp.append(hexString);
501 embeddedHex.clear();
502 }
503
504 // encode as PrintableString unless value contains
505 // non-PrintableString chars
506 if (this.oid.equals(PKCS9Attribute.EMAIL_ADDRESS_OID) ||
507 (this.oid.equals(X500Name.DOMAIN_COMPONENT_OID) &&
508 PRESERVE_OLD_DC_ENCODING == false)) {
509 // EmailAddress and DomainComponent must be IA5String
510 return new DerValue(DerValue.tag_IA5String, temp.toString());
511 } else if (isPrintableString) {
512 return new DerValue(temp.toString());
513 } else {
514 return new DerValue(DerValue.tag_UTF8String, temp.toString());
515 }
516 }
517
518 private static Byte getEmbeddedHexPair(int c1, Reader in)
519 throws IOException {
520
521 if (hexDigits.indexOf(Character.toUpperCase((char)c1)) >= 0) {
522 int c2 = readChar(in, "unexpected EOF - " +
523 "escaped hex value must include two valid digits");
524
525 if (hexDigits.indexOf(Character.toUpperCase((char)c2)) >= 0) {
526 int hi = Character.digit((char)c1, 16);
527 int lo = Character.digit((char)c2, 16);
528 return new Byte((byte)((hi<<4) + lo));
529 } else {
530 throw new IOException
531 ("escaped hex value must include two valid digits");
532 }
533 }
534 return null;
535 }
536
537 private static String getEmbeddedHexString(List<Byte> hexList)
538 throws IOException {
539 int n = hexList.size();
540 byte[] hexBytes = new byte[n];
541 for (int i = 0; i < n; i++) {
542 hexBytes[i] = hexList.get(i).byteValue();
543 }
544 return new String(hexBytes, "UTF8");
545 }
546
547 private static boolean isTerminator(int ch, int format) {
548 switch (ch) {
549 case -1:
550 case '+':
551 case ',':
552 return true;
553 case ';':
554 case '>':
555 return format != RFC2253;
556 default:
557 return false;
558 }
559 }
560
561 private static int readChar(Reader in, String errMsg) throws IOException {
562 int c = in.read();
563 if (c == -1) {
564 throw new IOException(errMsg);
565 }
566 return c;
567 }
568
569 private static boolean trailingSpace(Reader in) throws IOException {
570
571 boolean trailing = false;
572
573 if (!in.markSupported()) {
574 // oh well
575 return true;
576 } else {
577 // make readAheadLimit huge -
578 // in practice, AVA was passed a StringReader from X500Name,
579 // and StringReader ignores readAheadLimit anyways
580 in.mark(9999);
581 while (true) {
582 int nextChar = in.read();
583 if (nextChar == -1) {
584 trailing = true;
585 break;
586 } else if (nextChar == ' ') {
587 continue;
588 } else if (nextChar == '\\') {
589 int followingChar = in.read();
590 if (followingChar != ' ') {
591 trailing = false;
592 break;
593 }
594 } else {
595 trailing = false;
596 break;
597 }
598 }
599
600 in.reset();
601 return trailing;
602 }
603 }
604
605 AVA(DerValue derval) throws IOException {
606 // Individual attribute value assertions are SEQUENCE of two values.
607 // That'd be a "struct" outside of ASN.1.
608 if (derval.tag != DerValue.tag_Sequence) {
609 throw new IOException("AVA not a sequence");
610 }
611 oid = X500Name.intern(derval.data.getOID());
612 value = derval.data.getDerValue();
613
614 if (derval.data.available() != 0) {
615 throw new IOException("AVA, extra bytes = "
616 + derval.data.available());
617 }
618 }
619
620 AVA(DerInputStream in) throws IOException {
621 this(in.getDerValue());
622 }
623
624 public boolean equals(Object obj) {
625 if (this == obj) {
626 return true;
627 }
628 if (obj instanceof AVA == false) {
629 return false;
630 }
631 AVA other = (AVA)obj;
632 return this.toRFC2253CanonicalString().equals
633 (other.toRFC2253CanonicalString());
634 }
635
636 /**
637 * Returns a hashcode for this AVA.
638 *
639 * @return a hashcode for this AVA.
640 */
641 public int hashCode() {
642 return toRFC2253CanonicalString().hashCode();
643 }
644
645 /*
646 * AVAs are encoded as a SEQUENCE of two elements.
647 */
648 public void encode(DerOutputStream out) throws IOException {
649 derEncode(out);
650 }
651
652 /**
653 * DER encode this object onto an output stream.
654 * Implements the <code>DerEncoder</code> interface.
655 *
656 * @param out
657 * the output stream on which to write the DER encoding.
658 *
659 * @exception IOException on encoding error.
660 */
661 public void derEncode(OutputStream out) throws IOException {
662 DerOutputStream tmp = new DerOutputStream();
663 DerOutputStream tmp2 = new DerOutputStream();
664
665 tmp.putOID(oid);
666 value.encode(tmp);
667 tmp2.write(DerValue.tag_Sequence, tmp);
668 out.write(tmp2.toByteArray());
669 }
670
671 private String toKeyword(int format, Map<String, String> oidMap) {
672 return AVAKeyword.getKeyword(oid, format, oidMap);
673 }
674
675 /**
676 * Returns a printable form of this attribute, using RFC 1779
677 * syntax for individual attribute/value assertions.
678 */
679 public String toString() {
680 return toKeywordValueString
681 (toKeyword(DEFAULT, Collections.<String, String>emptyMap()));
682 }
683
684 /**
685 * Returns a printable form of this attribute, using RFC 1779
686 * syntax for individual attribute/value assertions. It only
687 * emits standardised keywords.
688 */
689 public String toRFC1779String() {
690 return toRFC1779String(Collections.<String, String>emptyMap());
691 }
692
693 /**
694 * Returns a printable form of this attribute, using RFC 1779
695 * syntax for individual attribute/value assertions. It
696 * emits standardised keywords, as well as keywords contained in the
697 * OID/keyword map.
698 */
699 public String toRFC1779String(Map<String, String> oidMap) {
700 return toKeywordValueString(toKeyword(RFC1779, oidMap));
701 }
702
703 /**
704 * Returns a printable form of this attribute, using RFC 2253
705 * syntax for individual attribute/value assertions. It only
706 * emits standardised keywords.
707 */
708 public String toRFC2253String() {
709 return toRFC2253String(Collections.<String, String>emptyMap());
710 }
711
712 /**
713 * Returns a printable form of this attribute, using RFC 2253
714 * syntax for individual attribute/value assertions. It
715 * emits standardised keywords, as well as keywords contained in the
716 * OID/keyword map.
717 */
718 public String toRFC2253String(Map<String, String> oidMap) {
719 /*
720 * Section 2.3: The AttributeTypeAndValue is encoded as the string
721 * representation of the AttributeType, followed by an equals character
722 * ('=' ASCII 61), followed by the string representation of the
723 * AttributeValue. The encoding of the AttributeValue is given in
724 * section 2.4.
725 */
726 StringBuilder typeAndValue = new StringBuilder(100);
727 typeAndValue.append(toKeyword(RFC2253, oidMap));
728 typeAndValue.append('=');
729
730 /*
731 * Section 2.4: Converting an AttributeValue from ASN.1 to a String.
732 * If the AttributeValue is of a type which does not have a string
733 * representation defined for it, then it is simply encoded as an
734 * octothorpe character ('#' ASCII 35) followed by the hexadecimal
735 * representation of each of the bytes of the BER encoding of the X.500
736 * AttributeValue. This form SHOULD be used if the AttributeType is of
737 * the dotted-decimal form.
738 */
739 if ((typeAndValue.charAt(0) >= '0' && typeAndValue.charAt(0) <= '9') ||
740 !isDerString(value, false))
741 {
742 byte[] data = null;
743 try {
744 data = value.toByteArray();
745 } catch (IOException ie) {
746 throw new IllegalArgumentException("DER Value conversion");
747 }
748 typeAndValue.append('#');
749 for (int j = 0; j < data.length; j++) {
750 byte b = data[j];
751 typeAndValue.append(Character.forDigit(0xF & (b >>> 4), 16));
752 typeAndValue.append(Character.forDigit(0xF & b, 16));
753 }
754 } else {
755 /*
756 * 2.4 (cont): Otherwise, if the AttributeValue is of a type which
757 * has a string representation, the value is converted first to a
758 * UTF-8 string according to its syntax specification.
759 *
760 * NOTE: this implementation only emits DirectoryStrings of the
761 * types returned by isDerString().
762 */
763 String valStr = null;
764 try {
765 valStr = new String(value.getDataBytes(), "UTF8");
766 } catch (IOException ie) {
767 throw new IllegalArgumentException("DER Value conversion");
768 }
769
770 /*
771 * 2.4 (cont): If the UTF-8 string does not have any of the
772 * following characters which need escaping, then that string can be
773 * used as the string representation of the value.
774 *
775 * o a space or "#" character occurring at the beginning of the
776 * string
777 * o a space character occurring at the end of the string
778 * o one of the characters ",", "+", """, "\", "<", ">" or ";"
779 *
780 * Implementations MAY escape other characters.
781 *
782 * NOTE: this implementation also recognizes "=" and "#" as
783 * characters which need escaping.
784 *
785 * If a character to be escaped is one of the list shown above, then
786 * it is prefixed by a backslash ('\' ASCII 92).
787 *
788 * Otherwise the character to be escaped is replaced by a backslash
789 * and two hex digits, which form a single byte in the code of the
790 * character.
791 */
792 final String escapees = ",=+<>#;\"\\";
793 StringBuilder sbuffer = new StringBuilder();
794
795 for (int i = 0; i < valStr.length(); i++) {
796 char c = valStr.charAt(i);
797 if (DerValue.isPrintableStringChar(c) ||
798 escapees.indexOf(c) >= 0) {
799
800 // escape escapees
801 if (escapees.indexOf(c) >= 0) {
802 sbuffer.append('\\');
803 }
804
805 // append printable/escaped char
806 sbuffer.append(c);
807
808 } else if (debug != null && Debug.isOn("ava")) {
809
810 // embed non-printable/non-escaped char
811 // as escaped hex pairs for debugging
812 byte[] valueBytes = null;
813 try {
814 valueBytes = Character.toString(c).getBytes("UTF8");
815 } catch (IOException ie) {
816 throw new IllegalArgumentException
817 ("DER Value conversion");
818 }
819 for (int j = 0; j < valueBytes.length; j++) {
820 sbuffer.append('\\');
821 char hexChar = Character.forDigit
822 (0xF & (valueBytes[j] >>> 4), 16);
823 sbuffer.append(Character.toUpperCase(hexChar));
824 hexChar = Character.forDigit
825 (0xF & (valueBytes[j]), 16);
826 sbuffer.append(Character.toUpperCase(hexChar));
827 }
828 } else {
829
830 // append non-printable/non-escaped char
831 sbuffer.append(c);
832 }
833 }
834
835 char[] chars = sbuffer.toString().toCharArray();
836 sbuffer = new StringBuilder();
837
838 // Find leading and trailing whitespace.
839 int lead; // index of first char that is not leading whitespace
840 for (lead = 0; lead < chars.length; lead++) {
841 if (chars[lead] != ' ' && chars[lead] != '\r') {
842 break;
843 }
844 }
845 int trail; // index of last char that is not trailing whitespace
846 for (trail = chars.length - 1; trail >= 0; trail--) {
847 if (chars[trail] != ' ' && chars[trail] != '\r') {
848 break;
849 }
850 }
851
852 // escape leading and trailing whitespace
853 for (int i = 0; i < chars.length; i++) {
854 char c = chars[i];
855 if (i < lead || i > trail) {
856 sbuffer.append('\\');
857 }
858 sbuffer.append(c);
859 }
860 typeAndValue.append(sbuffer.toString());
861 }
862 return typeAndValue.toString();
863 }
864
865 public String toRFC2253CanonicalString() {
866 /*
867 * Section 2.3: The AttributeTypeAndValue is encoded as the string
868 * representation of the AttributeType, followed by an equals character
869 * ('=' ASCII 61), followed by the string representation of the
870 * AttributeValue. The encoding of the AttributeValue is given in
871 * section 2.4.
872 */
873 StringBuilder typeAndValue = new StringBuilder(40);
874 typeAndValue.append
875 (toKeyword(RFC2253, Collections.<String, String>emptyMap()));
876 typeAndValue.append('=');
877
878 /*
879 * Section 2.4: Converting an AttributeValue from ASN.1 to a String.
880 * If the AttributeValue is of a type which does not have a string
881 * representation defined for it, then it is simply encoded as an
882 * octothorpe character ('#' ASCII 35) followed by the hexadecimal
883 * representation of each of the bytes of the BER encoding of the X.500
884 * AttributeValue. This form SHOULD be used if the AttributeType is of
885 * the dotted-decimal form.
886 */
887 if ((typeAndValue.charAt(0) >= '0' && typeAndValue.charAt(0) <= '9') ||
888 !isDerString(value, true))
889 {
890 byte[] data = null;
891 try {
892 data = value.toByteArray();
893 } catch (IOException ie) {
894 throw new IllegalArgumentException("DER Value conversion");
895 }
896 typeAndValue.append('#');
897 for (int j = 0; j < data.length; j++) {
898 byte b = data[j];
899 typeAndValue.append(Character.forDigit(0xF & (b >>> 4), 16));
900 typeAndValue.append(Character.forDigit(0xF & b, 16));
901 }
902 } else {
903 /*
904 * 2.4 (cont): Otherwise, if the AttributeValue is of a type which
905 * has a string representation, the value is converted first to a
906 * UTF-8 string according to its syntax specification.
907 *
908 * NOTE: this implementation only emits DirectoryStrings of the
909 * types returned by isDerString().
910 */
911 String valStr = null;
912 try {
913 valStr = new String(value.getDataBytes(), "UTF8");
914 } catch (IOException ie) {
915 throw new IllegalArgumentException("DER Value conversion");
916 }
917
918 /*
919 * 2.4 (cont): If the UTF-8 string does not have any of the
920 * following characters which need escaping, then that string can be
921 * used as the string representation of the value.
922 *
923 * o a space or "#" character occurring at the beginning of the
924 * string
925 * o a space character occurring at the end of the string
926 *
927 * o one of the characters ",", "+", """, "\", "<", ">" or ";"
928 *
929 * If a character to be escaped is one of the list shown above, then
930 * it is prefixed by a backslash ('\' ASCII 92).
931 *
932 * Otherwise the character to be escaped is replaced by a backslash
933 * and two hex digits, which form a single byte in the code of the
934 * character.
935 */
936 final String escapees = ",+<>;\"\\";
937 StringBuilder sbuffer = new StringBuilder();
938 boolean previousWhite = false;
939
940 for (int i = 0; i < valStr.length(); i++) {
941 char c = valStr.charAt(i);
942
943 if (DerValue.isPrintableStringChar(c) ||
944 escapees.indexOf(c) >= 0 ||
945 (i == 0 && c == '#')) {
946
947 // escape leading '#' and escapees
948 if ((i == 0 && c == '#') || escapees.indexOf(c) >= 0) {
949 sbuffer.append('\\');
950 }
951
952 // convert multiple whitespace to single whitespace
953 if (!Character.isWhitespace(c)) {
954 previousWhite = false;
955 sbuffer.append(c);
956 } else {
957 if (previousWhite == false) {
958 // add single whitespace
959 previousWhite = true;
960 sbuffer.append(c);
961 } else {
962 // ignore subsequent consecutive whitespace
963 continue;
964 }
965 }
966
967 } else if (debug != null && Debug.isOn("ava")) {
968
969 // embed non-printable/non-escaped char
970 // as escaped hex pairs for debugging
971
972 previousWhite = false;
973
974 byte valueBytes[] = null;
975 try {
976 valueBytes = Character.toString(c).getBytes("UTF8");
977 } catch (IOException ie) {
978 throw new IllegalArgumentException
979 ("DER Value conversion");
980 }
981 for (int j = 0; j < valueBytes.length; j++) {
982 sbuffer.append('\\');
983 sbuffer.append(Character.forDigit
984 (0xF & (valueBytes[j] >>> 4), 16));
985 sbuffer.append(Character.forDigit
986 (0xF & (valueBytes[j]), 16));
987 }
988 } else {
989
990 // append non-printable/non-escaped char
991
992 previousWhite = false;
993 sbuffer.append(c);
994 }
995 }
996
997 // remove leading and trailing whitespace from value
998 typeAndValue.append(sbuffer.toString().trim());
999 }
1000
1001 String canon = typeAndValue.toString();
1002 canon = canon.toUpperCase(Locale.US).toLowerCase(Locale.US);
1003 return Normalizer.normalize(canon, Normalizer.Form.NFKD);
1004 }
1005
1006 /*
1007 * Return true if DerValue can be represented as a String.
1008 */
1009 private static boolean isDerString(DerValue value, boolean canonical) {
1010 if (canonical) {
1011 switch (value.tag) {
1012 case DerValue.tag_PrintableString:
1013 case DerValue.tag_UTF8String:
1014 return true;
1015 default:
1016 return false;
1017 }
1018 } else {
1019 switch (value.tag) {
1020 case DerValue.tag_PrintableString:
1021 case DerValue.tag_T61String:
1022 case DerValue.tag_IA5String:
1023 case DerValue.tag_GeneralString:
1024 case DerValue.tag_BMPString:
1025 case DerValue.tag_UTF8String:
1026 return true;
1027 default:
1028 return false;
1029 }
1030 }
1031 }
1032
1033 boolean hasRFC2253Keyword() {
1034 return AVAKeyword.hasKeyword(oid, RFC2253);
1035 }
1036
1037 private String toKeywordValueString(String keyword) {
1038 /*
1039 * Construct the value with as little copying and garbage
1040 * production as practical. First the keyword (mandatory),
1041 * then the equals sign, finally the value.
1042 */
1043 StringBuilder retval = new StringBuilder(40);
1044
1045 retval.append(keyword);
1046 retval.append("=");
1047
1048 try {
1049 String valStr = value.getAsString();
1050
1051 if (valStr == null) {
1052
1053 // rfc1779 specifies that attribute values associated
1054 // with non-standard keyword attributes may be represented
1055 // using the hex format below. This will be used only
1056 // when the value is not a string type
1057
1058 byte data [] = value.toByteArray();
1059
1060 retval.append('#');
1061 for (int i = 0; i < data.length; i++) {
1062 retval.append(hexDigits.charAt((data [i] >> 4) & 0x0f));
1063 retval.append(hexDigits.charAt(data [i] & 0x0f));
1064 }
1065
1066 } else {
1067
1068 boolean quoteNeeded = false;
1069 StringBuilder sbuffer = new StringBuilder();
1070 boolean previousWhite = false;
1071 final String escapees = ",+=\n<>#;\\\"";
1072
1073 /*
1074 * Special characters (e.g. AVA list separators) cause strings
1075 * to need quoting, or at least escaping. So do leading or
1076 * trailing spaces, and multiple internal spaces.
1077 */
1078 for (int i = 0; i < valStr.length(); i++) {
1079 char c = valStr.charAt(i);
1080 if (DerValue.isPrintableStringChar(c) ||
1081 escapees.indexOf(c) >= 0) {
1082
1083 // quote if leading whitespace or special chars
1084 if (!quoteNeeded &&
1085 ((i == 0 && (c == ' ' || c == '\n')) ||
1086 escapees.indexOf(c) >= 0)) {
1087 quoteNeeded = true;
1088 }
1089
1090 // quote if multiple internal whitespace
1091 if (!(c == ' ' || c == '\n')) {
1092 // escape '"' and '\'
1093 if (c == '"' || c == '\\') {
1094 sbuffer.append('\\');
1095 }
1096 previousWhite = false;
1097 } else {
1098 if (!quoteNeeded && previousWhite) {
1099 quoteNeeded = true;
1100 }
1101 previousWhite = true;
1102 }
1103
1104 sbuffer.append(c);
1105
1106 } else if (debug != null && Debug.isOn("ava")) {
1107
1108 // embed non-printable/non-escaped char
1109 // as escaped hex pairs for debugging
1110
1111 previousWhite = false;
1112
1113 // embed escaped hex pairs
1114 byte[] valueBytes =
1115 Character.toString(c).getBytes("UTF8");
1116 for (int j = 0; j < valueBytes.length; j++) {
1117 sbuffer.append('\\');
1118 char hexChar = Character.forDigit
1119 (0xF & (valueBytes[j] >>> 4), 16);
1120 sbuffer.append(Character.toUpperCase(hexChar));
1121 hexChar = Character.forDigit
1122 (0xF & (valueBytes[j]), 16);
1123 sbuffer.append(Character.toUpperCase(hexChar));
1124 }
1125 } else {
1126
1127 // append non-printable/non-escaped char
1128
1129 previousWhite = false;
1130 sbuffer.append(c);
1131 }
1132 }
1133
1134 // quote if trailing whitespace
1135 if (sbuffer.length() > 0) {
1136 char trailChar = sbuffer.charAt(sbuffer.length() - 1);
1137 if (trailChar == ' ' || trailChar == '\n') {
1138 quoteNeeded = true;
1139 }
1140 }
1141
1142 // Emit the string ... quote it if needed
1143 if (quoteNeeded) {
1144 retval.append("\"" + sbuffer.toString() + "\"");
1145 } else {
1146 retval.append(sbuffer.toString());
1147 }
1148 }
1149 } catch (IOException e) {
1150 throw new IllegalArgumentException("DER Value conversion");
1151 }
1152
1153 return retval.toString();
1154 }
1155
1156}
1157
1158/**
1159 * Helper class that allows conversion from String to ObjectIdentifier and
1160 * vice versa according to RFC1779, RFC2253, and an augmented version of
1161 * those standards.
1162 */
1163class AVAKeyword {
1164
1165 private static final Map<ObjectIdentifier,AVAKeyword> oidMap;
1166 private static final Map<String,AVAKeyword> keywordMap;
1167
1168 private String keyword;
1169 private ObjectIdentifier oid;
1170 private boolean rfc1779Compliant, rfc2253Compliant;
1171
1172 private AVAKeyword(String keyword, ObjectIdentifier oid,
1173 boolean rfc1779Compliant, boolean rfc2253Compliant) {
1174 this.keyword = keyword;
1175 this.oid = oid;
1176 this.rfc1779Compliant = rfc1779Compliant;
1177 this.rfc2253Compliant = rfc2253Compliant;
1178
1179 // register it
1180 oidMap.put(oid, this);
1181 keywordMap.put(keyword, this);
1182 }
1183
1184 private boolean isCompliant(int standard) {
1185 switch (standard) {
1186 case AVA.RFC1779:
1187 return rfc1779Compliant;
1188 case AVA.RFC2253:
1189 return rfc2253Compliant;
1190 case AVA.DEFAULT:
1191 return true;
1192 default:
1193 // should not occur, internal error
1194 throw new IllegalArgumentException("Invalid standard " + standard);
1195 }
1196 }
1197
1198 /**
1199 * Get an object identifier representing the specified keyword (or
1200 * string encoded object identifier) in the given standard.
1201 *
1202 * @throws IOException If the keyword is not valid in the specified standard
1203 */
1204 static ObjectIdentifier getOID(String keyword, int standard)
1205 throws IOException {
1206 return getOID
1207 (keyword, standard, Collections.<String, String>emptyMap());
1208 }
1209
1210 /**
1211 * Get an object identifier representing the specified keyword (or
1212 * string encoded object identifier) in the given standard.
1213 *
1214 * @param keywordMap a Map where a keyword String maps to a corresponding
1215 * OID String. Each AVA keyword will be mapped to the corresponding OID.
1216 * If an entry does not exist, it will fallback to the builtin
1217 * keyword/OID mapping.
1218 * @throws IOException If the keyword is not valid in the specified standard
1219 * or the OID String to which a keyword maps to is improperly formatted.
1220 */
1221 static ObjectIdentifier getOID
1222 (String keyword, int standard, Map<String, String> extraKeywordMap)
1223 throws IOException {
1224
1225 keyword = keyword.toUpperCase();
1226 if (standard == AVA.RFC2253) {
1227 if (keyword.startsWith(" ") || keyword.endsWith(" ")) {
1228 throw new IOException("Invalid leading or trailing space " +
1229 "in keyword \"" + keyword + "\"");
1230 }
1231 } else {
1232 keyword = keyword.trim();
1233 }
1234
1235 // check user-specified keyword map first, then fallback to built-in
1236 // map
1237 String oidString = extraKeywordMap.get(keyword);
1238 if (oidString == null) {
1239 AVAKeyword ak = keywordMap.get(keyword);
1240 if ((ak != null) && ak.isCompliant(standard)) {
1241 return ak.oid;
1242 }
1243 } else {
1244 return new ObjectIdentifier(oidString);
1245 }
1246
1247 // no keyword found or not standard compliant, check if OID string
1248
1249 // RFC1779 requires, DEFAULT allows OID. prefix
1250 if (standard == AVA.RFC1779) {
1251 if (keyword.startsWith("OID.") == false) {
1252 throw new IOException("Invalid RFC1779 keyword: " + keyword);
1253 }
1254 keyword = keyword.substring(4);
1255 } else if (standard == AVA.DEFAULT) {
1256 if (keyword.startsWith("OID.")) {
1257 keyword = keyword.substring(4);
1258 }
1259 }
1260 boolean number = false;
1261 if (keyword.length() != 0) {
1262 char ch = keyword.charAt(0);
1263 if ((ch >= '0') && (ch <= '9')) {
1264 number = true;
1265 }
1266 }
1267 if (number == false) {
1268 throw new IOException("Invalid keyword \"" + keyword + "\"");
1269 }
1270 return new ObjectIdentifier(keyword);
1271 }
1272
1273 /**
1274 * Get a keyword for the given ObjectIdentifier according to standard.
1275 * If no keyword is available, the ObjectIdentifier is encoded as a
1276 * String.
1277 */
1278 static String getKeyword(ObjectIdentifier oid, int standard) {
1279 return getKeyword
1280 (oid, standard, Collections.<String, String>emptyMap());
1281 }
1282
1283 /**
1284 * Get a keyword for the given ObjectIdentifier according to standard.
1285 * Checks the extraOidMap for a keyword first, then falls back to the
1286 * builtin/default set. If no keyword is available, the ObjectIdentifier
1287 * is encoded as a String.
1288 */
1289 static String getKeyword
1290 (ObjectIdentifier oid, int standard, Map<String, String> extraOidMap) {
1291
1292 // check extraOidMap first, then fallback to built-in map
1293 String oidString = oid.toString();
1294 String keywordString = extraOidMap.get(oidString);
1295 if (keywordString == null) {
1296 AVAKeyword ak = oidMap.get(oid);
1297 if ((ak != null) && ak.isCompliant(standard)) {
1298 return ak.keyword;
1299 }
1300 } else {
1301 if (keywordString.length() == 0) {
1302 throw new IllegalArgumentException("keyword cannot be empty");
1303 }
1304 keywordString = keywordString.trim();
1305 char c = keywordString.charAt(0);
1306 if (c < 65 || c > 122 || (c > 90 && c < 97)) {
1307 throw new IllegalArgumentException
1308 ("keyword does not start with letter");
1309 }
1310 for (int i=1; i<keywordString.length(); i++) {
1311 c = keywordString.charAt(i);
1312 if ((c < 65 || c > 122 || (c > 90 && c < 97)) &&
1313 (c < 48 || c > 57) && c != '_') {
1314 throw new IllegalArgumentException
1315 ("keyword character is not a letter, digit, or underscore");
1316 }
1317 }
1318 return keywordString;
1319 }
1320 // no compliant keyword, use OID
1321 if (standard == AVA.RFC2253) {
1322 return oidString;
1323 } else {
1324 return "OID." + oidString;
1325 }
1326 }
1327
1328 /**
1329 * Test if oid has an associated keyword in standard.
1330 */
1331 static boolean hasKeyword(ObjectIdentifier oid, int standard) {
1332 AVAKeyword ak = oidMap.get(oid);
1333 if (ak == null) {
1334 return false;
1335 }
1336 return ak.isCompliant(standard);
1337 }
1338
1339 static {
1340 oidMap = new HashMap<ObjectIdentifier,AVAKeyword>();
1341 keywordMap = new HashMap<String,AVAKeyword>();
1342
1343 // NOTE if multiple keywords are available for one OID, order
1344 // is significant!! Preferred *LAST*.
1345 new AVAKeyword("CN", X500Name.commonName_oid, true, true);
1346 new AVAKeyword("C", X500Name.countryName_oid, true, true);
1347 new AVAKeyword("L", X500Name.localityName_oid, true, true);
1348 new AVAKeyword("S", X500Name.stateName_oid, false, false);
1349 new AVAKeyword("ST", X500Name.stateName_oid, true, true);
1350 new AVAKeyword("O", X500Name.orgName_oid, true, true);
1351 new AVAKeyword("OU", X500Name.orgUnitName_oid, true, true);
1352 new AVAKeyword("T", X500Name.title_oid, false, false);
1353 new AVAKeyword("IP", X500Name.ipAddress_oid, false, false);
1354 new AVAKeyword("STREET", X500Name.streetAddress_oid,true, true);
1355 new AVAKeyword("DC", X500Name.DOMAIN_COMPONENT_OID,
1356 false, true);
1357 new AVAKeyword("DNQUALIFIER", X500Name.DNQUALIFIER_OID, false, false);
1358 new AVAKeyword("DNQ", X500Name.DNQUALIFIER_OID, false, false);
1359 new AVAKeyword("SURNAME", X500Name.SURNAME_OID, false, false);
1360 new AVAKeyword("GIVENNAME", X500Name.GIVENNAME_OID, false, false);
1361 new AVAKeyword("INITIALS", X500Name.INITIALS_OID, false, false);
1362 new AVAKeyword("GENERATION", X500Name.GENERATIONQUALIFIER_OID,
1363 false, false);
1364 new AVAKeyword("EMAIL", PKCS9Attribute.EMAIL_ADDRESS_OID, false, false);
1365 new AVAKeyword("EMAILADDRESS", PKCS9Attribute.EMAIL_ADDRESS_OID,
1366 false, false);
1367 new AVAKeyword("UID", X500Name.userid_oid, false, true);
1368 new AVAKeyword("SERIALNUMBER", X500Name.SERIALNUMBER_OID, false, false);
1369 }
1370}