2012年2月

ajax中使用HTTP Basic Authenticate

抓包可以发现其实就是多了个header,header串可以如下构造:

[code language="javascript"]
function make_base_auth(user, password) {
var tok = user + ':' + pass;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
[/code]

Base64.encode自己网上找个base64编码的javascript版就可以了,这里不提供。
以下为用jQuery发送请求的代码:

[code language="javascript"]
var auth = make_basic_auth('me', 'mypassword'); //用户名和密码
var url = 'http://example.com';
$.ajax({
url : url,
method : 'GET',
beforeSend : function(req) {
req.setRequestHeader('Authorization', auth);
}
});
[/code]

base32 encoding in javascript

经测试不支持中文,只支持英文字符。

[code language="javascript"]
var baseenc = baseenc || {};
baseenc.b32encode = function(s) {
/* encodes a string s to base32 and returns the encoded string */
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";

var parts = [];
var quanta= Math.floor((s.length / 5));
var leftover = s.length % 5;

if (leftover != 0) {
for (var i = 0; i < (5-leftover); i++) { s += '\x00'; }
quanta += 1;
}

for (i = 0; i < quanta; i++) {
parts.push(alphabet.charAt(s.charCodeAt(i*5) >> 3));
parts.push(alphabet.charAt( ((s.charCodeAt(i*5) & 0x07) << 2)
| (s.charCodeAt(i*5+1) >> 6)));
parts.push(alphabet.charAt( ((s.charCodeAt(i*5+1) & 0x3F) >> 1) ));
parts.push(alphabet.charAt( ((s.charCodeAt(i*5+1) & 0x01) << 4)
| (s.charCodeAt(i*5+2) >> 4)));
parts.push(alphabet.charAt( ((s.charCodeAt(i*5+2) & 0x0F) << 1)
| (s.charCodeAt(i*5+3) >> 7)));
parts.push(alphabet.charAt( ((s.charCodeAt(i*5+3) & 0x7F) >> 2)));
parts.push(alphabet.charAt( ((s.charCodeAt(i*5+3) & 0x03) << 3)
| (s.charCodeAt(i*5+4) >> 5)));
parts.push(alphabet.charAt( ((s.charCodeAt(i*5+4) & 0x1F) )));
}

var replace = 0;
if (leftover == 1) replace = 6;
else if (leftover == 2) replace = 4;
else if (leftover == 3) replace = 3;
else if (leftover == 4) replace = 1;

for (i = 0; i < replace; i++) parts.pop();
for (i = 0; i < replace; i++) parts.push("=");

return parts.join("");
};
[/code]

via