Remove trailing “=” when base64 encoding

前端 未结 9 2028
时光取名叫无心
时光取名叫无心 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  decodeBase64Object(encodedMessage: String, encodeToClass: Class): 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

提交回复
热议问题