base64url in java

前端 未结 10 582
攒了一身酷
攒了一身酷 2020-12-05 06:49

https://web.archive.org/web/20110422225659/https://en.wikipedia.org/wiki/Base64#URL_applications

talks about base64Url - Decode


a modified Base64 for U

相关标签:
10条回答
  • 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));
        }
    }
    
    0 讨论(0)
  • 2020-12-05 07:17

    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.

    0 讨论(0)
  • 2020-12-05 07:19

    Java8+

    import java.util.Base64;
    
    
    return Base64.getUrlEncoder().encodeToString(bytes);
    
    0 讨论(0)
  • 2020-12-05 07:23

    In Java try the method Base64.encodeBase64URLSafeString() from Commons Codec library for encoding.

    0 讨论(0)
  • 2020-12-05 07:26

    @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

    • newStringUtf8()
    • decodeBase64()
    0 讨论(0)
  • 2020-12-05 07:31

    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.

    0 讨论(0)
提交回复
热议问题