https://github.com/mattrobenolt/node_nibbler

可以将本源码复制到自己需要的JS文件中,比如下面这个文件,一个基于BASE64加密请求参数的REST工具:

【附件:】REST-TEST.html

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>REST-TEST</title>
<script type="text/javascript"
src="http://libs.baidu.com/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var Nibbler = function (options) {
var construct, // options
pad, dataBits, codeBits, keyString, arrayData, // private instance variables
mask, group, max, // private methods
gcd, translate, // public methods
encode, decode, utf16to8, utf8to16; // pseudo-constructor
construct = function () {
var i, mag, prev; // options
pad = options.pad || '';
dataBits = options.dataBits;
codeBits = options.codeBits;
keyString = options.keyString;
arrayData = options.arrayData; // bitmasks
mag = Math.max(dataBits, codeBits);
prev = 0;
mask = [];
for (i = 0; i < mag; i += 1) {
mask.push(prev);
prev += prev + 1;
}
max = prev; // ouput code characters in multiples of this number
group = dataBits / gcd(dataBits, codeBits);
}; // greatest common divisor
gcd = function (a, b) {
var t;
while (b !== 0) {
t = b;
b = a % b;
a = t;
}
return a;
}; // the re-coder
translate = function (input, bitsIn, bitsOut, decoding) {
var i, len, chr, byteIn,
buffer, size, output,
write; // append a byte to the output
write = function (n) {
if (!decoding) {
output.push(keyString.charAt(n));
} else if (arrayData) {
output.push(n);
} else {
output.push(String.fromCharCode(n));
}
}; buffer = 0;
size = 0;
output = []; len = input.length;
for (i = 0; i < len; i += 1) {
// the new size the buffer will be after adding these bits
size += bitsIn; // read a character
if (decoding) {
// decode it
chr = input.charAt(i);
byteIn = keyString.indexOf(chr);
if (chr === pad) {
break;
} else if (byteIn < 0) {
throw 'the character "' + chr + '" is not a member of ' + keyString;
}
} else {
if (arrayData) {
byteIn = input[i];
} else {
byteIn = input.charCodeAt(i);
}
if ((byteIn | max) !== max) {
throw byteIn + " is outside the range 0-" + max;
}
} // shift the buffer to the left and add the new bits
buffer = (buffer << bitsIn) | byteIn; // as long as there's enough in the buffer for another output...
while (size >= bitsOut) {
// the new size the buffer will be after an output
size -= bitsOut; // output the part that lies to the left of that number of bits
// by shifting the them to the right
write(buffer >> size); // remove the bits we wrote from the buffer
// by applying a mask with the new size
buffer &= mask[size];
}
} // If we're encoding and there's input left over, pad the output.
// Otherwise, leave the extra bits off, 'cause they themselves are padding
if (!decoding && size > 0) { // flush the buffer
write(buffer << (bitsOut - size)); // add padding keyString for the remainder of the group
len = output.length % group;
for (i = 0; i < len; i += 1) {
output.push(pad);
}
} // string!
return (arrayData && decoding) ? output : output.join('');
}; /**
* Encode. Input and output are strings.
*/
encode = function (str) {
//return translate(input, dataBits, codeBits, false);
str = utf16to8(str);
var out = "", i = 0, len = str.length, c1, c2, c3, base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
while (i < len) {
c1 = str.charCodeAt(i++) & 0xff;
if (i == len) {
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt((c1 & 0x3) << 4);
out += "==";
break;
}
c2 = str.charCodeAt(i++);
if (i == len) {
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt(((c1 & 0x3) << 4)
| ((c2 & 0xF0) >> 4));
out += base64EncodeChars.charAt((c2 & 0xF) << 2);
out += "=";
break;
}
c3 = str.charCodeAt(i++);
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt(((c1 & 0x3) << 4)
| ((c2 & 0xF0) >> 4));
out += base64EncodeChars.charAt(((c2 & 0xF) << 2)
| ((c3 & 0xC0) >> 6));
out += base64EncodeChars.charAt(c3 & 0x3F);
}
return out;
}; /**
* Decode. Input and output are strings.
*/
decode = function (str) {
//return translate(input, codeBits, dataBits, true);
var c1, c2, c3, c4; var i, len,out;
var base64DecodeChars = new Array(-1, -1, -1, -1, -1,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53,54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1,0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26,27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);len = str.length; i = 0; out = ""; while (i < len) { do { c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff]; } while (i < len && c1 == -1); if (c1 == -1) break; do { c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff]; } while (i < len && c2 == -1); if (c2 == -1) break; out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4)); do { c3 = str.charCodeAt(i++) & 0xff; if (c3 == 61) {out = utf8to16(out);return out;} c3 = base64DecodeChars[c3]; } while (i < len && c3 == -1); if (c3 == -1) break; out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2)); do { c4 = str.charCodeAt(i++) & 0xff; if (c4 == 61) {out = utf8to16(out);return out;} c4 = base64DecodeChars[c4]; } while (i < len && c4 == -1); if (c4 == -1) break; out += String.fromCharCode(((c3 & 0x03) << 6) | c4); } out = utf8to16(out);return out;
}; utf16to8 = function (str){
var out, i, len, c;
out = "";
len = str.length;
for (i = 0; i < len; i++) {
c = str.charCodeAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
out += str.charAt(i);
} else if (c > 0x07FF) {
out += String
.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
out += String
.fromCharCode(0x80 | ((c >> 6) & 0x3F));
out += String
.fromCharCode(0x80 | ((c >> 0) & 0x3F));
} else {
out += String
.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
out += String
.fromCharCode(0x80 | ((c >> 0) & 0x3F));
}
}
return out;
}; utf8to16 = function (str){
var out, i, len, c; var char2,char3; out = ""; len = str.length; i = 0; while (i < len) { c = str.charCodeAt(i++); switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: out += str.charAt(i - 1); break; case 12: case 13: char2 = str.charCodeAt(i++); out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); break; case 14: char2 = str.charCodeAt(i++); char3 = str.charCodeAt(i++); out += String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)); break; } } return out;
}
this.encode = encode;
this.decode = decode;
construct();
};
window.Base32 = new Nibbler({
dataBits: 8,
codeBits: 5,
keyString: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
pad: '='
});
window.Base64 = new Nibbler({
dataBits: 8,
codeBits: 6,
keyString: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
pad: '='
}); window.JSON = new function(){
var useHasOwn = !!{}.hasOwnProperty;
var pad = function(n) {
return n < 10 ? "0" + n : n;
}; var m = {
"\b": '\\b',
"\t": '\\t',
"\n": '\\n',
"\f": '\\f',
"\r": '\\r',
'"' : '\\"',
"\\": '\\\\'
}; var encodeString = function(s){
if (/["\\\x00-\x1f]/.test(s)) {
return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
var c = m[b];
if(c){
return c;
}
c = b.charCodeAt();
return "\\u00" +
Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
}) + '"';
}
return '"' + s + '"';
}; var encodeArray = function(o){
var a = ["["], b, i, l = o.length, v;
for (i = 0; i < l; i += 1) {
v = o[i];
switch (typeof v) {
case "undefined":
case "function":
case "unknown":
break;
default:
if (b) {
a.push(',');
}
a.push(v === null ? "null" : JSON.encode(v));
b = true;
}
}
a.push("]");
return a.join("");
}; var encodeDate = function(o){
return '"' + o.getFullYear() + "-" +
pad(o.getMonth() + 1) + "-" +
pad(o.getDate()) + "T" +
pad(o.getHours()) + ":" +
pad(o.getMinutes()) + ":" +
pad(o.getSeconds()) + '"';
}; this.encode = function(o){
if(typeof o == "undefined" || o === null){
return "null";
}else if(o instanceof Array){
return encodeArray(o);
}else if(o instanceof Date){
return encodeDate(o);
}else if(typeof o == "string"){
return encodeString(o);
}else if(typeof o == "number"){
return isFinite(o) ? String(o) : "null";
}else if(typeof o == "boolean"){
return String(o);
}else {
var a = ["{"], b, i, v;
for (i in o) {
if(!useHasOwn || o.hasOwnProperty(i)) {
v = o[i];
switch (typeof v) {
case "undefined":
case "function":
case "unknown":
break;
default:
if(b){
a.push(',');
}
a.push(this.encode(i), ":",
v === null ? "null" : this.encode(v));
b = true;
}
}
}
a.push("}");
return a.join("");
}
};
this.decode = function(json){
return eval("(" + json + ')');
};
};
String.space = function (len) {
var t = [], i;
for (i = 0; i < len; i++) {
t.push(' ');
}
return t.join('');
};
function format(msg) {
var text = msg.split("\n").join(" ");
var t = [];
var tab = 0;
var inString = false;
for (var i = 0, len = text.length; i < len; i++) {
var c = text.charAt(i);
if (inString && c === inString) {
if (text.charAt(i - 1) !== '\\') {
inString = false;
}
} else if (!inString && (c === '"' || c === "'")) {
inString = c;
} else if (!inString && (c === ' ' || c === "\t")) {
c = '';
} else if (!inString && c === ':') {
c += ' ';
} else if (!inString && c === ',') {
c += "\n" + String.space(tab * 2);
} else if (!inString && (c === '[' || c === '{')) {
tab++;
c += "\n" + String.space(tab * 2);
} else if (!inString && (c === ']' || c === '}')) {
tab--;
c = "\n" + String.space(tab * 2) + c;
}
t.push(c);
}
$("#resp").val(t.join(''));
};
function getRemoveWhiteSpace(msg) {
var text = msg.split("\n").join(" ");
var t = [];
var inString = false;
for (var i = 0, len = text.length; i < len; i++) {
var c = text.charAt(i);
if (inString && c === inString) {
// TODO: \\"
if (text.charAt(i - 1) !== '\\') {
inString = false;
}
} else if (!inString && (c === '"' || c === "'")) {
inString = c;
} else if (!inString && (c === ' ' || c === "\t")) {
c = '';
}
t.push(c);
}
$("#resp").val(t.join(''));
};
$(document).ready(function(){
// $("#reqMethod").change(function(e){
// if("GET"==$("#reqMethod").val()){
// $("#paramDiv").hide();
// }else{
// $("#paramDiv").show();
// }
// }).change();
$("#sub").click(function(e){
var paramData=null;
// if("POST"==$("#reqMethod").val()){
if(null!=$("#reqParam").val() && $("#reqParam").val().length>=2){
paramData=Base64.encode($("#reqParam").val());
}
// };
$.ajax({
url:$("#reqUrl").val(),
type:$("#reqMethod").val(),
dataType:"text",
data:paramData,
success:function(msg){
$("#resp").val(msg);
},
error:function(XMLHttpRequest, textStatus, errorThrown){
$("#resp").val("请求有误");
}
});
});
$("#decode").click(function(e){
$("#resp").val(Base64.decode($("#resp").val()));
});
$("#encode").click(function(e){
$("#resp").val(Base64.encode($("#resp").val()));
});
$("#format").click(function(e){
format($("#resp").val());
});
$("#removeWhite").click(function(e){
getRemoveWhiteSpace($("#resp").val());
});
$("#clearLeft").click(function(e){
$("#reqUrl").val("");
$("#reqParam").val("");
});
$("#clearRight").click(function(e){
$("#resp").val("");
});
   });
</script>
</head>
<body bossAnalyOpType="add">
<div style="float: left; padding-top: 20px;">
<span>url:</span></br><textarea type="text" style="width: 450px; height: 150px;" id="reqUrl"></textarea></br>
</br> <span>方式:</span><select id="reqMethod"><option value="GET"
selected="true">GET</option>
<option value="POST">POST</option></select></br>
</br>
<div id="paramDiv">
<div>参数:</div>
<textarea id="reqParam" style="width: 450px; height: 150px;"
placeholder="编码前的参数"></textarea>
</div>
</div>
<div style="float: left; padding-left: 50px; padding-top: 80px;">
<button id="clearLeft" value="清空左侧">清空左侧</button></br></br>
<button id="clearRight" value="清空右侧">清空右侧</button></br></br>
<button id="sub" value="提交">提交</button>
</div>
<div style="float: left; padding-left: 50px;">
<span>返回结果:</span></br>
<div>
<textarea id="resp" style="width: 500px; height: 400px;"></textarea>
</br>
<button id="decode">base64解码</button>
<button id="encode">base64编码</button>
<button id="format">
JSON格式化
</buttion>
<button id="removeWhite">
JSON反格式化
</buttion>
<div></div>
</body>
</html>

node_nibbler:自定义Base32/base64 encode/decode库的更多相关文章

  1. Base64 encode/decode large file

    转载:http://www.cnblogs.com/jzywh/archive/2008/04/20/base64_encode_large_file.html The class System.Co ...

  2. javascript base64 encode decode 支持中文

    * 字符编码 ** 一定要知道数据的字符编码 ** 使用utf-8字符编码存储数据 ** 使用utf-8字符编码输出数据 * Crypto.js 支持中文 Base64编码说明 Base64编码要求把 ...

  3. BASE64 Encode Decode

    package com.humi.encryption; import java.io.IOException; import java.io.UnsupportedEncodingException ...

  4. java URLEncoder 和Base64.encode()

    参考: http://www.360doc.com/content/10/1103/12/1485725_66213001.shtml (URLEncode) http://blog.csdn.net ...

  5. python中文处理之encode/decode函数

    python中文处理相信迷惑过不少同学.下面说说python2/3的encode和decode函数. python2中,使用decode()和encode()来进行解码和编码,以unicode类型作为 ...

  6. python编码问题之\"encode\"&\"decode\"

    python encode decode 编码 decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换 ...

  7. python编码encode decode(解惑)

    关于python 字符串编码一直没有搞清楚,今天总结了一下. Python 字符串类型 Python有两种字符串类型:str 与 unicode. 字符串实例 # -*- coding: utf-8 ...

  8. (转)Integrating Intel® Media SDK with FFmpeg for mux/demuxing and audio encode/decode usages 1

    Download Article and Source Code Download Integrating Intel® Media SDK with FFmpeg for mux/demuxing ...

  9. python3.3 unicode(encode&decode)

    最近在用python写多语言的一个插件时,涉及到python3.x中的unicode和编码操作,本文就是针对编码问题研究的汇总,目前已开源至github.以下内容来自项目中的README. 1 ASC ...

随机推荐

  1. 读javascript高级程序设计04-canvas

    一.基本用法 1.要使用canvas元素,需要先给定其width和height来设置绘图区域的大小.canvas中间的文本会在浏览器不支持canvas的情况下显示出来. <canvas widt ...

  2. net中序列化读写xml

    参考http://www.cnblogs.com/fish-li/archive/2013/05/05/3061816.html 我们可以直接使用XmlTextReader.XmlDocument.X ...

  3. 交换机的端口状态是UP,但是查询该端口下的MAC地址为空

    (电脑已关机)电脑与交换机直连的端口状态 还是 UP ,但是 查询该端口下的 MAC地址为空. 初步怀疑原因: Wake-on-LAN(电脑关机,网卡还在工作) Wake-On-LAN简称WOL,是一 ...

  4. WCF初探-16:WCF数据协定之基础知识

    数据协定概念 “数据协定”是在服务与客户端之间达成的正式协议,用于以抽象方式描述要交换的数据. 也就是说,为了进行通信,客户端和服务不必共享相同的类型,而只需共享相同的数据协定. 数据协定为每一个做数 ...

  5. SqlServer索引及优化详解

    实际上,您可以把索引理解为一种特殊的目录.微软的SQL SERVER提供了两种索引:聚集索引(clustered index,也称聚类索引.簇集索引)和非聚集索引(nonclustered index ...

  6. 初始化脚本(Os_Init_Optimization.sh)

    #!/bin/bash #解压缩startup.tar.gz包 cd /tmp && tar -zxf startup.tar.gz #初始化YUM源 rm -rf /etc/yum. ...

  7. 团队开发——冲刺1.b

    冲刺阶段一(第二天) 1.昨天做了什么? 在了解C#的基础上,深入熟悉Windows窗体应用程序,熟练掌握基本功能 2.今天准备做什么? 在C#的Windows窗体应用程序中,设计简单的游戏开始主界面 ...

  8. Android 学习第7课,java android project 项目文档结构

    src: 主要存放java源文件 gen:用于存放由开发工具自动生成的内容 R.java(很重要),用于登记各种资源的ID,编译器在你放入资源于自动生成的,程序员不需要自己去修改,是不能自己修改的 往 ...

  9. ubuntu 调整桌面图标大小

    打开文件浏览器,例如从“位置” 里打开 “主文件夹”,点 “编辑” –>“首选项”,把 “图标视图默认值” 下的“默认缩放级别” 改为 75%.现在图标大小跟WinXP 下的差不多. 或者 在 ...

  10. iOS AudioQueue机制的延迟问题探究

    关键字:VOIP,AudioUnit,AudioQueue,RemoteIO问题描述VOIP通话,iOS底层音频方式采用AudioUnit机制,本来也挺好,但是会有遇到CS域来电时RemoteIO挂死 ...