java - Why do Base64.decode produce same byte array for different strings? -


i'm using url safe base64 encoding encode randomly generated byte arrays. have problem on decoding. when decode 2 different strings (all last chars identical), produces same byte array. example, both "dgvzdcbzdhjpbmr" , "dgvzdcbzdhjpbmq" strings result same:

array(116, 101, 115, 116, 32, 115, 116, 114, 105, 110, 106) 

for encoding/decoding use java.util.base64 in way:

// encoding... base64.geturlencoder().withoutpadding().encodetostring(mystring.getbytes()) // decoding... base64.geturldecoder().decode(base64string) 

what reason of collision? possible chars other last one? , how can fix , make decoding return different byte array each different string?

the issue seeing, caused fact number of bytes have in "result" (11 bytes) doesn't "fill" last char of base64 encoded string.

remember base64 encodes each 8 bit entity 6 bit chars. resulting string needs 11 * 8 / 6 bytes, or 14 2/3 chars. can't write partial characters. first 4 bits (or 2/3 of last char) significant. last 2 bits not decoded. of:

dgvzdcbzdhjpbmo dgvzdcbzdhjpbmp dgvzdcbzdhjpbmq dgvzdcbzdhjpbmr 

all decode same 11 bytes (116, 101, 115, 116, 32, 115, 116, 114, 105, 110, 106).

ps: without padding, decoders try decode "last" byte well, , you'll have 12 byte result (with different last byte). reason comment (asking if withoutpadding() option idea). decoder seems handle this.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -