dankogai / js-base64

Base64 implementation for JavaScript
BSD 3-Clause "New" or "Revised" License
4.27k stars 1.33k forks source link

Cannot decode js-base64 UTF-8 encoded String #158

Closed Sercurio closed 1 year ago

Sercurio commented 2 years ago

Hi! I'm trying to decode a string containing an UTF-8 character from the javascript library to Java server:

My test: index.js

import { Base64 } from 'js-base64';

function App() {
  console.log(Base64.encode("louis:€"));
}

Decoder.java

class DecoderTest{
    @org.junit.jupiter.api.Test
    void readToken() {
        String x = new String(Base64.getEncoder().encode("louis:€".getBytes(StandardCharsets.UTF_8)));
        Assertions.assertEquals("louis:€", readToken2(x));
        Assertions.assertEquals("louis:€", readToken2("Basic bG91aXM64oKs"));
    }

    public static String readToken2(String token) {
        String cleanToken = token.replace("Basic ", "");
        byte[] bytesToken = cleanToken.getBytes(StandardCharsets.UTF_8);
        byte[] bytesDecoded = Base64.getDecoder().decode(bytesToken);
        String decoded = new String(bytesDecoded, StandardCharsets.UTF_8);
        return decoded;
    }
}

The output of the test:

org.opentest4j.AssertionFailedError: 
Expected :louis:€
Actual   :louis:�
<Click to see difference>
dankogai commented 1 year ago

I thinks it is your decoder's problem. Here is the REPL of node.js.

> var str = "louis:€"
undefined
> Base64.encode(str)
'bG91aXM64oKs'
> Base64.decode(Base64.encode(str)) === str
true