From 270c64a4eeedf0343f54e3199048d5ebe1402621 Mon Sep 17 00:00:00 2001 From: Rebecca Lu Date: Thu, 7 Sep 2017 16:26:49 +0800 Subject: [PATCH] fix(base64): base64 decode/encode unicode --- src/getMeta.js | 11 ++++++++++- src/getResult.js | 9 ++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/getMeta.js b/src/getMeta.js index 1eef938..bb00318 100644 --- a/src/getMeta.js +++ b/src/getMeta.js @@ -10,6 +10,15 @@ function randomHexStr(length) { return str; } +function b64EncodeUnicode(str) { + // First we use encodeURIComponent to get percent-encoded UTF-8, + // then we convert the percent encodings into raw bytes which + // can be fed into btoa. + return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, + (match, p1) => String.fromCharCode('0x' + p1) + )); +} + function getMeta(item, secret, appId) { const salt = `${Math.floor(Date.now() / 1000)}:${randomHexStr(8)}`; const metaObj = { @@ -23,7 +32,7 @@ function getMeta(item, secret, appId) { const metaPrefix = JSON.stringify(metaObj); const hash = md5(`${appId}+${metaPrefix}+${salt}+${secret}`); - return btoa(`${metaPrefix};hash=${hash}`); + return b64EncodeUnicode(`${metaPrefix};hash=${hash}`); } export default getMeta; diff --git a/src/getResult.js b/src/getResult.js index 279d9fd..d53fd67 100644 --- a/src/getResult.js +++ b/src/getResult.js @@ -1,6 +1,13 @@ +function b64DecodeUnicode(str) { + // Going backwards: from bytestream, to percent-encoding, to original string. + return decodeURIComponent(atob(str).split('').map(c => { + return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); + }).join('')); +} + function getResult(meta) { try { - meta.result = eval('(' + atob(meta.result) + ')'); // eslint-disable-line no-eval + meta.result = eval('(' + b64DecodeUnicode(meta.result) + ')'); // eslint-disable-line no-eval } catch (e) { }