Remove trailing “=” when base64 encoding

前端 未结 9 2046
时光取名叫无心
时光取名叫无心 2020-11-29 23:58

I am noticing that whenever I base64 encode a string, a \"=\" is appended at the end. Can I remove this character and then reliably decode it later by adding it back, or is

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 00:30

    On Android I am using this:

    Global

    String CHARSET_NAME ="UTF-8";
    

    Encode

    String base64 = new String(
                Base64.encode(byteArray, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_CLOSE | Base64.NO_WRAP),
                CHARSET_NAME);
    return base64.trim();
    

    Decode

    byte[] bytes = Base64.decode(base64String,
                Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_CLOSE | Base64.NO_WRAP);
    

    equals this on Java:

    Encode

    private static String base64UrlEncode(byte[] input)
    {
        Base64 encoder = new Base64(true);
        byte[] encodedBytes = encoder.encode(input);
        return StringUtils.newStringUtf8(encodedBytes).trim();
    }
    

    Decode

    private static byte[] base64UrlDecode(String input) {
        byte[] originalValue = StringUtils.getBytesUtf8(input);
        Base64 decoder = new Base64(true);
        return decoder.decode(originalValue);
    }
    

    I had never problems with trailing "=" and I am using Bouncycastle as well

提交回复
热议问题