1 package org.bouncycastle.asn1;
5 public class DERBitString
12 * return the correct number of pad bits for a bit string defined in
15 static protected int getPadBits(
27 val = ((bitString >> 8) & 0xFF);
31 val = (bitString & 0xFF);
36 while (((val <<= 1) & 0xFF) != 0)
45 * return the correct number of bytes for a bit string defined in
48 static protected byte[] getBytes(
53 byte[] bytes = new byte[2];
55 bytes[0] = (byte)(bitString & 0xFF);
56 bytes[1] = (byte)((bitString >> 8) & 0xFF);
62 byte[] bytes = new byte[1];
64 bytes[0] = (byte)(bitString & 0xFF);
71 * return a Bit String from the passed in object
73 * @exception IllegalArgumentException if the object cannot be converted.
75 public static DERBitString getInstance(
78 if (obj == null || obj instanceof DERBitString)
80 return (DERBitString)obj;
83 if (obj instanceof ASN1OctetString)
85 byte[] bytes = ((ASN1OctetString)obj).getOctets();
86 int padBits = bytes[0];
87 byte[] data = new byte[bytes.length - 1];
89 System.arraycopy(bytes, 1, data, 0, bytes.length - 1);
91 return new DERBitString(data, padBits);
94 if (obj instanceof ASN1TaggedObject)
96 return getInstance(((ASN1TaggedObject)obj).getObject());
99 throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
103 * return a Bit String from a tagged object.
105 * @param obj the tagged object holding the object we want
106 * @param explicit true if the object is meant to be explicitly
107 * tagged false otherwise.
108 * @exception IllegalArgumentException if the tagged object cannot
111 public static DERBitString getInstance(
112 ASN1TaggedObject obj,
115 return getInstance(obj.getObject());
118 protected DERBitString(
122 this.data = new byte[1];
124 this.padBits = padBits;
128 * @param data the octets making up the bit string.
129 * @param padBits the number of extra bits at the end of the string.
136 this.padBits = padBits;
150 ByteArrayOutputStream bOut = new ByteArrayOutputStream();
151 DEROutputStream dOut = new DEROutputStream(bOut);
153 dOut.writeObject(obj);
156 this.data = bOut.toByteArray();
159 catch (IOException e)
161 throw new IllegalArgumentException("Error processing object : " + e.toString());
165 public byte[] getBytes()
170 public int getPadBits()
179 byte[] bytes = new byte[getBytes().length + 1];
181 bytes[0] = (byte)getPadBits();
182 System.arraycopy(getBytes(), 0, bytes, 1, bytes.length - 1);
184 out.writeEncoded(BIT_STRING, bytes);
187 public boolean equals(
190 if (o == null || !(o instanceof DERBitString))
195 DERBitString other = (DERBitString)o;
197 if (data.length != other.data.length)
202 for (int i = 0; i != data.length; i++)
204 if (data[i] != other.data[i])
210 return (padBits == other.padBits);