原文連接:https://www.cnblogs.com/Ehtan/p/4361986.html#undefinedhtml
添加COM引用: Microsoft Script Control 1.0
算法
一、添加幫助類測試
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); } } }
二、測試代碼this
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 + @"js\security.js"; jsHelper.AddJavaScriptFile(path); path = AppDomain.CurrentDomain.BaseDirectory + @"js\rsa.js"; jsHelper.AddJavaScriptFile(path); } } }