2

I use this code in C#.net to send challenge to web page.

        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        Byte[] rnd = new Byte[64];
        rng.GetBytes(rnd);
        hidChallenge.Value = Encoding.Unicode.GetString(rnd);

And I in java script use of it.

var base64str = document.getElementById("<%=hidChallenge.ClientID %>");

When run and debug:

base64str =  感≗좦短䗅燛梻脕冔춇噙풣訋詇蹘᧩쾏휇᯸늸䫐顨◣希ࠟ䠎ᐷ

But in java (JSP)

I use this code:

Random r = new Random();
byte[] rndbyte = new byte[64];
r.nextBytes(rndbyte);
String challenge = new String(rndbyte,StandardCharsets.UTF_16LE);                    
session.setAttribute("challenge", challenge);

And in javascript:

var base64str = 퓻�ꦖ쁳春꼪ꝝ䣇͋ꟼ鱐䆺㺪᠁郷̣攺줶ꋏ歮㏹㬎ꢔ崬魔弝孓翊

I try follow charset also:

US_ASCII

UTF_8

UTF_16

So I get base 64 string error.

2
  • WTF? This is not base64. This is... Ok, I have seen this. Will break if two bytes are inside the surrogate range. Commented Apr 29, 2018 at 11:43
  • Honestly, just use base64. Commented Apr 29, 2018 at 11:47

1 Answer 1

3

it sounds like there is a confusion between what UTF-8/16 or Ascii are for, and Base64.

UTF-8 is meant to encode string to byte sequence. And Base64 is meant to encode byte sequence to string.

If you want to generate base64 in Java, here is how it should look like:

Random r = new Random();
byte[] rndbyte = new byte[64];
r.nextBytes(rndbyte);
String challenge = Base64.encodeBase64String(rndbyte);                    
session.setAttribute("challenge", challenge);

Here is another post that explain pretty good the difference, if you want to know more about this: What's the difference between UTF8/UTF16 and Base64 in terms of encoding

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.