当前位置: 首页 > web >正文

Microsoft.ClearScript.V8单例模式封装,方便下次使用。

C#调用js还是没有python方便,但是微软出的V8算是目前最全的JS引擎了,完整的模拟了浏览器环境。并且支持js和C#双向通信。

下面是单例代码,可以直接调用。

using Microsoft.ClearScript;
using Microsoft.ClearScript.V8;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;public sealed class SM2CryptoService : IDisposable
{private static readonly Lazy<SM2CryptoService> _lazyInstance =new Lazy<SM2CryptoService>(() => new SM2CryptoService(), LazyThreadSafetyMode.ExecutionAndPublication);public static SM2CryptoService Instance => _lazyInstance.Value;private const V8ScriptEngineFlags EngineFlags =V8ScriptEngineFlags.EnableTaskPromiseConversion |V8ScriptEngineFlags.EnableDateTimeConversion |V8ScriptEngineFlags.DisableGlobalMembers;private static readonly TimeSpan FileReadRetryDelay = TimeSpan.FromMilliseconds(100);private const int MaxFileReadRetries = 3;private readonly V8ScriptEngine _jsEngine;private bool _disposed;private readonly object _engineLock = new();private SM2CryptoService(){try{string jsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"Areas", "GZ_RideAuth", "Js", "sm2.js");LogInfo($"初始化SM2服务,JS路径: {jsPath}");if (!File.Exists(jsPath))throw new FileNotFoundException("SM2加密库文件未找到", jsPath);string jsCode = ReadJsFileWithRetry(jsPath, MaxFileReadRetries);_jsEngine = new V8ScriptEngine("SM2Engine", EngineFlags){AllowReflection = false,MaxRuntimeHeapSize = 1024 * 1024 * 1024 // 20MB内存限制};_jsEngine.Execute(jsCode);LogInfo("服务初始化成功");}catch (Exception ex){LogError("初始化致命错误", ex);Dispose();throw new CryptographicException("SM2加密服务初始化失败", ex);}}public string Encrypt(string plainText){if (_disposed)throw new ObjectDisposedException(GetType().FullName);if (string.IsNullOrWhiteSpace(plainText))return string.Empty;lock (_engineLock){var sw = Stopwatch.StartNew();try{var result = _jsEngine.Script.window.SM2.sm2Encrypt(plainText);string cipherText = result.ToString();LogInfo($"加密完成,耗时: {sw.ElapsedMilliseconds}ms");return cipherText;}catch (ScriptEngineException ex){LogError("JS执行错误", ex);throw new CryptographicException("SM2加密过程出错", ex);}catch (Exception ex){LogError("系统错误", ex);throw;}}}public void Dispose(){if (_disposed) return;lock (_engineLock){if (_disposed) return;try{_jsEngine?.Execute("window.SM2.cleanup && window.SM2.cleanup()");_jsEngine?.Dispose();LogInfo("V8引擎已释放");}catch (Exception ex){LogError("资源释放异常", ex);}finally{_disposed = true;GC.SuppressFinalize(this);}}}~SM2CryptoService() => Dispose();private string ReadJsFileWithRetry(string path, int maxRetries){for (int i = 0; i < maxRetries; i++){try{string content = File.ReadAllText(path, Encoding.UTF8);if (string.IsNullOrWhiteSpace(content))throw new InvalidDataException("JS文件内容为空");return content;}catch (IOException) when (i < maxRetries - 1){Thread.Sleep(FileReadRetryDelay * (i + 1));}}throw new IOException($"读取JS文件失败,已重试{maxRetries}次");}private void LogInfo(string message) =>Debug.WriteLine($"[{DateTime.UtcNow:u}] [SM2] [INFO] {message}");private void LogError(string message, Exception ex = null) =>Debug.WriteLine($"[{DateTime.UtcNow:u}] [SM2] [ERROR] {message}{(ex != null ? $"\n{ex}" : "")}");
}

注意:
1.先使用_jsEngine.Execute(jsCode);把JS脚本加载进入v8引擎
2.使用_jsEngine.Script.window.SM2.sm2Encrypt(plainText);进行调用,其中window.SM2.sm2Encrypt(plainText)这部分是我JS中的方法,我挂载在window上面。_jsEngine.Script这部分就是js环境,理解成浏览器的控制台,你后半部分就像你平时浏览器控制台中调用网页中的方法一样操作。

http://www.xdnf.cn/news/8661.html

相关文章:

  • Android12 launcher3修改App图标白边问题
  • Linux命令简介
  • 过滤器和拦截器的区别
  • web常见的攻击方式有哪些?如何防御?
  • 防止误触的手机锁屏实用工具
  • 跨平台兼容Setup PDF 编辑器页面合并拆分OCR 识别支持多语言
  • Jenkins的Pipline中有哪些区块,以及其它知识点整理
  • 【 大模型技术驱动智能网联汽车革命:关键技术解析与未来趋势】
  • 安全基础与协议分析
  • 静态分配动态绑定
  • 数据的获取与读取篇---常见的数据格式JSON
  • 一张纸决定的高度
  • 数据透视表和公式法在Excel中实现去除重复计数的方法
  • 大数据治理:理论、实践与未来展望(二)
  • 稳固基石 - Prometheus 与 Alertmanager 运维考量
  • 探索产品经理的MVP:从概念到实践
  • 信息安全管理与评估2025上海卷
  • 在UniApp中开发微信小程序实现图片、音频和视频下载功能
  • C++单例模式
  • Spring boot和SSM项目对比
  • Sqlserver-数据库的事务日志已满,原因为“LOG_BACKUP”。
  • 转移dp简单数学数论
  • SAP全面转向AI战略,S/4HANA悄然隐身
  • 【笔记】为 Miniconda 安装图形界面的方法
  • 微服务架构实战:Eureka服务注册发现与Ribbon负载均衡详解
  • Day126 | 灵神 | 二叉树 | 层数最深的叶子结点的和
  • 第2章 数据库设计
  • 多场景游戏AI新突破!Divide-Fuse-Conquer如何激发大模型“顿悟时刻“?
  • JAVA网络编程——socket套接字的介绍上(详细)
  • uniapp+ts 多环境编译