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