base64url in java

前端 未结 10 583
攒了一身酷
攒了一身酷 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条回答
  • 2020-12-05 07:33

    Guava now has Base64 decoding built in.

    https://google.github.io/guava/releases/17.0/api/docs/com/google/common/io/BaseEncoding.html

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

    Base64 encoding is part of the JDK since Java 8. URL safe encoding is also supported with java.util.Base64.getUrlEncoder(), and the "=" padding can be skipped by additionally using the java.util.Base64.Encoder.withoutPadding() method:

    import java.nio.charset.StandardCharsets;
    import java.util.Base64;
    
    public String encode(String raw) {
        return Base64.getUrlEncoder()
                .withoutPadding()
                .encodeToString(raw.getBytes(StandardCharsets.UTF_8));
    }
    
    0 讨论(0)
  • 2020-12-05 07:34
    public static byte[] encodeUrlSafe(byte[] data) {
        byte[] encode = Base64.encode(data);
        for (int i = 0; i < encode.length; i++) {
            if (encode[i] == '+') {
                encode[i] = '-';
            } else if (encode[i] == '/') {
                encode[i] = '_';
            }
        }
        return encode;
    }
    
    public static byte[] decodeUrlSafe(byte[] data) {
        byte[] encode = Arrays.copyOf(data, data.length);
        for (int i = 0; i < encode.length; i++) {
            if (encode[i] == '-') {
                encode[i] = '+';
            } else if (encode[i] == '_') {
                encode[i] = '/';
            }
        }
        return Base64.decode(encode);
    }
    
    0 讨论(0)
  • 2020-12-05 07:38

    In the Android SDK, there's a dedicated flag in the Base64 class: Base64.URL_SAFE, use it like so to decode to a String:

    import android.util.Base64;
    byte[] byteData = Base64.decode(body, Base64.URL_SAFE);
    str = new String(byteData, "UTF-8");
    
    0 讨论(0)
提交回复
热议问题