原文链接:https://www.cnblogs.com/Ehtan/p/4361986.html#undefined
添加COM引用: Microsoft Script Control 1.0
1、添加帮助类
using MSScriptControl; using System; using System.IO; namespace Javascript { /// <summary> /// JavascriptHelper /// </summary> public class JavascriptHelper { /// <summary> /// ScriptControl /// </summary> private ScriptControl jsControl = null; /// <summary> /// 构造方法 /// </summary> public JavascriptHelper() { this.jsControl = new ScriptControl(); this.jsControl.UseSafeSubset = true; this.jsControl.Language = "JScript"; } /// <summary> /// 添加js文件 /// </summary> /// <param name="filePath">js文件路径</param> public void AddJavaScriptFile(string filePath) { if (!File.Exists(filePath)) { throw new Exception("文件" + filePath + "不存在。"); } string jsCode = File.ReadAllText(filePath); this.jsControl.AddCode(jsCode); } /// <summary> /// 添加js代码 /// </summary> /// <param name="jsCode">js代码</param> public void AddJavascriptCode(string jsCode) { this.jsControl.AddCode(jsCode); } /// <summary> /// 执行js /// </summary> /// <param name="method">方法名</param> /// <returns>结果</returns> public dynamic Excecute(string method) { return this.jsControl.Eval(method); } } }
2、测试代码
using System; using System.IO; namespace Javascript { public class Program { public static void Main(string[] args) { string plantext = "123456"; string ciphertext = Rsa(plantext); Console.WriteLine(ciphertext); Console.ReadLine(); } /// <summary> /// rsa加密算法 /// </summary> /// <param name="plantext">明文</param> /// <returns>密文</returns> private static string Rsa(string plantext) { JavascriptHelper jsHelper = new JavascriptHelper(); AddJSFile(jsHelper); string method = string.Format("encrypt('{0}');", plantext); string ciphertext = jsHelper.Excecute(method).ToString(); return ciphertext; } /// <summary> /// 添加js文件 /// </summary> /// <param name="jsHelper">JavascriptHelper</param> private static void AddJSFile(JavascriptHelper jsHelper) { string path = string.Empty; path = AppDomain.CurrentDomain.BaseDirectory + @"jssecurity.js"; jsHelper.AddJavaScriptFile(path); path = AppDomain.CurrentDomain.BaseDirectory + @"js sa.js"; jsHelper.AddJavaScriptFile(path); } } }