dojo / core

:rocket: Dojo 2 - language helpers and utilities.
http://dojo.io
Other
213 stars 62 forks source link

dojo/core encoding.ts - base64 does not work anymore #299

Closed sebilasse closed 7 years ago

sebilasse commented 7 years ago

I am not sure about base64 but it returns different results compared to my own base64 functions ... However even directly decoding an encoded string returns a wrong result : A very simple test was console.log( base64.decode(base64.encode('Lorem')) );

Should result: 'Lorem' This results in 'Lore' ...

Apart from that if I've got characters like + it was a completely different result.

What I am basically looking for are the functions to encode/decode any string to base64 and to base64Url. This is what I am currently using:

export function escape(str: string) {
  return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
}
export function unescape(str: string) {
  str = str.toString();
  var mod = str.length % 4;
  if (mod !== 0) { str += _repeat('=', 4 - mod); }
  return str.replace(/\-/g, '+').replace(/_/g, '/');
}

function _repeat(str: string, num: number) { return new Array(num + 1).join(str); };
/* base64 --> */
export function base64Encode(str: string) {
  if (has('host-node')) {
    return new Buffer(str).toString('base64');
  } else {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(m, p1) {
      return String.fromCharCode(parseInt(('0x'+p1), 16));
    }));
  }
}
export function base64Decode(b64String: string | Buffer) {
  b64String = b64String.toString();
  if (has('host-node')) {
    return (new Buffer(b64String, 'base64')).toString('utf8');
  } else {
    return decodeURIComponent(b64String.split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
  }
}
export function base64UrlEncode(str: string): string {
  return escape(base64Encode(str));
}
export function base64UrlDecode(b64String: string | Buffer): string {
  b64String = b64String.toString();
  return base64Decode(unescape(b64String));
}
/* <-- base64 */
kitsonk commented 7 years ago

I ended up doing a unintentional fix for this in dojo/web-editor#7 which I should port over to here to fix the issue.

kitsonk commented 7 years ago

Taking a look at this, the API don't do what you might think it does. It really is designed for encoding an already base64 encoded string into a structured array, which can be handled in other ways. I think its general utility as part of core isn't actually that critical. I think it was more useful for our streams and encryption packages, which we haven't yet found a compelling need to migrate those to a beta stage. (Though neither package actually uses these).

We might want consider removing this from core until there is a compelling use case for it. One is alluding me at the moment. Also the utility that @sebilasse is essentially what I needed in web-editor. I will introduce that instead.