From f7d5b4fb8fb0cbc2192a0f76fb4a1ef79a35d811 Mon Sep 17 00:00:00 2001 From: Craig Raw Date: Sat, 8 Feb 2025 09:29:33 +0200 Subject: [PATCH] trim whitespace chars before testing if byte array contains only hex or base64 chars --- .../java/com/sparrowwallet/drongo/Utils.java | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/sparrowwallet/drongo/Utils.java b/src/main/java/com/sparrowwallet/drongo/Utils.java index 7db75b7..2284f4c 100644 --- a/src/main/java/com/sparrowwallet/drongo/Utils.java +++ b/src/main/java/com/sparrowwallet/drongo/Utils.java @@ -57,7 +57,7 @@ public class Utils { return false; } - for(byte b : bytes) { + for(byte b : trim(bytes)) { if(!((b >= '0' && b <= '9') || (b >= 'A' && b <= 'F') || (b >= 'a' && b <= 'f'))) { return false; } @@ -71,7 +71,7 @@ public class Utils { return false; } - for(byte b : bytes) { + for(byte b : trim(bytes)) { if(!((b >= '0' && b <= '9') || (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b == '+') || (b == '/') || (b == '='))) { return false; } @@ -80,6 +80,19 @@ public class Utils { return true; } + private static byte[] trim(byte[] bytes) { + int len = bytes.length; + int st = 0; + while ((st < len) && Character.isWhitespace((bytes[st] & 0xff))) { + st++; + } + while ((st < len) && Character.isWhitespace((bytes[len - 1] & 0xff))) { + len--; + } + + return ((st > 0) || (len < bytes.length)) ? Arrays.copyOfRange(bytes, st, len) : bytes; + } + public static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for ( int j = 0; j < bytes.length; j++ ) {