Remove trailing “=” when base64 encoding

前端 未结 9 1993
时光取名叫无心
时光取名叫无心 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:25

    For Android You may have trouble if You want to use android.util.base64 class, since that don't let you perform UnitTest others that integration test - those uses Adnroid environment.

    In other hand if You will use java.util.base64, compiler warns You that You sdk may to to low (below 26) to use it.

    So I suggest Android developers to use

    implementation "commons-codec:commons-codec:1.13"
    

    Encoding object

    fun encodeObjectToBase64(objectToEncode: Any): String{
        val objectJson = Gson().toJson(objectToEncode).toString()
        return encodeStringToBase64(objectJson.toByteArray(Charsets.UTF_8))
    }
    
    fun encodeStringToBase64(byteArray: ByteArray): String{
        return Base64.encodeBase64URLSafeString(byteArray).toString() // encode with no padding
    }
    

    Decoding to Object

    fun <T> decodeBase64Object(encodedMessage: String, encodeToClass: Class<T>): T{
        val decodedBytes = Base64.decodeBase64(encodedMessage)
        val messageString = String(decodedBytes, StandardCharsets.UTF_8)
        return Gson().fromJson(messageString, encodeToClass)
    }
    

    Of course You may omit Gson parsing and put straight away into method Your String transformed to ByteArray

    0 讨论(0)
  • 2020-11-30 00:27

    = is added for padding. The lenght of a base64 string should be multiple of 4, so 1 or 2 = are added as necessary.

    Read: No, you shouldn't remove it.

    0 讨论(0)
  • 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

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