THRIFT-5190: StringUtils haven't take `(offset + length) > bytes.length` into account
Client: java
Patch: dugenkui <dugenkui@meituan.com>

This closes #2125
diff --git a/lib/java/src/org/apache/thrift/utils/StringUtils.java b/lib/java/src/org/apache/thrift/utils/StringUtils.java
index 15183a3..9b9671b 100644
--- a/lib/java/src/org/apache/thrift/utils/StringUtils.java
+++ b/lib/java/src/org/apache/thrift/utils/StringUtils.java
@@ -55,6 +55,9 @@
     if (offset < 0) {
       throw new IndexOutOfBoundsException("Negative start offset " + offset);
     }
+    if (length > bytes.length - offset) {
+      throw new IndexOutOfBoundsException("Invalid range, bytes.length: " + bytes.length + " offset: " + offset + " length: " + length);
+    }
     char[] chars = new char[length * 2];
     for (int i = 0; i < length; i++) {
       int unsignedInt = bytes[i + offset] & 0xFF;
diff --git a/lib/java/test/org/apache/thrift/utils/TestStringUtils.java b/lib/java/test/org/apache/thrift/utils/TestStringUtils.java
index 3a8cf39..3224e77 100644
--- a/lib/java/test/org/apache/thrift/utils/TestStringUtils.java
+++ b/lib/java/test/org/apache/thrift/utils/TestStringUtils.java
@@ -20,6 +20,7 @@
 package org.apache.thrift.utils;
 
 import org.junit.Assert;
+import org.junit.Before;
 import org.junit.Test;
 
 public class TestStringUtils {
@@ -31,4 +32,28 @@
     Assert.assertEquals("EFAB92", StringUtils.bytesToHexString(bytes, 2, 3));
     Assert.assertNull(StringUtils.bytesToHexString(null));
   }
+
+
+  private byte[] bytes;
+
+  @Before
+  public void setUp() throws Exception {
+    bytes = new byte[]{1, 2, 3, 4, 5};
+  }
+
+  @Test(expected = IllegalArgumentException.class)
+  public void testNegativeLength() {
+    StringUtils.bytesToHexString(bytes, 0, -1);
+  }
+
+  @Test(expected = IndexOutOfBoundsException.class)
+  public void testNegativeStartOffset() {
+    StringUtils.bytesToHexString(bytes, -1, 1);
+  }
+
+  @Test(expected = IndexOutOfBoundsException.class)
+  public void testInvalidRange() {
+    StringUtils.bytesToHexString(bytes, 5, 1);
+  }
+
 }