Perf. opts and correctness checks when decoding BMPString
@@ -397,25 +397,53 @@ static int readLength(InputStream s, int limit, boolean isParsing)
private static char[] getBMPCharBuffer(DefiniteLengthInputStream defIn)
throws IOException
{
- int len = defIn.getRemaining() / 2;
- char[] buf = new char[len];
- int totalRead = 0;
- while (totalRead < len)
+ int remainingBytes = defIn.getRemaining();
+ if (0 != (remainingBytes & 1))
{
- int ch1 = defIn.read();
- if (ch1 < 0)
+ throw new IOException("malformed BMPString encoding encountered");
+ }
+
+ char[] string = new char[remainingBytes / 2];
+ int stringPos = 0;
+
+ byte[] buf = new byte[8];
+ while (remainingBytes >= 8)
+ {
+ if (Streams.readFully(defIn, buf, 0, 8) != 8)
+ {
+ throw new EOFException("EOF encountered in middle of BMPString");
+ }
+
+ string[stringPos ] = (char)((buf[0] << 8) | (buf[1] & 0xFF));
+ string[stringPos + 1] = (char)((buf[2] << 8) | (buf[3] & 0xFF));
+ string[stringPos + 2] = (char)((buf[4] << 8) | (buf[5] & 0xFF));
+ string[stringPos + 3] = (char)((buf[6] << 8) | (buf[7] & 0xFF));
+ stringPos += 4;
+ remainingBytes -= 8;
+ }
+ if (remainingBytes > 0)
+ {
+ if (Streams.readFully(defIn, buf, 0, remainingBytes) != remainingBytes)
{
- break;
+ throw new EOFException("EOF encountered in middle of BMPString");
}
- int ch2 = defIn.read();
- if (ch2 < 0)
+
+ int bufPos = 0;
+ do
{
- break;
+ int b1 = buf[bufPos++] << 8;
+ int b2 = buf[bufPos++] & 0xFF;
+ string[stringPos++] = (char)(b1 | b2);
}
- buf[totalRead++] = (char)((ch1 << 8) | (ch2 & 0xff));
+ while (bufPos < remainingBytes);
}
- return buf;
+ if (0 != defIn.getRemaining() || string.length != stringPos)
+ {
+ throw new IllegalStateException();
+ }
+
+ return string;
}
static ASN1Primitive createPrimitiveDERObject(
