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.

VOLVO
  • 541
  • 5
  • 16

1 Answers1

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

Luc
  • 1,393
  • 1
  • 6
  • 14