Skip to content

Commit cdc5b28

Browse files
committed
fix: Base64 decoding to discard newline characters
1 parent 31e847a commit cdc5b28

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

google-http-client/src/test/java/com/google/api/client/util/Base64Test.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,4 +62,45 @@ public void test_encodeBase64URLSafe_withNull_shouldReturnNull() {
6262
public void test_encodeBase64_withNull_shouldReturnNull() {
6363
assertNull(Base64.encodeBase64(null));
6464
}
65+
66+
public void test_decodeBase64_newline_character_invalid_length() {
67+
// The RFC 4648 (https://datatracker.ietf.org/doc/html/rfc4648#section-3.3) states that a
68+
// specification referring to the Base64 encoding may state that it ignores characters outside
69+
// the base alphabet.
70+
71+
// In Base64 encoding, 3 characters (24 bits) are converted to 4 of 6-bits, each of which is
72+
// converted to a byte (a character).
73+
// Base64encode("abc") => "YWJj" (4 characters)
74+
// Base64encode("def") => "ZGVm" (4 characters)
75+
// Adding a new line character between them. This should be discarded.
76+
String encodedString = "YWJj\nZGVm";
77+
78+
// This is a reference implementation by Apache Commons Codec. It discards the new line
79+
// characters.
80+
assertEquals(
81+
"abcdef",
82+
new String(
83+
org.apache.commons.codec.binary.Base64.decodeBase64(encodedString),
84+
StandardCharsets.UTF_8));
85+
// This is our implementation
86+
assertEquals("abcdef", new String(Base64.decodeBase64(encodedString), StandardCharsets.UTF_8));
87+
}
88+
89+
public void test_decodeBase64_newline_character_between() {
90+
// In Base64 encoding, 2 characters (16 bits) are converted to 3 of 6-bits plus the padding
91+
// character ('=").
92+
// Base64encode("ab") => "YWI=" (3 characters + padding character)
93+
// Adding a new line character that should be discarded between them
94+
String encodedString = "YW\nI=";
95+
96+
// This is a reference implementation by Apache Commons Codec. It discards the new line
97+
// characters.
98+
assertEquals(
99+
"ab",
100+
new String(
101+
org.apache.commons.codec.binary.Base64.decodeBase64(encodedString),
102+
StandardCharsets.UTF_8));
103+
// This is our implementation
104+
assertEquals("ab", new String(Base64.decodeBase64(encodedString), StandardCharsets.UTF_8));
105+
}
65106
}

0 commit comments

Comments
 (0)