Skip to content

Commit 0fe06ac

Browse files
fix: validate that all characters after first padding character in Base64 decode (#7491)
fix: validate that all characters after first padding character are also padding characters
1 parent a508fd2 commit 0fe06ac

2 files changed

Lines changed: 12 additions & 2 deletions

File tree

src/main/java/com/thealgorithms/conversions/Base64.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,8 +119,15 @@ public static byte[] decode(String input) {
119119

120120
// Validate padding: '=' can only appear at the end (last 1 or 2 chars)
121121
int firstPadding = input.indexOf('=');
122-
if (firstPadding != -1 && firstPadding < input.length() - 2) {
123-
throw new IllegalArgumentException("Padding '=' can only appear at the end (last 1 or 2 characters)");
122+
if (firstPadding != -1) {
123+
if (firstPadding < input.length() - 2) {
124+
throw new IllegalArgumentException("Padding '=' can only appear at the end (last 1 or 2 characters)");
125+
}
126+
for (int i = firstPadding; i < input.length(); i++) {
127+
if (input.charAt(i) != '=') {
128+
throw new IllegalArgumentException("A padding '=' must not be followed by a non-padding character");
129+
}
130+
}
124131
}
125132

126133
List<Byte> result = new ArrayList<>();

src/test/java/com/thealgorithms/conversions/Base64Test.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,9 @@ void testInvalidPaddingPosition() {
127127
assertThrows(IllegalArgumentException.class, () -> Base64.decode("Q=QQ"));
128128
assertThrows(IllegalArgumentException.class, () -> Base64.decode("Q=Q="));
129129
assertThrows(IllegalArgumentException.class, () -> Base64.decode("=QQQ"));
130+
assertThrows(IllegalArgumentException.class, () -> Base64.decode("QQ=Q"));
131+
assertThrows(IllegalArgumentException.class, () -> Base64.decode("AB=C"));
132+
assertThrows(IllegalArgumentException.class, () -> Base64.decode("AB=A"));
130133
}
131134

132135
@Test

0 commit comments

Comments
 (0)