0N/A/*
2362N/A * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/Apackage sun.security.util;
0N/A
0N/Aimport java.io.InputStream;
0N/Aimport java.io.IOException;
0N/Aimport java.io.EOFException;
0N/Aimport java.util.Date;
0N/Aimport java.util.Vector;
0N/Aimport java.math.BigInteger;
0N/Aimport java.io.DataInputStream;
0N/A
0N/A/**
0N/A * A DER input stream, used for parsing ASN.1 DER-encoded data such as
0N/A * that found in X.509 certificates. DER is a subset of BER/1, which has
0N/A * the advantage that it allows only a single encoding of primitive data.
0N/A * (High level data such as dates still support many encodings.) That is,
0N/A * it uses the "Definite" Encoding Rules (DER) not the "Basic" ones (BER).
0N/A *
0N/A * <P>Note that, like BER/1, DER streams are streams of explicitly
0N/A * tagged data values. Accordingly, this programming interface does
0N/A * not expose any variant of the java.io.InputStream interface, since
0N/A * that kind of input stream holds untagged data values and using that
0N/A * I/O model could prevent correct parsing of the DER data.
0N/A *
0N/A * <P>At this time, this class supports only a subset of the types of DER
0N/A * data encodings which are defined. That subset is sufficient for parsing
0N/A * most X.509 certificates.
0N/A *
0N/A *
0N/A * @author David Brownell
0N/A * @author Amit Kapoor
0N/A * @author Hemma Prafullchandra
0N/A */
0N/A
0N/Apublic class DerInputStream {
0N/A
0N/A /*
0N/A * This version only supports fully buffered DER. This is easy to
0N/A * work with, though if large objects are manipulated DER becomes
0N/A * awkward to deal with. That's where BER is useful, since BER
0N/A * handles streaming data relatively well.
0N/A */
0N/A DerInputBuffer buffer;
0N/A
0N/A /** The DER tag of the value; one of the tag_ constants. */
0N/A public byte tag;
0N/A
0N/A /**
0N/A * Create a DER input stream from a data buffer. The buffer is not
0N/A * copied, it is shared. Accordingly, the buffer should be treated
0N/A * as read-only.
0N/A *
0N/A * @param data the buffer from which to create the string (CONSUMED)
0N/A */
0N/A public DerInputStream(byte[] data) throws IOException {
0N/A init(data, 0, data.length);
0N/A }
0N/A
0N/A /**
0N/A * Create a DER input stream from part of a data buffer.
0N/A * The buffer is not copied, it is shared. Accordingly, the
0N/A * buffer should be treated as read-only.
0N/A *
0N/A * @param data the buffer from which to create the string (CONSUMED)
0N/A * @param offset the first index of <em>data</em> which will
0N/A * be read as DER input in the new stream
0N/A * @param len how long a chunk of the buffer to use,
0N/A * starting at "offset"
0N/A */
0N/A public DerInputStream(byte[] data, int offset, int len) throws IOException {
0N/A init(data, offset, len);
0N/A }
0N/A
0N/A /*
0N/A * private helper routine
0N/A */
0N/A private void init(byte[] data, int offset, int len) throws IOException {
0N/A if ((offset+2 > data.length) || (offset+len > data.length)) {
0N/A throw new IOException("Encoding bytes too short");
0N/A }
0N/A // check for indefinite length encoding
0N/A if (DerIndefLenConverter.isIndefinite(data[offset+1])) {
0N/A byte[] inData = new byte[len];
0N/A System.arraycopy(data, offset, inData, 0, len);
0N/A
0N/A DerIndefLenConverter derIn = new DerIndefLenConverter();
0N/A buffer = new DerInputBuffer(derIn.convert(inData));
0N/A } else
0N/A buffer = new DerInputBuffer(data, offset, len);
0N/A buffer.mark(Integer.MAX_VALUE);
0N/A }
0N/A
0N/A DerInputStream(DerInputBuffer buf) {
0N/A buffer = buf;
0N/A buffer.mark(Integer.MAX_VALUE);
0N/A }
0N/A
0N/A /**
0N/A * Creates a new DER input stream from part of this input stream.
0N/A *
0N/A * @param len how long a chunk of the current input stream to use,
0N/A * starting at the current position.
0N/A * @param do_skip true if the existing data in the input stream should
0N/A * be skipped. If this value is false, the next data read
0N/A * on this stream and the newly created stream will be the
0N/A * same.
0N/A */
0N/A public DerInputStream subStream(int len, boolean do_skip)
0N/A throws IOException {
0N/A DerInputBuffer newbuf = buffer.dup();
0N/A
0N/A newbuf.truncate(len);
0N/A if (do_skip) {
0N/A buffer.skip(len);
0N/A }
0N/A return new DerInputStream(newbuf);
0N/A }
0N/A
0N/A /**
0N/A * Return what has been written to this DerInputStream
0N/A * as a byte array. Useful for debugging.
0N/A */
0N/A public byte[] toByteArray() {
0N/A return buffer.toByteArray();
0N/A }
0N/A
0N/A /*
0N/A * PRIMITIVES -- these are "universal" ASN.1 simple types.
0N/A *
0N/A * INTEGER, ENUMERATED, BIT STRING, OCTET STRING, NULL
0N/A * OBJECT IDENTIFIER, SEQUENCE (OF), SET (OF)
0N/A * UTF8String, PrintableString, T61String, IA5String, UTCTime,
0N/A * GeneralizedTime, BMPString.
0N/A * Note: UniversalString not supported till encoder is available.
0N/A */
0N/A
0N/A /**
0N/A * Get an integer from the input stream as an integer.
0N/A *
0N/A * @return the integer held in this DER input stream.
0N/A */
0N/A public int getInteger() throws IOException {
0N/A if (buffer.read() != DerValue.tag_Integer) {
0N/A throw new IOException("DER input, Integer tag error");
0N/A }
0N/A return buffer.getInteger(getLength(buffer));
0N/A }
0N/A
0N/A /**
0N/A * Get a integer from the input stream as a BigInteger object.
0N/A *
0N/A * @return the integer held in this DER input stream.
0N/A */
0N/A public BigInteger getBigInteger() throws IOException {
0N/A if (buffer.read() != DerValue.tag_Integer) {
0N/A throw new IOException("DER input, Integer tag error");
0N/A }
0N/A return buffer.getBigInteger(getLength(buffer), false);
0N/A }
0N/A
0N/A /**
0N/A * Returns an ASN.1 INTEGER value as a positive BigInteger.
0N/A * This is just to deal with implementations that incorrectly encode
0N/A * some values as negative.
0N/A *
0N/A * @return the integer held in this DER value as a BigInteger.
0N/A */
0N/A public BigInteger getPositiveBigInteger() throws IOException {
0N/A if (buffer.read() != DerValue.tag_Integer) {
0N/A throw new IOException("DER input, Integer tag error");
0N/A }
0N/A return buffer.getBigInteger(getLength(buffer), true);
0N/A }
0N/A
0N/A /**
0N/A * Get an enumerated from the input stream.
0N/A *
0N/A * @return the integer held in this DER input stream.
0N/A */
0N/A public int getEnumerated() throws IOException {
0N/A if (buffer.read() != DerValue.tag_Enumerated) {
0N/A throw new IOException("DER input, Enumerated tag error");
0N/A }
0N/A return buffer.getInteger(getLength(buffer));
0N/A }
0N/A
0N/A /**
0N/A * Get a bit string from the input stream. Padded bits (if any)
0N/A * will be stripped off before the bit string is returned.
0N/A */
0N/A public byte[] getBitString() throws IOException {
0N/A if (buffer.read() != DerValue.tag_BitString)
0N/A throw new IOException("DER input not an bit string");
0N/A
0N/A return buffer.getBitString(getLength(buffer));
0N/A }
0N/A
0N/A /**
0N/A * Get a bit string from the input stream. The bit string need
0N/A * not be byte-aligned.
0N/A */
0N/A public BitArray getUnalignedBitString() throws IOException {
0N/A if (buffer.read() != DerValue.tag_BitString)
0N/A throw new IOException("DER input not a bit string");
0N/A
0N/A int length = getLength(buffer) - 1;
0N/A
0N/A /*
0N/A * First byte = number of excess bits in the last octet of the
0N/A * representation.
0N/A */
0N/A int validBits = length*8 - buffer.read();
0N/A
0N/A byte[] repn = new byte[length];
0N/A
0N/A if ((length != 0) && (buffer.read(repn) != length))
0N/A throw new IOException("short read of DER bit string");
0N/A return new BitArray(validBits, repn);
0N/A }
0N/A
0N/A /**
0N/A * Returns an ASN.1 OCTET STRING from the input stream.
0N/A */
0N/A public byte[] getOctetString() throws IOException {
0N/A if (buffer.read() != DerValue.tag_OctetString)
0N/A throw new IOException("DER input not an octet string");
0N/A
0N/A int length = getLength(buffer);
0N/A byte[] retval = new byte[length];
0N/A if ((length != 0) && (buffer.read(retval) != length))
0N/A throw new IOException("short read of DER octet string");
0N/A
0N/A return retval;
0N/A }
0N/A
0N/A /**
0N/A * Returns the asked number of bytes from the input stream.
0N/A */
0N/A public void getBytes(byte[] val) throws IOException {
0N/A if ((val.length != 0) && (buffer.read(val) != val.length)) {
0N/A throw new IOException("short read of DER octet string");
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Reads an encoded null value from the input stream.
0N/A */
0N/A public void getNull() throws IOException {
0N/A if (buffer.read() != DerValue.tag_Null || buffer.read() != 0)
0N/A throw new IOException("getNull, bad data");
0N/A }
0N/A
0N/A /**
0N/A * Reads an X.200 style Object Identifier from the stream.
0N/A */
0N/A public ObjectIdentifier getOID() throws IOException {
0N/A return new ObjectIdentifier(this);
0N/A }
0N/A
0N/A /**
0N/A * Return a sequence of encoded entities. ASN.1 sequences are
0N/A * ordered, and they are often used, like a "struct" in C or C++,
0N/A * to group data values. They may have optional or context
0N/A * specific values.
0N/A *
0N/A * @param startLen guess about how long the sequence will be
0N/A * (used to initialize an auto-growing data structure)
0N/A * @return array of the values in the sequence
0N/A */
0N/A public DerValue[] getSequence(int startLen) throws IOException {
0N/A tag = (byte)buffer.read();
0N/A if (tag != DerValue.tag_Sequence)
0N/A throw new IOException("Sequence tag error");
0N/A return readVector(startLen);
0N/A }
0N/A
0N/A /**
0N/A * Return a set of encoded entities. ASN.1 sets are unordered,
0N/A * though DER may specify an order for some kinds of sets (such
0N/A * as the attributes in an X.500 relative distinguished name)
0N/A * to facilitate binary comparisons of encoded values.
0N/A *
0N/A * @param startLen guess about how large the set will be
0N/A * (used to initialize an auto-growing data structure)
0N/A * @return array of the values in the sequence
0N/A */
0N/A public DerValue[] getSet(int startLen) throws IOException {
0N/A tag = (byte)buffer.read();
0N/A if (tag != DerValue.tag_Set)
0N/A throw new IOException("Set tag error");
0N/A return readVector(startLen);
0N/A }
0N/A
0N/A /**
0N/A * Return a set of encoded entities. ASN.1 sets are unordered,
0N/A * though DER may specify an order for some kinds of sets (such
0N/A * as the attributes in an X.500 relative distinguished name)
0N/A * to facilitate binary comparisons of encoded values.
0N/A *
0N/A * @param startLen guess about how large the set will be
0N/A * (used to initialize an auto-growing data structure)
0N/A * @param implicit if true tag is assumed implicit.
0N/A * @return array of the values in the sequence
0N/A */
0N/A public DerValue[] getSet(int startLen, boolean implicit)
0N/A throws IOException {
0N/A tag = (byte)buffer.read();
0N/A if (!implicit) {
0N/A if (tag != DerValue.tag_Set) {
0N/A throw new IOException("Set tag error");
0N/A }
0N/A }
0N/A return (readVector(startLen));
0N/A }
0N/A
0N/A /*
0N/A * Read a "vector" of values ... set or sequence have the
0N/A * same encoding, except for the initial tag, so both use
0N/A * this same helper routine.
0N/A */
0N/A protected DerValue[] readVector(int startLen) throws IOException {
0N/A DerInputStream newstr;
0N/A
0N/A byte lenByte = (byte)buffer.read();
0N/A int len = getLength((lenByte & 0xff), buffer);
0N/A
0N/A if (len == -1) {
0N/A // indefinite length encoding found
0N/A int readLen = buffer.available();
0N/A int offset = 2; // for tag and length bytes
0N/A byte[] indefData = new byte[readLen + offset];
0N/A indefData[0] = tag;
0N/A indefData[1] = lenByte;
0N/A DataInputStream dis = new DataInputStream(buffer);
0N/A dis.readFully(indefData, offset, readLen);
0N/A dis.close();
0N/A DerIndefLenConverter derIn = new DerIndefLenConverter();
0N/A buffer = new DerInputBuffer(derIn.convert(indefData));
0N/A if (tag != buffer.read())
0N/A throw new IOException("Indefinite length encoding" +
0N/A " not supported");
0N/A len = DerInputStream.getLength(buffer);
0N/A }
0N/A
0N/A if (len == 0)
0N/A // return empty array instead of null, which should be
0N/A // used only for missing optionals
0N/A return new DerValue[0];
0N/A
0N/A /*
0N/A * Create a temporary stream from which to read the data,
0N/A * unless it's not really needed.
0N/A */
0N/A if (buffer.available() == len)
0N/A newstr = this;
0N/A else
0N/A newstr = subStream(len, true);
0N/A
0N/A /*
0N/A * Pull values out of the stream.
0N/A */
0N/A Vector<DerValue> vec = new Vector<DerValue>(startLen);
0N/A DerValue value;
0N/A
0N/A do {
0N/A value = new DerValue(newstr.buffer);
0N/A vec.addElement(value);
0N/A } while (newstr.available() > 0);
0N/A
0N/A if (newstr.available() != 0)
0N/A throw new IOException("extra data at end of vector");
0N/A
0N/A /*
0N/A * Now stick them into the array we're returning.
0N/A */
0N/A int i, max = vec.size();
0N/A DerValue[] retval = new DerValue[max];
0N/A
0N/A for (i = 0; i < max; i++)
0N/A retval[i] = vec.elementAt(i);
0N/A
0N/A return retval;
0N/A }
0N/A
0N/A /**
0N/A * Get a single DER-encoded value from the input stream.
0N/A * It can often be useful to pull a value from the stream
0N/A * and defer parsing it. For example, you can pull a nested
0N/A * sequence out with one call, and only examine its elements
0N/A * later when you really need to.
0N/A */
0N/A public DerValue getDerValue() throws IOException {
0N/A return new DerValue(buffer);
0N/A }
0N/A
0N/A /**
0N/A * Read a string that was encoded as a UTF8String DER value.
0N/A */
0N/A public String getUTF8String() throws IOException {
0N/A return readString(DerValue.tag_UTF8String, "UTF-8", "UTF8");
0N/A }
0N/A
0N/A /**
0N/A * Read a string that was encoded as a PrintableString DER value.
0N/A */
0N/A public String getPrintableString() throws IOException {
0N/A return readString(DerValue.tag_PrintableString, "Printable",
0N/A "ASCII");
0N/A }
0N/A
0N/A /**
0N/A * Read a string that was encoded as a T61String DER value.
0N/A */
0N/A public String getT61String() throws IOException {
0N/A /*
0N/A * Works for common characters between T61 and ASCII.
0N/A */
0N/A return readString(DerValue.tag_T61String, "T61", "ISO-8859-1");
0N/A }
0N/A
0N/A /**
0N/A * Read a string that was encoded as a IA5tring DER value.
0N/A */
0N/A public String getIA5String() throws IOException {
0N/A return readString(DerValue.tag_IA5String, "IA5", "ASCII");
0N/A }
0N/A
0N/A /**
0N/A * Read a string that was encoded as a BMPString DER value.
0N/A */
0N/A public String getBMPString() throws IOException {
0N/A return readString(DerValue.tag_BMPString, "BMP",
0N/A "UnicodeBigUnmarked");
0N/A }
0N/A
0N/A /**
0N/A * Read a string that was encoded as a GeneralString DER value.
0N/A */
0N/A public String getGeneralString() throws IOException {
0N/A return readString(DerValue.tag_GeneralString, "General",
0N/A "ASCII");
0N/A }
0N/A
0N/A /**
0N/A * Private helper routine to read an encoded string from the input
0N/A * stream.
0N/A * @param stringTag the tag for the type of string to read
0N/A * @param stringName a name to display in error messages
0N/A * @param enc the encoder to use to interpret the data. Should
0N/A * correspond to the stringTag above.
0N/A */
0N/A private String readString(byte stringTag, String stringName,
0N/A String enc) throws IOException {
0N/A
0N/A if (buffer.read() != stringTag)
0N/A throw new IOException("DER input not a " +
0N/A stringName + " string");
0N/A
0N/A int length = getLength(buffer);
0N/A byte[] retval = new byte[length];
0N/A if ((length != 0) && (buffer.read(retval) != length))
0N/A throw new IOException("short read of DER " +
0N/A stringName + " string");
0N/A
0N/A return new String(retval, enc);
0N/A }
0N/A
0N/A /**
0N/A * Get a UTC encoded time value from the input stream.
0N/A */
0N/A public Date getUTCTime() throws IOException {
0N/A if (buffer.read() != DerValue.tag_UtcTime)
0N/A throw new IOException("DER input, UTCtime tag invalid ");
0N/A return buffer.getUTCTime(getLength(buffer));
0N/A }
0N/A
0N/A /**
0N/A * Get a Generalized encoded time value from the input stream.
0N/A */
0N/A public Date getGeneralizedTime() throws IOException {
0N/A if (buffer.read() != DerValue.tag_GeneralizedTime)
0N/A throw new IOException("DER input, GeneralizedTime tag invalid ");
0N/A return buffer.getGeneralizedTime(getLength(buffer));
0N/A }
0N/A
0N/A /*
0N/A * Get a byte from the input stream.
0N/A */
0N/A // package private
0N/A int getByte() throws IOException {
0N/A return (0x00ff & buffer.read());
0N/A }
0N/A
0N/A public int peekByte() throws IOException {
0N/A return buffer.peek();
0N/A }
0N/A
0N/A // package private
0N/A int getLength() throws IOException {
0N/A return getLength(buffer);
0N/A }
0N/A
0N/A /*
0N/A * Get a length from the input stream, allowing for at most 32 bits of
0N/A * encoding to be used. (Not the same as getting a tagged integer!)
0N/A *
0N/A * @return the length or -1 if indefinite length found.
0N/A * @exception IOException on parsing error or unsupported lengths.
0N/A */
0N/A static int getLength(InputStream in) throws IOException {
0N/A return getLength(in.read(), in);
0N/A }
0N/A
0N/A /*
0N/A * Get a length from the input stream, allowing for at most 32 bits of
0N/A * encoding to be used. (Not the same as getting a tagged integer!)
0N/A *
0N/A * @return the length or -1 if indefinite length found.
0N/A * @exception IOException on parsing error or unsupported lengths.
0N/A */
0N/A static int getLength(int lenByte, InputStream in) throws IOException {
0N/A int value, tmp;
0N/A
0N/A tmp = lenByte;
0N/A if ((tmp & 0x080) == 0x00) { // short form, 1 byte datum
0N/A value = tmp;
0N/A } else { // long form or indefinite
0N/A tmp &= 0x07f;
0N/A
0N/A /*
0N/A * NOTE: tmp == 0 indicates indefinite length encoded data.
0N/A * tmp > 4 indicates more than 4Gb of data.
0N/A */
0N/A if (tmp == 0)
0N/A return -1;
0N/A if (tmp < 0 || tmp > 4)
0N/A throw new IOException("DerInputStream.getLength(): lengthTag="
0N/A + tmp + ", "
0N/A + ((tmp < 0) ? "incorrect DER encoding." : "too big."));
0N/A
0N/A for (value = 0; tmp > 0; tmp --) {
0N/A value <<= 8;
0N/A value += 0x0ff & in.read();
0N/A }
0N/A }
0N/A return value;
0N/A }
0N/A
0N/A /**
0N/A * Mark the current position in the buffer, so that
0N/A * a later call to <code>reset</code> will return here.
0N/A */
0N/A public void mark(int value) { buffer.mark(value); }
0N/A
0N/A
0N/A /**
0N/A * Return to the position of the last <code>mark</code>
0N/A * call. A mark is implicitly set at the beginning of
0N/A * the stream when it is created.
0N/A */
0N/A public void reset() { buffer.reset(); }
0N/A
0N/A
0N/A /**
0N/A * Returns the number of bytes available for reading.
0N/A * This is most useful for testing whether the stream is
0N/A * empty.
0N/A */
0N/A public int available() { return buffer.available(); }
0N/A}