简体   繁体   中英

Java Base64 MIME decoding/encoding throws away delimiters

I have a Base64-encoded string that looks like "data:image/png;base64,iVBORw0K" . I'm trying to decode it back to binary and later encode it again into Base64 using java.util.Base64 . Strangely, after decoding and encoding again, I would lose the delimiters and get back "dataimage/pngbase64iVBORw0I=" .

This is how I do the decoding and encoding (written in Scala, but you get the idea):

import java.util.Base64

val b64mime = "data:image/png;base64,iVBORw0K"

val decoder = Base64.getMimeDecoder
val encoder = Base64.getMimeEncoder

println(encoder.encodeToString(decoder.decode(b64mime)))

Here is an example: https://scalafiddle.io/sf/TJY7eeg/0

This also happens with javax.xml.bind.DatatypeConverter . What am I doing wrong? Is this the expected behavior?

The string you are trying to deal with looks like an example of a "data:" URL as specified in RFC 2397

The correct way to deal with one of these is parse it into its components, and then decode only the component that is base64 encoded. Here is the syntax

   dataurl    := "data:" [ mediatype ] [ ";base64" ] "," data
   mediatype  := [ type "/" subtype ] *( ";" parameter )
   data       := *urlchar
   parameter  := attribute "=" value

So this says that everything up to the comma in your example is non-base64 data. You cannot simply treat the whole string as base64 because it contains characters that are not valid in any standard variant of the base64 encoding scheme.

This Q&A talks about RFC 2397 parsers in Java:

Base64 doesnt have those characters in it. It looks like the decoder is ignoring those invalid characters.

@ decoder.decode(";") 
res10: Array[Byte] = Array()

However if you just decode the last part you get what you want.

@ decoder.decode("iVBORw0K") 
res9: Array[Byte] = Array(-119, 80, 78, 71, 13, 10)
@ encoder.encodeToString(res9) 
res12: String = "iVBORw0K"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM