Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
package com.google.api.client.util;

import com.google.common.io.BaseEncoding;
import com.google.common.io.BaseEncoding.DecodingException;

/**
* Proxy for handling Base64 encoding/decoding.
Expand Down Expand Up @@ -99,8 +98,8 @@ public static byte[] decodeBase64(byte[] base64Data) {
* Decodes a Base64 String into octets. Note that this method handles both URL-safe and
* non-URL-safe base 64 encoded strings.
*
* <p>For the compatibility with the old version that used Apache Commons Coded's decodeBase64,
* this method discards new line characters and trailing whitespaces.
* <p>For compatibility with the old version that used Apache Commons Codec's decodeBase64, this
* method discards new line characters and trailing whitespaces.
*
* @param base64String String containing Base64 data or {@code null} for {@code null} result
* @return Array containing decoded data or {@code null} for {@code null} input
Expand All @@ -109,14 +108,12 @@ public static byte[] decodeBase64(String base64String) {
if (base64String == null) {
return null;
}
try {
return BASE64_DECODER.decode(base64String);
} catch (IllegalArgumentException e) {
if (e.getCause() instanceof DecodingException) {
return BASE64URL_DECODER.decode(base64String.trim());
}
throw e;
}
String normalizedBase64String = base64String.trim();
BaseEncoding decoder =
normalizedBase64String.indexOf('-') >= 0 || normalizedBase64String.indexOf('_') >= 0
? BASE64URL_DECODER
: BASE64_DECODER;
return decoder.decode(normalizedBase64String);
}

private Base64() {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,21 @@ public void test_decodeBase64_withoutPadding() {
assertEquals("foo:bar", new String(Base64.decodeBase64(encoded), StandardCharsets.UTF_8));
}

@Test
public void test_decodeBase64_urlSafe() {
assertThat(Base64.decodeBase64("-_8=")).isEqualTo(new byte[] {(byte) 0xfb, (byte) 0xff});
}

@Test
public void test_decodeBase64_urlSafeWithoutPadding() {
assertThat(Base64.decodeBase64("-_8")).isEqualTo(new byte[] {(byte) 0xfb, (byte) 0xff});
}

@Test
public void test_decodeBase64_urlSafeWithTrailingWhitespace() {
assertThat(Base64.decodeBase64("-_8=\r\n")).isEqualTo(new byte[] {(byte) 0xfb, (byte) 0xff});
}

@Test
public void test_decodeBase64_withTrailingWhitespace() {
// Some internal use cases append extra space characters that apache-commons base64 decoding
Expand Down
Loading