Created
October 14, 2015 02:23
-
-
Save yuezk/5fdcb487971482a43897 to your computer and use it in GitHub Desktop.
按照 CC 文档中描述的 THQS 加密算法对提交的数据进行加密处理
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 依赖 JS 的 MD5 库 https://blueimp.github.io/JavaScript-MD5/js/md5.js | |
// 按照 CC 文档中描述的 THQS 加密算法对提交的数据进行加密处理 | |
// 具体的加密算法在 http://t.cn/Ry3Hs7W 的附录部分 | |
function encrypt(data) { | |
// 1. 将键值对按照 key 的升序排序 | |
var qs = data.sort(function (a, b) { | |
return a.name > b.name; | |
}).map(function (item) { | |
return item.name + '=' + encodeURIComponent(item.value); | |
}); | |
// 2. 加入时间戳和 API_KEY | |
qs.push('time=' + Math.floor(new Date().getTime() / 1000)); | |
qs.push('salt=' + API_KEY); | |
// 3. md5 计算得出 hash | |
qs.push('hash=' + md5(qs.join('&'))); | |
// 4. remove salt | |
qs.splice(-2, 1); | |
return qs.join('&'); | |
} | |
// 用法 | |
var data = [ | |
{ | |
name: 'foo', | |
value: 'foo_value' | |
}, { | |
name: 'bar', | |
value: 'bar_value' | |
}, | |
... | |
]; | |
var qs = encrypt(data); | |
console.log(qs); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment