JavaScript中的64位加密及解密

作者:seasun 来源:我想网 时间:2009-12-23 19:10:00 

JavaScript中的64位加密及解密的两个方法。

function base64Encode(text){
if (/([^\u0000-\u00ff])/.test(text)){
throw new Error(”Can’t base64 encode non-ASCII characters.”);
}
var digits = “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/”,
i = 0,
cur, prev, byteNum,
result=[];
while(i < text.length){
cur = text.charCodeAt(i);
byteNum = i % 3;
switch(byteNum){
case 0: //first byte
result.push(digits.charAt(cur >> 2));
break;
case 1: //second byte
result.push(digits.charAt((prev & 3) << 4 | (cur >> 4)));
break;
case 2: //third byte
result.push(digits.charAt((prev & 0×0f) << 2 | (cur >> 6)));
result.push(digits.charAt(cur & 0×3f));
break;
}
prev = cur;
i++;
}
if (byteNum == 0){
result.push(digits.charAt((prev & 3) << 4));
result.push(”==”);
} else if (byteNum == 1){
result.push(digits.charAt((prev & 0×0f) << 2));
result.push(”=”);
}
return result.join(”");
}
function base64Decode(text){
text = text.replace(/\s/g,”");
if(!(/^[a-z0-9\+\/\s]+\={0,2}$/i.test(text)) || text.length % 4 > 0){
throw new Error(”Not a base64-encoded string.”);
}
//local variables
var digits = “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/”,
cur, prev, digitNum,
i=0,
result = [];
text = text.replace(/=/g, “”);
while(i < text.length){
cur = digits.indexOf(text.charAt(i));
digitNum = i % 4;
switch(digitNum){
//case 0: first digit – do nothing, not enough info to work with
case 1: //second digit
result.push(String.fromCharCode(prev << 2 | cur >> 4));
break;
case 2: //third digit
result.push(String.fromCharCode((prev & 0×0f) << 4 | cur >> 2));
break;
case 3: //fourth digit
result.push(String.fromCharCode((prev & 3) << 6 | cur));
break;
}
prev = cur;
i++;
}
return result.join(”");
}

标签:加密,解密,JavaScript
0
投稿

猜你喜欢

  • 使用javascript修复浏览器中12个常见而又头痛的问题

    2008-10-28 19:38:00
  • 一文读懂Python 枚举

    2023-02-16 16:12:46
  • Python K最近邻从原理到实现的方法

    2022-10-13 09:41:45
  • 深入分析在Python模块顶层运行的代码引起的一个Bug

    2021-06-29 01:26:29
  • Python中的getopt函数使用详解

    2023-04-07 03:08:00
  • Python实战之实现简单的名片管理系统

    2023-07-18 06:48:02
  • Python实现问题回答小游戏

    2023-05-13 13:26:19
  • python字典快速保存于读取的方法

    2022-02-18 02:22:11
  • 详解pandas数据合并与重塑(pd.concat篇)

    2023-06-02 00:05:37
  • 常用SQL语句优化技巧总结【经典】

    2024-01-20 19:27:03
  • asp将table生成excel文件(xls)

    2011-03-07 11:17:00
  • 利用Python实现命令行版的火车票查看器

    2021-10-24 13:59:21
  • Python 闭包,函数分隔作用域,nonlocal声明非局部变量操作示例

    2023-07-29 00:03:51
  • python实现汉诺塔算法

    2022-11-11 04:57:51
  • Python列表的定义及使用

    2023-08-02 03:38:32
  • Python删除列表中重复元素的七种方法举例

    2021-08-16 06:10:15
  • pytorch绘制曲线的方法

    2022-09-03 06:43:54
  • Python数据结构之队列详解

    2023-11-17 14:04:34
  • 通过优化CSS代码 减小对系统资源的占用

    2010-08-03 12:33:00
  • Thinkphp5.0 框架使用模型Model添加、更新、删除数据操作详解

    2024-06-07 15:35:37
  • asp之家 网络编程 m.aspxhome.com