Skip to content

Commit

Permalink
fix(base64): base64 decode/encode unicode
Browse files Browse the repository at this point in the history
  • Loading branch information
Y--p--Y committed Sep 7, 2017
1 parent d76ef50 commit 270c64a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
11 changes: 10 additions & 1 deletion src/getMeta.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand All @@ -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;
9 changes: 8 additions & 1 deletion src/getResult.js
Original file line number Diff line number Diff line change
@@ -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) {
}

Expand Down

0 comments on commit 270c64a

Please sign in to comment.