Skip to content

Core: decodeBase64() catches and falls back to base64url using exceptions for control flow #2159

@rahul0611

Description

@rahul0611

Environment details

  • Type: Core
  • OS type and version: (please specify)
  • Java version: (please specify)
  • google-http-client version(s): (please specify)

Steps to reproduce

  1. Call Base64.decodeBase64() with a Base64url-encoded string (containing '-' and '_'), or any string that is not valid standard Base64.
  2. Observe that the method attempts to decode using the standard decoder, catches IllegalArgumentException, and then retries with the Base64url decoder iff the cause is an instance of DecodingException.

Code example

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;
  }
}

Stack trace

(Provide if applicable)

External references such as API reference guides

Any additional information below

  • The implementation of decodeBase64(String base64String) relies on catching exceptions to distinguish standard Base64 from Base64url, which is not optimal for control flow and impacts performance.
  • This pattern is dated and can mask genuine decoding issues.
  • Suggestion: Consider pre-detecting the encoding style (by inspecting the characters for '-'/'_' or '+'/'/') or letting callers specify which decoder to use.
  • Recommend avoiding exceptions for normal logic flow; rely on them for truly exceptional situations.

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions