001: /*
002: * @(#)DerInputStream.java 1.54 06/10/10
003: *
004: * Copyright 1990-2006 Sun Microsystems, Inc. All Rights Reserved.
005: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
006: *
007: * This program is free software; you can redistribute it and/or
008: * modify it under the terms of the GNU General Public License version
009: * 2 only, as published by the Free Software Foundation.
010: *
011: * This program is distributed in the hope that it will be useful, but
012: * WITHOUT ANY WARRANTY; without even the implied warranty of
013: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
014: * General Public License version 2 for more details (a copy is
015: * included at /legal/license.txt).
016: *
017: * You should have received a copy of the GNU General Public License
018: * version 2 along with this work; if not, write to the Free Software
019: * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
020: * 02110-1301 USA
021: *
022: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
023: * Clara, CA 95054 or visit www.sun.com if you need additional
024: * information or have any questions.
025: *
026: */
027:
028: package sun.security.util;
029:
030: import java.io.InputStream;
031: import java.io.IOException;
032: import java.io.EOFException;
033: import java.util.Date;
034: import java.util.Vector;
035: import java.math.BigInteger;
036: import java.io.DataInputStream;
037:
038: /**
039: * A DER input stream, used for parsing ASN.1 DER-encoded data such as
040: * that found in X.509 certificates. DER is a subset of BER/1, which has
041: * the advantage that it allows only a single encoding of primitive data.
042: * (High level data such as dates still support many encodings.) That is,
043: * it uses the "Definite" Encoding Rules (DER) not the "Basic" ones (BER).
044: *
045: * <P>Note that, like BER/1, DER streams are streams of explicitly
046: * tagged data values. Accordingly, this programming interface does
047: * not expose any variant of the java.io.InputStream interface, since
048: * that kind of input stream holds untagged data values and using that
049: * I/O model could prevent correct parsing of the DER data.
050: *
051: * <P>At this time, this class supports only a subset of the types of DER
052: * data encodings which are defined. That subset is sufficient for parsing
053: * most X.509 certificates.
054: *
055: * @version 1.47
056: *
057: * @author David Brownell
058: * @author Amit Kapoor
059: * @author Hemma Prafullchandra
060: */
061:
062: public class DerInputStream {
063:
064: /*
065: * This version only supports fully buffered DER. This is easy to
066: * work with, though if large objects are manipulated DER becomes
067: * awkward to deal with. That's where BER is useful, since BER
068: * handles streaming data relatively well.
069: */
070: DerInputBuffer buffer;
071:
072: /** The DER tag of the value; one of the tag_ constants. */
073: public byte tag;
074:
075: /**
076: * Create a DER input stream from a data buffer. The buffer is not
077: * copied, it is shared. Accordingly, the buffer should be treated
078: * as read-only.
079: *
080: * @param data the buffer from which to create the string (CONSUMED)
081: */
082: public DerInputStream(byte[] data) throws IOException {
083: init(data, 0, data.length);
084: }
085:
086: /**
087: * Create a DER input stream from part of a data buffer.
088: * The buffer is not copied, it is shared. Accordingly, the
089: * buffer should be treated as read-only.
090: *
091: * @param data the buffer from which to create the string (CONSUMED)
092: * @param offset the first index of <em>data</em> which will
093: * be read as DER input in the new stream
094: * @param len how long a chunk of the buffer to use,
095: * starting at "offset"
096: */
097: public DerInputStream(byte[] data, int offset, int len)
098: throws IOException {
099: init(data, offset, len);
100: }
101:
102: /*
103: * private helper routine
104: */
105: private void init(byte[] data, int offset, int len)
106: throws IOException {
107: if ((offset + 2 > data.length) || (offset + len > data.length)) {
108: throw new IOException("Encoding bytes too short");
109: }
110: // check for indefinite length encoding
111: if (DerIndefLenConverter.isIndefinite(data[offset + 1])) {
112: byte[] inData = new byte[len];
113: System.arraycopy(data, offset, inData, 0, len);
114:
115: DerIndefLenConverter derIn = new DerIndefLenConverter();
116: buffer = new DerInputBuffer(derIn.convert(inData));
117: } else
118: buffer = new DerInputBuffer(data, offset, len);
119: buffer.mark(Integer.MAX_VALUE);
120: }
121:
122: DerInputStream(DerInputBuffer buf) {
123: buffer = buf;
124: buffer.mark(Integer.MAX_VALUE);
125: }
126:
127: /**
128: * Creates a new DER input stream from part of this input stream.
129: *
130: * @param len how long a chunk of the current input stream to use,
131: * starting at the current position.
132: * @param do_skip true if the existing data in the input stream should
133: * be skipped. If this value is false, the next data read
134: * on this stream and the newly created stream will be the
135: * same.
136: */
137: public DerInputStream subStream(int len, boolean do_skip)
138: throws IOException {
139: DerInputBuffer newbuf = buffer.dup();
140:
141: newbuf.truncate(len);
142: if (do_skip) {
143: buffer.skip(len);
144: }
145: return new DerInputStream(newbuf);
146: }
147:
148: /**
149: * Return what has been written to this DerInputStream
150: * as a byte array. Useful for debugging.
151: */
152: public byte[] toByteArray() {
153: return buffer.toByteArray();
154: }
155:
156: /*
157: * PRIMITIVES -- these are "universal" ASN.1 simple types.
158: *
159: * INTEGER, ENUMERATED, BIT STRING, OCTET STRING, NULL
160: * OBJECT IDENTIFIER, SEQUENCE (OF), SET (OF)
161: * UTF8String, PrintableString, T61String, IA5String, UTCTime,
162: * GeneralizedTime, BMPString.
163: * Note: UniversalString not supported till encoder is available.
164: */
165:
166: /**
167: * Get an integer from the input stream as an integer.
168: *
169: * @return the integer held in this DER input stream.
170: */
171: public int getInteger() throws IOException {
172: if (buffer.read() != DerValue.tag_Integer) {
173: throw new IOException("DER input, Integer tag error");
174: }
175: return buffer.getInteger(getLength(buffer));
176: }
177:
178: /**
179: * Get a integer from the input stream as a BigInteger object.
180: *
181: * @return the integer held in this DER input stream.
182: */
183: public BigInteger getBigInteger() throws IOException {
184: if (buffer.read() != DerValue.tag_Integer) {
185: throw new IOException("DER input, Integer tag error");
186: }
187: return buffer.getBigInteger(getLength(buffer));
188: }
189:
190: /**
191: * Get an enumerated from the input stream.
192: *
193: * @return the integer held in this DER input stream.
194: */
195: public int getEnumerated() throws IOException {
196: if (buffer.read() != DerValue.tag_Enumerated) {
197: throw new IOException("DER input, Enumerated tag error");
198: }
199: return buffer.getInteger(getLength(buffer));
200: }
201:
202: /**
203: * Get a bit string from the input stream. Padded bits (if any)
204: * will be stripped off before the bit string is returned.
205: */
206: public byte[] getBitString() throws IOException {
207: if (buffer.read() != DerValue.tag_BitString)
208: throw new IOException("DER input not an bit string");
209:
210: return buffer.getBitString(getLength(buffer));
211: }
212:
213: /**
214: * Get a bit string from the input stream. The bit string need
215: * not be byte-aligned.
216: */
217: public BitArray getUnalignedBitString() throws IOException {
218: if (buffer.read() != DerValue.tag_BitString)
219: throw new IOException("DER input not a bit string");
220:
221: int length = getLength(buffer) - 1;
222:
223: /*
224: * First byte = number of excess bits in the last octet of the
225: * representation.
226: */
227: int validBits = length * 8 - buffer.read();
228:
229: byte[] repn = new byte[length];
230:
231: if ((length != 0) && (buffer.read(repn) != length))
232: throw new IOException("short read of DER bit string");
233: return new BitArray(validBits, repn);
234: }
235:
236: /**
237: * Returns an ASN.1 OCTET STRING from the input stream.
238: */
239: public byte[] getOctetString() throws IOException {
240: if (buffer.read() != DerValue.tag_OctetString)
241: throw new IOException("DER input not an octet string");
242:
243: int length = getLength(buffer);
244: byte[] retval = new byte[length];
245: if ((length != 0) && (buffer.read(retval) != length))
246: throw new IOException("short read of DER octet string");
247:
248: return retval;
249: }
250:
251: /**
252: * Returns the asked number of bytes from the input stream.
253: */
254: public void getBytes(byte[] val) throws IOException {
255: if ((val.length != 0) && (buffer.read(val) != val.length)) {
256: throw new IOException("short read of DER octet string");
257: }
258: }
259:
260: /**
261: * Reads an encoded null value from the input stream.
262: */
263: public void getNull() throws IOException {
264: if (buffer.read() != DerValue.tag_Null || buffer.read() != 0)
265: throw new IOException("getNull, bad data");
266: }
267:
268: /**
269: * Reads an X.200 style Object Identifier from the stream.
270: */
271: public ObjectIdentifier getOID() throws IOException {
272: return new ObjectIdentifier(this );
273: }
274:
275: /**
276: * Return a sequence of encoded entities. ASN.1 sequences are
277: * ordered, and they are often used, like a "struct" in C or C++,
278: * to group data values. They may have optional or context
279: * specific values.
280: *
281: * @param startLen guess about how long the sequence will be
282: * (used to initialize an auto-growing data structure)
283: * @return array of the values in the sequence
284: */
285: public DerValue[] getSequence(int startLen) throws IOException {
286: tag = (byte) buffer.read();
287: if (tag != DerValue.tag_Sequence)
288: throw new IOException("Sequence tag error");
289: return readVector(startLen);
290: }
291:
292: /**
293: * Return a set of encoded entities. ASN.1 sets are unordered,
294: * though DER may specify an order for some kinds of sets (such
295: * as the attributes in an X.500 relative distinguished name)
296: * to facilitate binary comparisons of encoded values.
297: *
298: * @param startLen guess about how large the set will be
299: * (used to initialize an auto-growing data structure)
300: * @return array of the values in the sequence
301: */
302: public DerValue[] getSet(int startLen) throws IOException {
303: tag = (byte) buffer.read();
304: if (tag != DerValue.tag_Set)
305: throw new IOException("Set tag error");
306: return readVector(startLen);
307: }
308:
309: /**
310: * Return a set of encoded entities. ASN.1 sets are unordered,
311: * though DER may specify an order for some kinds of sets (such
312: * as the attributes in an X.500 relative distinguished name)
313: * to facilitate binary comparisons of encoded values.
314: *
315: * @param startLen guess about how large the set will be
316: * (used to initialize an auto-growing data structure)
317: * @param implicit if true tag is assumed implicit.
318: * @return array of the values in the sequence
319: */
320: public DerValue[] getSet(int startLen, boolean implicit)
321: throws IOException {
322: tag = (byte) buffer.read();
323: if (!implicit) {
324: if (tag != DerValue.tag_Set) {
325: throw new IOException("Set tag error");
326: }
327: }
328: return (readVector(startLen));
329: }
330:
331: /*
332: * Read a "vector" of values ... set or sequence have the
333: * same encoding, except for the initial tag, so both use
334: * this same helper routine.
335: */
336: protected DerValue[] readVector(int startLen) throws IOException {
337: DerInputStream newstr;
338:
339: byte lenByte = (byte) buffer.read();
340: int len = getLength((lenByte & 0xff), buffer);
341:
342: if (len == -1) {
343: // indefinite length encoding found
344: int readLen = buffer.available();
345: int offset = 2; // for tag and length bytes
346: byte[] indefData = new byte[readLen + offset];
347: indefData[0] = tag;
348: indefData[1] = lenByte;
349: DataInputStream dis = new DataInputStream(buffer);
350: dis.readFully(indefData, offset, readLen);
351: dis.close();
352: DerIndefLenConverter derIn = new DerIndefLenConverter();
353: buffer = new DerInputBuffer(derIn.convert(indefData));
354: if (tag != buffer.read())
355: throw new IOException("Indefinite length encoding"
356: + " not supported");
357: len = DerInputStream.getLength(buffer);
358: }
359:
360: if (len == 0)
361: // return empty array instead of null, which should be
362: // used only for missing optionals
363: return new DerValue[0];
364:
365: /*
366: * Create a temporary stream from which to read the data,
367: * unless it's not really needed.
368: */
369: if (buffer.available() == len)
370: newstr = this ;
371: else
372: newstr = subStream(len, true);
373:
374: /*
375: * Pull values out of the stream.
376: */
377: Vector vec = new Vector(startLen);
378: DerValue value;
379:
380: do {
381: value = new DerValue(newstr.buffer);
382: vec.addElement(value);
383: } while (newstr.available() > 0);
384:
385: if (newstr.available() != 0)
386: throw new IOException("extra data at end of vector");
387:
388: /*
389: * Now stick them into the array we're returning.
390: */
391: int i, max = vec.size();
392: DerValue[] retval = new DerValue[max];
393:
394: for (i = 0; i < max; i++)
395: retval[i] = (DerValue) vec.elementAt(i);
396:
397: return retval;
398: }
399:
400: /**
401: * Get a single DER-encoded value from the input stream.
402: * It can often be useful to pull a value from the stream
403: * and defer parsing it. For example, you can pull a nested
404: * sequence out with one call, and only examine its elements
405: * later when you really need to.
406: */
407: public DerValue getDerValue() throws IOException {
408: return new DerValue(buffer);
409: }
410:
411: /**
412: * Read a string that was encoded as a UTF8String DER value.
413: */
414: public String getUTF8String() throws IOException {
415: return readString(DerValue.tag_UTF8String, "UTF-8", "UTF8");
416: }
417:
418: /**
419: * Read a string that was encoded as a PrintableString DER value.
420: */
421: public String getPrintableString() throws IOException {
422: return readString(DerValue.tag_PrintableString, "Printable",
423: "ASCII");
424: }
425:
426: /**
427: * Read a string that was encoded as a T61String DER value.
428: */
429: public String getT61String() throws IOException {
430: /*
431: * Works for common characters between T61 and ASCII.
432: */
433: return readString(DerValue.tag_T61String, "T61", "ISO-8859-1");
434: }
435:
436: /**
437: * Read a string that was encoded as a IA5tring DER value.
438: */
439: public String getIA5String() throws IOException {
440: return readString(DerValue.tag_IA5String, "IA5", "ASCII");
441: }
442:
443: /**
444: * Read a string that was encoded as a BMPString DER value.
445: */
446: public String getBMPString() throws IOException {
447: return readString(DerValue.tag_BMPString, "BMP",
448: "UnicodeBigUnmarked");
449: }
450:
451: /**
452: * Read a string that was encoded as a GeneralString DER value.
453: */
454: public String getGeneralString() throws IOException {
455: return readString(DerValue.tag_GeneralString, "General",
456: "ASCII");
457: }
458:
459: /**
460: * Private helper routine to read an encoded string from the input
461: * stream.
462: * @param stringTag the tag for the type of string to read
463: * @param stringName a name to display in error messages
464: * @param enc the encoder to use to interpret the data. Should
465: * correspond to the stringTag above.
466: */
467: private String readString(byte stringTag, String stringName,
468: String enc) throws IOException {
469:
470: if (buffer.read() != stringTag)
471: throw new IOException("DER input not a " + stringName
472: + " string");
473:
474: int length = getLength(buffer);
475: byte[] retval = new byte[length];
476: if ((length != 0) && (buffer.read(retval) != length))
477: throw new IOException("short read of DER " + stringName
478: + " string");
479:
480: return new String(retval, enc);
481: }
482:
483: /**
484: * Get a UTC encoded time value from the input stream.
485: */
486: public Date getUTCTime() throws IOException {
487: if (buffer.read() != DerValue.tag_UtcTime)
488: throw new IOException("DER input, UTCtime tag invalid ");
489: return buffer.getUTCTime(getLength(buffer));
490: }
491:
492: /**
493: * Get a Generalized encoded time value from the input stream.
494: */
495: public Date getGeneralizedTime() throws IOException {
496: if (buffer.read() != DerValue.tag_GeneralizedTime)
497: throw new IOException(
498: "DER input, GeneralizedTime tag invalid ");
499: return buffer.getGeneralizedTime(getLength(buffer));
500: }
501:
502: /*
503: * Get a byte from the input stream.
504: */
505: // package private
506: int getByte() throws IOException {
507: return (0x00ff & buffer.read());
508: }
509:
510: public int peekByte() throws IOException {
511: return buffer.peek();
512: }
513:
514: // package private
515: int getLength() throws IOException {
516: return getLength(buffer);
517: }
518:
519: /*
520: * Get a length from the input stream, allowing for at most 32 bits of
521: * encoding to be used. (Not the same as getting a tagged integer!)
522: *
523: * @return the length or -1 if indefinite length found.
524: * @exception IOException on parsing error or unsupported lengths.
525: */
526: static int getLength(InputStream in) throws IOException {
527: return getLength(in.read(), in);
528: }
529:
530: /*
531: * Get a length from the input stream, allowing for at most 32 bits of
532: * encoding to be used. (Not the same as getting a tagged integer!)
533: *
534: * @return the length or -1 if indefinite length found.
535: * @exception IOException on parsing error or unsupported lengths.
536: */
537: static int getLength(int lenByte, InputStream in)
538: throws IOException {
539: int value, tmp;
540:
541: tmp = lenByte;
542: if ((tmp & 0x080) == 0x00) { // short form, 1 byte datum
543: value = tmp;
544: } else { // long form or indefinite
545: tmp &= 0x07f;
546:
547: /*
548: * NOTE: tmp == 0 indicates indefinite length encoded data.
549: * tmp > 4 indicates more than 4Gb of data.
550: */
551: if (tmp == 0)
552: return -1;
553: if (tmp < 0 || tmp > 4)
554: throw new IOException(
555: "DerInputStream.getLength(): lengthTag="
556: + tmp
557: + ", "
558: + ((tmp < 0) ? "incorrect DER encoding."
559: : "too big."));
560:
561: for (value = 0; tmp > 0; tmp--) {
562: value <<= 8;
563: value += 0x0ff & in.read();
564: }
565: }
566: return value;
567: }
568:
569: /**
570: * Mark the current position in the buffer, so that
571: * a later call to <code>reset</code> will return here.
572: */
573: public void mark(int value) {
574: buffer.mark(value);
575: }
576:
577: /**
578: * Return to the position of the last <code>mark</code>
579: * call. A mark is implicitly set at the beginning of
580: * the stream when it is created.
581: */
582: public void reset() {
583: buffer.reset();
584: }
585:
586: /**
587: * Returns the number of bytes available for reading.
588: * This is most useful for testing whether the stream is
589: * empty.
590: */
591: public int available() {
592: return buffer.available();
593: }
594: }
|