Home >Web Front-end >JS Tutorial >NodeJS implements client js encryption

NodeJS implements client js encryption

高洛峰
高洛峰Original
2017-01-10 09:22:471172browse

Idea:

Server-side rendering business code js =>

The front-end and back-end agreed encryption algorithms=>

Business code for signature=>

Client decryption business code=>

eval Execute

Node routing example:

/**
 * 请自定义 restful API 这里以 GET 为例
 * @param {req}
 * @param {res}
 * @return {next()}
 */
//var util = require('utility');
exports.encryption = function(req, res){
 //GET
 var name = req.query.name
 , jsStr // 用于 服务端渲染的 js 脚本
 , doc = {
  n : '支持请求参数',
 };
 // isSafe : 常规安全字符判断
 if (fun.isSafe(name)) doc['n'] = name;
 /////////////////需要加密的js 业务代码 start///////////////////// 
 jsStr = function(n){
 alert('开始执行业务代码~')
 // 变量 N 可以是某些 之前需要 服务端渲染的 信息
 // 比如 自产 的 url 之类
 function sayHello(s){
  alert('您输入了: '+s);
 }
 sayHello(n);
 //
 }
 //////////////////需要加密的js 业务代码 end//////////////////// 
 jsStr = '('+jsStr.toString()+')("'+( name ? doc.n : '默认的')+'")';
 var key = util.md5('highsea90'+Date.now())
 var resStr = myFromCharCode(key, jsStr);
 res.render('cm/eval',{
 title : 'js 加密 demo',
 charCode : escape(myFromCharCode.toString()),
 data : escape(resStr),
 key : key
 })
};
 /**
 * @param {m}密钥
 * @param {text}文本
 * @return {last}加密文本
 */
 function myFromCharCode (m, text){
 var last = '';
 for (var i = 0 , l = text.length; i < l; i++) {
  for (var j = 0, k = m.length; j < k; j++) {
  var key = m.charCodeAt(j)
   , text2 = text.charCodeAt(i) ^ key
  }
  last += String.fromCharCode(text2);
 }
 return last;
 }

Client page example:

<!DOCTYPE html>
<html>
<head>
 <title><%=title%></title>
</head>
<body>
<script type="text/javascript">
 // 执行 约定的 加密算法
 eval(unescape("<%=charCode%>"));
 // 服务端加密后的 字符串 用约定的 算法进行解密
 var str = myFromCharCode("<%=key%>", unescape("<%=data%>"));
 // 执行业务代码
 eval(str);
</script>
</body>
</html>

Code demonstration

A short video:

NodeJS implements client js encryption

The above is the entire content of this article. I hope that the content of this article can bring some help to everyone's study or work. At the same time I also hope to support the PHP Chinese website!

For more articles related to NodeJS implementing client js encryption, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn