Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openjdk-multiarch-jdk8u
Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/security/util/DerValue.java
38830 views
1
/**
2
* Copyright (c) 1996, 2017, 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.util;
27
28
import java.io.*;
29
import java.math.BigInteger;
30
import java.util.Date;
31
import sun.misc.IOUtils;
32
33
/**
34
* Represents a single DER-encoded value. DER encoding rules are a subset
35
* of the "Basic" Encoding Rules (BER), but they only support a single way
36
* ("Definite" encoding) to encode any given value.
37
*
38
* <P>All DER-encoded data are triples <em>{type, length, data}</em>. This
39
* class represents such tagged values as they have been read (or constructed),
40
* and provides structured access to the encoded data.
41
*
42
* <P>At this time, this class supports only a subset of the types of DER
43
* data encodings which are defined. That subset is sufficient for parsing
44
* most X.509 certificates, and working with selected additional formats
45
* (such as PKCS #10 certificate requests, and some kinds of PKCS #7 data).
46
*
47
* A note with respect to T61/Teletex strings: From RFC 1617, section 4.1.3
48
* and RFC 5280, section 8, we assume that this kind of string will contain
49
* ISO-8859-1 characters only.
50
*
51
*
52
* @author David Brownell
53
* @author Amit Kapoor
54
* @author Hemma Prafullchandra
55
*/
56
public class DerValue {
57
/** The tag class types */
58
public static final byte TAG_UNIVERSAL = (byte)0x000;
59
public static final byte TAG_APPLICATION = (byte)0x040;
60
public static final byte TAG_CONTEXT = (byte)0x080;
61
public static final byte TAG_PRIVATE = (byte)0x0c0;
62
63
/** The DER tag of the value; one of the tag_ constants. */
64
public byte tag;
65
66
protected DerInputBuffer buffer;
67
68
/**
69
* The DER-encoded data of the value, never null
70
*/
71
public final DerInputStream data;
72
73
private int length;
74
75
/*
76
* The type starts at the first byte of the encoding, and
77
* is one of these tag_* values. That may be all the type
78
* data that is needed.
79
*/
80
81
/*
82
* These tags are the "universal" tags ... they mean the same
83
* in all contexts. (Mask with 0x1f -- five bits.)
84
*/
85
86
/** Tag value indicating an ASN.1 "BOOLEAN" value. */
87
public final static byte tag_Boolean = 0x01;
88
89
/** Tag value indicating an ASN.1 "INTEGER" value. */
90
public final static byte tag_Integer = 0x02;
91
92
/** Tag value indicating an ASN.1 "BIT STRING" value. */
93
public final static byte tag_BitString = 0x03;
94
95
/** Tag value indicating an ASN.1 "OCTET STRING" value. */
96
public final static byte tag_OctetString = 0x04;
97
98
/** Tag value indicating an ASN.1 "NULL" value. */
99
public final static byte tag_Null = 0x05;
100
101
/** Tag value indicating an ASN.1 "OBJECT IDENTIFIER" value. */
102
public final static byte tag_ObjectId = 0x06;
103
104
/** Tag value including an ASN.1 "ENUMERATED" value */
105
public final static byte tag_Enumerated = 0x0A;
106
107
/** Tag value indicating an ASN.1 "UTF8String" value. */
108
public final static byte tag_UTF8String = 0x0C;
109
110
/** Tag value including a "printable" string */
111
public final static byte tag_PrintableString = 0x13;
112
113
/** Tag value including a "teletype" string */
114
public final static byte tag_T61String = 0x14;
115
116
/** Tag value including an ASCII string */
117
public final static byte tag_IA5String = 0x16;
118
119
/** Tag value indicating an ASN.1 "UTCTime" value. */
120
public final static byte tag_UtcTime = 0x17;
121
122
/** Tag value indicating an ASN.1 "GeneralizedTime" value. */
123
public final static byte tag_GeneralizedTime = 0x18;
124
125
/** Tag value indicating an ASN.1 "GenerallString" value. */
126
public final static byte tag_GeneralString = 0x1B;
127
128
/** Tag value indicating an ASN.1 "UniversalString" value. */
129
public final static byte tag_UniversalString = 0x1C;
130
131
/** Tag value indicating an ASN.1 "BMPString" value. */
132
public final static byte tag_BMPString = 0x1E;
133
134
// CONSTRUCTED seq/set
135
136
/**
137
* Tag value indicating an ASN.1
138
* "SEQUENCE" (zero to N elements, order is significant).
139
*/
140
public final static byte tag_Sequence = 0x30;
141
142
/**
143
* Tag value indicating an ASN.1
144
* "SEQUENCE OF" (one to N elements, order is significant).
145
*/
146
public final static byte tag_SequenceOf = 0x30;
147
148
/**
149
* Tag value indicating an ASN.1
150
* "SET" (zero to N members, order does not matter).
151
*/
152
public final static byte tag_Set = 0x31;
153
154
/**
155
* Tag value indicating an ASN.1
156
* "SET OF" (one to N members, order does not matter).
157
*/
158
public final static byte tag_SetOf = 0x31;
159
160
/*
161
* These values are the high order bits for the other kinds of tags.
162
*/
163
164
/**
165
* Returns true if the tag class is UNIVERSAL.
166
*/
167
public boolean isUniversal() { return ((tag & 0x0c0) == 0x000); }
168
169
/**
170
* Returns true if the tag class is APPLICATION.
171
*/
172
public boolean isApplication() { return ((tag & 0x0c0) == 0x040); }
173
174
/**
175
* Returns true iff the CONTEXT SPECIFIC bit is set in the type tag.
176
* This is associated with the ASN.1 "DEFINED BY" syntax.
177
*/
178
public boolean isContextSpecific() { return ((tag & 0x0c0) == 0x080); }
179
180
/**
181
* Returns true iff the CONTEXT SPECIFIC TAG matches the passed tag.
182
*/
183
public boolean isContextSpecific(byte cntxtTag) {
184
if (!isContextSpecific()) {
185
return false;
186
}
187
return ((tag & 0x01f) == cntxtTag);
188
}
189
190
boolean isPrivate() { return ((tag & 0x0c0) == 0x0c0); }
191
192
/** Returns true iff the CONSTRUCTED bit is set in the type tag. */
193
public boolean isConstructed() { return ((tag & 0x020) == 0x020); }
194
195
/**
196
* Returns true iff the CONSTRUCTED TAG matches the passed tag.
197
*/
198
public boolean isConstructed(byte constructedTag) {
199
if (!isConstructed()) {
200
return false;
201
}
202
return ((tag & 0x01f) == constructedTag);
203
}
204
205
/**
206
* Creates a PrintableString or UTF8string DER value from a string
207
*/
208
public DerValue(String value) throws IOException {
209
boolean isPrintableString = true;
210
for (int i = 0; i < value.length(); i++) {
211
if (!isPrintableStringChar(value.charAt(i))) {
212
isPrintableString = false;
213
break;
214
}
215
}
216
217
data = init(isPrintableString ? tag_PrintableString : tag_UTF8String, value);
218
}
219
220
/**
221
* Creates a string type DER value from a String object
222
* @param stringTag the tag for the DER value to create
223
* @param value the String object to use for the DER value
224
*/
225
public DerValue(byte stringTag, String value) throws IOException {
226
data = init(stringTag, value);
227
}
228
229
// Creates a DerValue from a tag and some DER-encoded data w/ additional
230
// arg to control whether DER checks are enforced.
231
DerValue(byte tag, byte[] data, boolean allowBER) {
232
this.tag = tag;
233
buffer = new DerInputBuffer(data.clone(), allowBER);
234
length = data.length;
235
this.data = new DerInputStream(buffer);
236
this.data.mark(Integer.MAX_VALUE);
237
}
238
239
/**
240
* Creates a DerValue from a tag and some DER-encoded data.
241
*
242
* @param tag the DER type tag
243
* @param data the DER-encoded data
244
*/
245
public DerValue(byte tag, byte[] data) {
246
this(tag, data, true);
247
}
248
249
/*
250
* package private
251
*/
252
DerValue(DerInputBuffer in) throws IOException {
253
254
// XXX must also parse BER-encoded constructed
255
// values such as sequences, sets...
256
tag = (byte)in.read();
257
byte lenByte = (byte)in.read();
258
length = DerInputStream.getLength(lenByte, in);
259
if (length == -1) { // indefinite length encoding found
260
DerInputBuffer inbuf = in.dup();
261
int readLen = inbuf.available();
262
int offset = 2; // for tag and length bytes
263
byte[] indefData = new byte[readLen + offset];
264
indefData[0] = tag;
265
indefData[1] = lenByte;
266
DataInputStream dis = new DataInputStream(inbuf);
267
dis.readFully(indefData, offset, readLen);
268
dis.close();
269
DerIndefLenConverter derIn = new DerIndefLenConverter();
270
inbuf = new DerInputBuffer(derIn.convert(indefData), in.allowBER);
271
if (tag != inbuf.read())
272
throw new IOException
273
("Indefinite length encoding not supported");
274
length = DerInputStream.getDefiniteLength(inbuf);
275
buffer = inbuf.dup();
276
buffer.truncate(length);
277
data = new DerInputStream(buffer);
278
// indefinite form is encoded by sending a length field with a
279
// length of 0. - i.e. [1000|0000].
280
// the object is ended by sending two zero bytes.
281
in.skip(length + offset);
282
} else {
283
284
buffer = in.dup();
285
buffer.truncate(length);
286
data = new DerInputStream(buffer);
287
288
in.skip(length);
289
}
290
}
291
292
// Get an ASN.1/DER encoded datum from a buffer w/ additional
293
// arg to control whether DER checks are enforced.
294
DerValue(byte[] buf, boolean allowBER) throws IOException {
295
data = init(true, new ByteArrayInputStream(buf), allowBER);
296
}
297
298
/**
299
* Get an ASN.1/DER encoded datum from a buffer. The
300
* entire buffer must hold exactly one datum, including
301
* its tag and length.
302
*
303
* @param buf buffer holding a single DER-encoded datum.
304
*/
305
public DerValue(byte[] buf) throws IOException {
306
this(buf, true);
307
}
308
309
// Get an ASN.1/DER encoded datum from part of a buffer w/ additional
310
// arg to control whether DER checks are enforced.
311
DerValue(byte[] buf, int offset, int len, boolean allowBER)
312
throws IOException {
313
data = init(true, new ByteArrayInputStream(buf, offset, len), allowBER);
314
}
315
316
/**
317
* Get an ASN.1/DER encoded datum from part of a buffer.
318
* That part of the buffer must hold exactly one datum, including
319
* its tag and length.
320
*
321
* @param buf the buffer
322
* @param offset start point of the single DER-encoded dataum
323
* @param length how many bytes are in the encoded datum
324
*/
325
public DerValue(byte[] buf, int offset, int len) throws IOException {
326
this(buf, offset, len, true);
327
}
328
329
// Get an ASN1/DER encoded datum from an input stream w/ additional
330
// arg to control whether DER checks are enforced.
331
DerValue(InputStream in, boolean allowBER) throws IOException {
332
data = init(false, in, allowBER);
333
}
334
335
/**
336
* Get an ASN1/DER encoded datum from an input stream. The
337
* stream may have additional data following the encoded datum.
338
* In case of indefinite length encoded datum, the input stream
339
* must hold only one datum.
340
*
341
* @param in the input stream holding a single DER datum,
342
* which may be followed by additional data
343
*/
344
public DerValue(InputStream in) throws IOException {
345
this(in, true);
346
}
347
348
private DerInputStream init(byte stringTag, String value)
349
throws IOException {
350
String enc = null;
351
352
tag = stringTag;
353
354
switch (stringTag) {
355
case tag_PrintableString:
356
case tag_IA5String:
357
case tag_GeneralString:
358
enc = "ASCII";
359
break;
360
case tag_T61String:
361
enc = "ISO-8859-1";
362
break;
363
case tag_BMPString:
364
enc = "UnicodeBigUnmarked";
365
break;
366
case tag_UTF8String:
367
enc = "UTF8";
368
break;
369
// TBD: Need encoder for UniversalString before it can
370
// be handled.
371
default:
372
throw new IllegalArgumentException("Unsupported DER string type");
373
}
374
375
byte[] buf = value.getBytes(enc);
376
length = buf.length;
377
buffer = new DerInputBuffer(buf, true);
378
DerInputStream result = new DerInputStream(buffer);
379
result.mark(Integer.MAX_VALUE);
380
return result;
381
}
382
383
/*
384
* helper routine
385
*/
386
private DerInputStream init(boolean fullyBuffered, InputStream in,
387
boolean allowBER) throws IOException {
388
389
tag = (byte)in.read();
390
byte lenByte = (byte)in.read();
391
length = DerInputStream.getLength(lenByte, in);
392
if (length == -1) { // indefinite length encoding found
393
int readLen = in.available();
394
int offset = 2; // for tag and length bytes
395
byte[] indefData = new byte[readLen + offset];
396
indefData[0] = tag;
397
indefData[1] = lenByte;
398
DataInputStream dis = new DataInputStream(in);
399
dis.readFully(indefData, offset, readLen);
400
dis.close();
401
DerIndefLenConverter derIn = new DerIndefLenConverter();
402
in = new ByteArrayInputStream(derIn.convert(indefData));
403
if (tag != in.read())
404
throw new IOException
405
("Indefinite length encoding not supported");
406
length = DerInputStream.getDefiniteLength(in);
407
}
408
409
if (fullyBuffered && in.available() != length)
410
throw new IOException("extra data given to DerValue constructor");
411
412
byte[] bytes = IOUtils.readExactlyNBytes(in, length);
413
414
buffer = new DerInputBuffer(bytes, allowBER);
415
return new DerInputStream(buffer);
416
}
417
418
/**
419
* Encode an ASN1/DER encoded datum onto a DER output stream.
420
*/
421
public void encode(DerOutputStream out)
422
throws IOException {
423
out.write(tag);
424
out.putLength(length);
425
// XXX yeech, excess copies ... DerInputBuffer.write(OutStream)
426
if (length > 0) {
427
byte[] value = new byte[length];
428
// always synchronized on data
429
synchronized (data) {
430
buffer.reset();
431
if (buffer.read(value) != length) {
432
throw new IOException("short DER value read (encode)");
433
}
434
out.write(value);
435
}
436
}
437
}
438
439
public final DerInputStream getData() {
440
return data;
441
}
442
443
public final byte getTag() {
444
return tag;
445
}
446
447
/**
448
* Returns an ASN.1 BOOLEAN
449
*
450
* @return the boolean held in this DER value
451
*/
452
public boolean getBoolean() throws IOException {
453
if (tag != tag_Boolean) {
454
throw new IOException("DerValue.getBoolean, not a BOOLEAN " + tag);
455
}
456
if (length != 1) {
457
throw new IOException("DerValue.getBoolean, invalid length "
458
+ length);
459
}
460
if (buffer.read() != 0) {
461
return true;
462
}
463
return false;
464
}
465
466
/**
467
* Returns an ASN.1 OBJECT IDENTIFIER.
468
*
469
* @return the OID held in this DER value
470
*/
471
public ObjectIdentifier getOID() throws IOException {
472
if (tag != tag_ObjectId)
473
throw new IOException("DerValue.getOID, not an OID " + tag);
474
return new ObjectIdentifier(buffer);
475
}
476
477
private byte[] append(byte[] a, byte[] b) {
478
if (a == null)
479
return b;
480
481
byte[] ret = new byte[a.length + b.length];
482
System.arraycopy(a, 0, ret, 0, a.length);
483
System.arraycopy(b, 0, ret, a.length, b.length);
484
485
return ret;
486
}
487
488
/**
489
* Returns an ASN.1 OCTET STRING
490
*
491
* @return the octet string held in this DER value
492
*/
493
public byte[] getOctetString() throws IOException {
494
495
if (tag != tag_OctetString && !isConstructed(tag_OctetString)) {
496
throw new IOException(
497
"DerValue.getOctetString, not an Octet String: " + tag);
498
}
499
// Note: do not attempt to call buffer.read(bytes) at all. There's a
500
// known bug that it returns -1 instead of 0.
501
if (length == 0) {
502
return new byte[0];
503
}
504
505
// Only allocate the array if there are enough bytes available.
506
// This only works for ByteArrayInputStream.
507
// The assignment below ensures that buffer has the required type.
508
ByteArrayInputStream arrayInput = buffer;
509
if (arrayInput.available() < length) {
510
throw new IOException("short read on DerValue buffer");
511
}
512
byte[] bytes = new byte[length];
513
arrayInput.read(bytes);
514
515
if (isConstructed()) {
516
DerInputStream in = new DerInputStream(bytes, 0, bytes.length,
517
buffer.allowBER);
518
bytes = null;
519
while (in.available() != 0) {
520
bytes = append(bytes, in.getOctetString());
521
}
522
}
523
return bytes;
524
}
525
526
/**
527
* Returns an ASN.1 INTEGER value as an integer.
528
*
529
* @return the integer held in this DER value.
530
*/
531
public int getInteger() throws IOException {
532
if (tag != tag_Integer) {
533
throw new IOException("DerValue.getInteger, not an int " + tag);
534
}
535
return buffer.getInteger(data.available());
536
}
537
538
/**
539
* Returns an ASN.1 INTEGER value as a BigInteger.
540
*
541
* @return the integer held in this DER value as a BigInteger.
542
*/
543
public BigInteger getBigInteger() throws IOException {
544
if (tag != tag_Integer)
545
throw new IOException("DerValue.getBigInteger, not an int " + tag);
546
return buffer.getBigInteger(data.available(), false);
547
}
548
549
/**
550
* Returns an ASN.1 INTEGER value as a positive BigInteger.
551
* This is just to deal with implementations that incorrectly encode
552
* some values as negative.
553
*
554
* @return the integer held in this DER value as a BigInteger.
555
*/
556
public BigInteger getPositiveBigInteger() throws IOException {
557
if (tag != tag_Integer)
558
throw new IOException("DerValue.getBigInteger, not an int " + tag);
559
return buffer.getBigInteger(data.available(), true);
560
}
561
562
/**
563
* Returns an ASN.1 ENUMERATED value.
564
*
565
* @return the integer held in this DER value.
566
*/
567
public int getEnumerated() throws IOException {
568
if (tag != tag_Enumerated) {
569
throw new IOException("DerValue.getEnumerated, incorrect tag: "
570
+ tag);
571
}
572
return buffer.getInteger(data.available());
573
}
574
575
/**
576
* Returns an ASN.1 BIT STRING value. The bit string must be byte-aligned.
577
*
578
* @return the bit string held in this value
579
*/
580
public byte[] getBitString() throws IOException {
581
if (tag != tag_BitString)
582
throw new IOException(
583
"DerValue.getBitString, not a bit string " + tag);
584
585
return buffer.getBitString();
586
}
587
588
/**
589
* Returns an ASN.1 BIT STRING value that need not be byte-aligned.
590
*
591
* @return a BitArray representing the bit string held in this value
592
*/
593
public BitArray getUnalignedBitString() throws IOException {
594
if (tag != tag_BitString)
595
throw new IOException(
596
"DerValue.getBitString, not a bit string " + tag);
597
598
return buffer.getUnalignedBitString();
599
}
600
601
/**
602
* Returns the name component as a Java string, regardless of its
603
* encoding restrictions (ASCII, T61, Printable, IA5, BMP, UTF8).
604
*/
605
// TBD: Need encoder for UniversalString before it can be handled.
606
public String getAsString() throws IOException {
607
if (tag == tag_UTF8String)
608
return getUTF8String();
609
else if (tag == tag_PrintableString)
610
return getPrintableString();
611
else if (tag == tag_T61String)
612
return getT61String();
613
else if (tag == tag_IA5String)
614
return getIA5String();
615
/*
616
else if (tag == tag_UniversalString)
617
return getUniversalString();
618
*/
619
else if (tag == tag_BMPString)
620
return getBMPString();
621
else if (tag == tag_GeneralString)
622
return getGeneralString();
623
else
624
return null;
625
}
626
627
/**
628
* Returns an ASN.1 BIT STRING value, with the tag assumed implicit
629
* based on the parameter. The bit string must be byte-aligned.
630
*
631
* @params tagImplicit if true, the tag is assumed implicit.
632
* @return the bit string held in this value
633
*/
634
public byte[] getBitString(boolean tagImplicit) throws IOException {
635
if (!tagImplicit) {
636
if (tag != tag_BitString)
637
throw new IOException("DerValue.getBitString, not a bit string "
638
+ tag);
639
}
640
return buffer.getBitString();
641
}
642
643
/**
644
* Returns an ASN.1 BIT STRING value, with the tag assumed implicit
645
* based on the parameter. The bit string need not be byte-aligned.
646
*
647
* @params tagImplicit if true, the tag is assumed implicit.
648
* @return the bit string held in this value
649
*/
650
public BitArray getUnalignedBitString(boolean tagImplicit)
651
throws IOException {
652
if (!tagImplicit) {
653
if (tag != tag_BitString)
654
throw new IOException("DerValue.getBitString, not a bit string "
655
+ tag);
656
}
657
return buffer.getUnalignedBitString();
658
}
659
660
/**
661
* Helper routine to return all the bytes contained in the
662
* DerInputStream associated with this object.
663
*/
664
public byte[] getDataBytes() throws IOException {
665
byte[] retVal = new byte[length];
666
synchronized (data) {
667
data.reset();
668
data.getBytes(retVal);
669
}
670
return retVal;
671
}
672
673
/**
674
* Returns an ASN.1 STRING value
675
*
676
* @return the printable string held in this value
677
*/
678
public String getPrintableString()
679
throws IOException {
680
if (tag != tag_PrintableString)
681
throw new IOException(
682
"DerValue.getPrintableString, not a string " + tag);
683
684
return new String(getDataBytes(), "ASCII");
685
}
686
687
/**
688
* Returns an ASN.1 T61 (Teletype) STRING value
689
*
690
* @return the teletype string held in this value
691
*/
692
public String getT61String() throws IOException {
693
if (tag != tag_T61String)
694
throw new IOException(
695
"DerValue.getT61String, not T61 " + tag);
696
697
return new String(getDataBytes(), "ISO-8859-1");
698
}
699
700
/**
701
* Returns an ASN.1 IA5 (ASCII) STRING value
702
*
703
* @return the ASCII string held in this value
704
*/
705
public String getIA5String() throws IOException {
706
if (tag != tag_IA5String)
707
throw new IOException(
708
"DerValue.getIA5String, not IA5 " + tag);
709
710
return new String(getDataBytes(), "ASCII");
711
}
712
713
/**
714
* Returns the ASN.1 BMP (Unicode) STRING value as a Java string.
715
*
716
* @return a string corresponding to the encoded BMPString held in
717
* this value
718
*/
719
public String getBMPString() throws IOException {
720
if (tag != tag_BMPString)
721
throw new IOException(
722
"DerValue.getBMPString, not BMP " + tag);
723
724
// BMPString is the same as Unicode in big endian, unmarked
725
// format.
726
return new String(getDataBytes(), "UnicodeBigUnmarked");
727
}
728
729
/**
730
* Returns the ASN.1 UTF-8 STRING value as a Java String.
731
*
732
* @return a string corresponding to the encoded UTF8String held in
733
* this value
734
*/
735
public String getUTF8String() throws IOException {
736
if (tag != tag_UTF8String)
737
throw new IOException(
738
"DerValue.getUTF8String, not UTF-8 " + tag);
739
740
return new String(getDataBytes(), "UTF8");
741
}
742
743
/**
744
* Returns the ASN.1 GENERAL STRING value as a Java String.
745
*
746
* @return a string corresponding to the encoded GeneralString held in
747
* this value
748
*/
749
public String getGeneralString() throws IOException {
750
if (tag != tag_GeneralString)
751
throw new IOException(
752
"DerValue.getGeneralString, not GeneralString " + tag);
753
754
return new String(getDataBytes(), "ASCII");
755
}
756
757
/**
758
* Returns a Date if the DerValue is UtcTime.
759
*
760
* @return the Date held in this DER value
761
*/
762
public Date getUTCTime() throws IOException {
763
if (tag != tag_UtcTime) {
764
throw new IOException("DerValue.getUTCTime, not a UtcTime: " + tag);
765
}
766
return buffer.getUTCTime(data.available());
767
}
768
769
/**
770
* Returns a Date if the DerValue is GeneralizedTime.
771
*
772
* @return the Date held in this DER value
773
*/
774
public Date getGeneralizedTime() throws IOException {
775
if (tag != tag_GeneralizedTime) {
776
throw new IOException(
777
"DerValue.getGeneralizedTime, not a GeneralizedTime: " + tag);
778
}
779
return buffer.getGeneralizedTime(data.available());
780
}
781
782
/**
783
* Bitwise equality comparison. DER encoded values have a single
784
* encoding, so that bitwise equality of the encoded values is an
785
* efficient way to establish equivalence of the unencoded values.
786
*
787
* @param other the object being compared with this one
788
*/
789
@Override
790
public boolean equals(Object o) {
791
if (this == o) {
792
return true;
793
}
794
if (!(o instanceof DerValue)) {
795
return false;
796
}
797
DerValue other = (DerValue) o;
798
if (tag != other.tag) {
799
return false;
800
}
801
if (data == other.data) {
802
return true;
803
}
804
805
// make sure the order of lock is always consistent to avoid a deadlock
806
return (System.identityHashCode(this.data)
807
> System.identityHashCode(other.data)) ?
808
doEquals(this, other):
809
doEquals(other, this);
810
}
811
812
/**
813
* Helper for public method equals()
814
*/
815
private static boolean doEquals(DerValue d1, DerValue d2) {
816
synchronized (d1.data) {
817
synchronized (d2.data) {
818
d1.data.reset();
819
d2.data.reset();
820
return d1.buffer.equals(d2.buffer);
821
}
822
}
823
}
824
825
/**
826
* Returns a printable representation of the value.
827
*
828
* @return printable representation of the value
829
*/
830
@Override
831
public String toString() {
832
try {
833
834
String str = getAsString();
835
if (str != null)
836
return "\"" + str + "\"";
837
if (tag == tag_Null)
838
return "[DerValue, null]";
839
if (tag == tag_ObjectId)
840
return "OID." + getOID();
841
842
// integers
843
else
844
return "[DerValue, tag = " + tag
845
+ ", length = " + length + "]";
846
} catch (IOException e) {
847
throw new IllegalArgumentException("misformatted DER value");
848
}
849
}
850
851
/**
852
* Returns a DER-encoded value, such that if it's passed to the
853
* DerValue constructor, a value equivalent to "this" is returned.
854
*
855
* @return DER-encoded value, including tag and length.
856
*/
857
public byte[] toByteArray() throws IOException {
858
DerOutputStream out = new DerOutputStream();
859
860
encode(out);
861
data.reset();
862
return out.toByteArray();
863
}
864
865
/**
866
* For "set" and "sequence" types, this function may be used
867
* to return a DER stream of the members of the set or sequence.
868
* This operation is not supported for primitive types such as
869
* integers or bit strings.
870
*/
871
public DerInputStream toDerInputStream() throws IOException {
872
if (tag == tag_Sequence || tag == tag_Set)
873
return new DerInputStream(buffer);
874
throw new IOException("toDerInputStream rejects tag type " + tag);
875
}
876
877
/**
878
* Get the length of the encoded value.
879
*/
880
public int length() {
881
return length;
882
}
883
884
/**
885
* Determine if a character is one of the permissible characters for
886
* PrintableString:
887
* A-Z, a-z, 0-9, space, apostrophe (39), left and right parentheses,
888
* plus sign, comma, hyphen, period, slash, colon, equals sign,
889
* and question mark.
890
*
891
* Characters that are *not* allowed in PrintableString include
892
* exclamation point, quotation mark, number sign, dollar sign,
893
* percent sign, ampersand, asterisk, semicolon, less than sign,
894
* greater than sign, at sign, left and right square brackets,
895
* backslash, circumflex (94), underscore, back quote (96),
896
* left and right curly brackets, vertical line, tilde,
897
* and the control codes (0-31 and 127).
898
*
899
* This list is based on X.680 (the ASN.1 spec).
900
*/
901
public static boolean isPrintableStringChar(char ch) {
902
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
903
(ch >= '0' && ch <= '9')) {
904
return true;
905
} else {
906
switch (ch) {
907
case ' ': /* space */
908
case '\'': /* apostrophe */
909
case '(': /* left paren */
910
case ')': /* right paren */
911
case '+': /* plus */
912
case ',': /* comma */
913
case '-': /* hyphen */
914
case '.': /* period */
915
case '/': /* slash */
916
case ':': /* colon */
917
case '=': /* equals */
918
case '?': /* question mark */
919
return true;
920
default:
921
return false;
922
}
923
}
924
}
925
926
/**
927
* Create the tag of the attribute.
928
*
929
* @params class the tag class type, one of UNIVERSAL, CONTEXT,
930
* APPLICATION or PRIVATE
931
* @params form if true, the value is constructed, otherwise it
932
* is primitive.
933
* @params val the tag value
934
*/
935
public static byte createTag(byte tagClass, boolean form, byte val) {
936
byte tag = (byte)(tagClass | val);
937
if (form) {
938
tag |= (byte)0x20;
939
}
940
return (tag);
941
}
942
943
/**
944
* Set the tag of the attribute. Commonly used to reset the
945
* tag value used for IMPLICIT encodings.
946
*
947
* @params tag the tag value
948
*/
949
public void resetTag(byte tag) {
950
this.tag = tag;
951
}
952
953
/**
954
* Returns a hashcode for this DerValue.
955
*
956
* @return a hashcode for this DerValue.
957
*/
958
@Override
959
public int hashCode() {
960
return toString().hashCode();
961
}
962
}
963
964