2D JS框架 - DES加密解密 与 Cookie的封装(C#与js互相加密解密)
这次实现了JS端的DES加密与解密,并且C#端也能正确解析DES的密文(反之也实现了)
使用的代码如下,非常方便:
<script src="A2D.js" type="text/javascript"></script> <script language="javascript" type="text/javascript"> var msg = $.DES.encrypt("要研究mysql,最好的资源莫过于源码了,所以本人打算通过调试源码的方式来深入理解mysql的点点滴滴。"); document.writeln(msg); document.writeln("<br />"); document.writeln($.DES.decrypt(msg)); </script>
输出内容:
385bdba36c0e65dee2ab7fc31fbf7ec43566195c29bf18e4722421397cbbf17a665843bd245226bf8947b59d1609837662b149fb025175d9f76dd9710b165c12c0763ca6d0dd549d8b2b9a2fb6f9a3ffaea19281d92eb84972ad3394198bd5ccb0bfb3be071ff32b <br /> 要研究mysql,最好的资源莫过于源码了,所以本人打算通过调试源码的方式来深入理解mysql的点点滴滴。
C#服务器端使用了js沙箱来运行A2D.js代码,因此能做到加密解密的一致性,如下:
public static class JSSecurity { public class MockWindow { } public class MockDocument { } public static string MainJSPath { get; set; } static MockWindow wnd = new MockWindow(); static MockDocument doc = new MockDocument(); public static string Encode(string plainText) { using (JavascriptContext context = new JavascriptContext()) { context.SetParameter("window", wnd); context.SetParameter("document", doc); context.SetParameter("message", plainText); string js = File.ReadAllText(MainJSPath); js += @" result = window.$.DES.encrypt(message); "; context.Run(js); string result = (string)context.GetParameter("result"); return result; } } public static string Decode(string encryptedText) { using (JavascriptContext context = new JavascriptContext()) { context.SetParameter("window", wnd); context.SetParameter("document", doc); context.SetParameter("encryptedMessage", encryptedText); string js = File.ReadAllText(MainJSPath); js += @" result = window.$.DES.decrypt(encryptedMessage); "; context.Run(js); string result = (string)context.GetParameter("result"); return result; } } }
真的很简单。
下面来看看Cookie的使用,加密了的,不是明文的,并且服务器端能够正确解析:
<form action="WebForm1.aspx" method="post"> <input type="button" onclick="javascript:onSetCookie();" value="set cookie(js des encrypt)" /> <br /> <input type="submit" value="Post" /> </form> <script language="javascript" type="text/javascript"> function onSetCookie() { $.Cookie.set("账号ID", "aaron.dai"); alert($.Cookie.get("账号ID")); } </script>
当click按钮后,设置cookie;点Post按钮后,submit到webform1.aspx,让C#来解析cookie的明文:
protected void Page_Load(object sender, EventArgs e) { global::A2D.JSSecurity.MainJSPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "A2D\\A2D.js"); foreach(string key in Request.Cookies.AllKeys) { Response.Write("key:"+key); Response.Write("<br />value:" + Request.Cookies[key].Value); Response.Write("<br />=====><br />"); Response.Write("key:" + global::A2D.JSSecurity.Decode(key)); Response.Write("<br />value:" + global::A2D.JSSecurity.Decode(Request.Cookies[key].Value)); } }
just so easy.
code download