0

Mine is an Phonegap project supporting for two platforms(Android and IOS).

For any server request I need to set the authorization header.This Header should be in encoded base64 UTF-16LE format to receive the response.

I am able to encode it to base64 by using jquery base-64 plugin.

var base64Enc=$.base64.encode("Surya@gmail.com"+":"+"Password01");

This works fine.But I need to convert this into UTF-16LE which has to be set as authorization header for my request.

beforeSend: function(xhr){
             xhr.setRequestHeader("Content-Type", "application/json");
             xhr.setRequestHeader("Authorization", "Basic " + base64Enc);
        },

How can I convert base64Enc into UTF-16LE. In java i can do the same by using new String(Base64.encodeBase64("Surya@gmail.com:Password01".getBytes("UTF-16LE")))

Please help me how to do this in JavaScript/jquery.Does Jquery has any plugin to do this coversion or should I have to use any utilities to achive this.

Please help me on this.Thanks in advance.

Surya
  • 439
  • 3
  • 9
  • 31

1 Answers1

0

With the assumption that you don't have to support IE < 10, use native ECMAScript.

Use window.atob()1 and window.btoa()2

Since:

DOMStrings are 16-bit-encoded strings 3

/* Base64 Encode */ 
var base64Enc = window.btoa("Surya@gmail.com"+":"+"Password01");

/* Base64 Decode (as UTF16 DOMString) */
var utf16Dec = window.atob(base64Enc);

1 https://developer.mozilla.org/en-US/docs/Web/API/window.atob

2 https://developer.mozilla.org/en-US/docs/Web/API/window.btoa

3 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding

couzzi
  • 6,316
  • 3
  • 24
  • 40
  • Mine is an mobile app (Phonegap)which Im supporting for Android and IOS.Is this approach going to work for Mobile apps.? – Surya Oct 23 '13 at 05:28
  • AFAIK, yes. It is my understanding that Phonegap simply wraps a webview—so under the hood, it's still Javascript/HTML etc. The above approach works in Webkit which both iOS and Android's browsers run inherently. – couzzi Oct 23 '13 at 16:40
  • 1
    I am able to convert into base64 by using $.base64.encode("Surya@gmail.com"+":"+"Password01")/window.btoa("Surya@gmail.com"+":"+"Password01");But I wanted this in base64 UTF-16LE format.How do i covert it into UTF-16LE ? – Surya Oct 24 '13 at 05:03
  • Yes.All of them are returning UTF8 not UTF16.:( – Surya Oct 28 '13 at 05:00
  • window.btoa("lame") returns "bGFtZQ==" when it should return the same as echo -n lame|iconv -f UTF-8 -t UTF-16LE |base64 which is bABhAG0AZQA= btoa is encoding the strings as UTF8 – pierce Jan 18 '17 at 20:26