https://web.archive.org/web/20110422225659/https://en.wikipedia.org/wiki/Base64#URL_applications
talks about base64Url - Decode
a modified Base64 for U
This class can help:
import android.util.Base64;
public class Encryptor {
public static String encode(String input) {
return Base64.encodeToString(input.getBytes(), Base64.URL_SAFE);
}
public static String decode(String encoded) {
return new String(Base64.decode(encoded.getBytes(), Base64.URL_SAFE));
}
}
With the usage of Base64
from Apache Commons, who can be configured to URL safe, I created the following function:
import org.apache.commons.codec.binary.Base64;
public static String base64UrlDecode(String input) {
String result = null;
Base64 decoder = new Base64(true);
byte[] decodedBytes = decoder.decode(input);
result = new String(decodedBytes);
return result;
}
The constructor Base64(true)
makes the decoding URL-safe.
Java8+
import java.util.Base64;
return Base64.getUrlEncoder().encodeToString(bytes);
In Java try the method Base64.encodeBase64URLSafeString()
from Commons Codec library for encoding.
@ufk's answer works, but you don't actually need to set the urlSafe
flag when you're just decoding.
urlSafe is only applied to encode operations. Decoding seamlessly handles both modes.
Also, there are some static helpers to make it shorter and more explicit:
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
public static String base64UrlDecode(String input) {
StringUtils.newStringUtf8(Base64.decodeBase64(input));
}
Docs
Right off the bat, it looks like your replace()
is backwards; that method replaces the occurrences of the first character with the second, not the other way around.