C# 使用 RSA 加密算法生成证书签名产生“The system cannot find the file specified”异常

使用 C# 中 RSA(System.Security.Cryptography.RSA) 加密算法生成证书签名进行身份验证,在 VS2022 开发工具本地运行应用程序一切正常。

但将应用程序部署到远程服务器(如:Azure App Services),生成签名时产生如下错误信息:

cs 复制代码
System.Security.Cryptography.CryptographicException: The system cannot find the file specified.
   at System.Security.Cryptography.CngKey.Import(ReadOnlySpan`1 keyBlob, String curveName, CngKeyBlobFormat format, CngProvider provider)
   at System.Security.Cryptography.CngPkcs8.ImportPkcs8(ReadOnlySpan`1 keyBlob)
   at System.Security.Cryptography.CngPkcs8.ImportPkcs8PrivateKey(ReadOnlySpan`1 source, Int32& bytesRead)
   at System.Security.Cryptography.RSACng.ImportPkcs8PrivateKey(ReadOnlySpan`1 source, Int32& bytesRead)

这很可能是因为 Cryptographic Service 提供程序试图在用户存储区中存储或加载证书的密钥,并且由于配置文件不可用,因此加密上下文不可用。

由于应用程序服务(Azure App Serivces)默认没有开启加载用户配置文件设定。

解决上述问题:

可在Azure应用程序服务 >> 配置 >> Application settings,增加 WEBSITE_LOAD_USER_PROFILE = 1 的应用配置信息即可。

若应用程序部署在 Windows IIS 服务器上,则可以在应用程序池开启"加载用户配置文件"设定即可,设定步骤如下:

  1. 打开IIS管理器。
  2. 进入应用程序池管理页面,点选中要设定的应用程序池。
  3. 在右边"操作"模块下点击"高级设置..."或鼠标右键选择"高级设置..."。
  4. 在"进程模型(Process Model)"节点,将"加载用户配置文件(Load User Profile) "设为 True,如下截图:
相关推荐
故事和你9141 分钟前
洛谷-数据结构1-1-线性表1
开发语言·数据结构·c++·算法·leetcode·动态规划·图论
石榴树下的七彩鱼1 小时前
图片修复 API 接入实战:网站如何自动去除图片水印(Python / PHP / C# 示例)
图像处理·后端·python·c#·php·api·图片去水印
techdashen2 小时前
Rust项目公开征测:Cargo 构建目录新布局方案
开发语言·后端·rust
星空椰2 小时前
JavaScript 进阶基础:函数、作用域与常用技巧总结
开发语言·前端·javascript
忒可君2 小时前
C# winform 自制分页功能
android·开发语言·c#
Rust研习社2 小时前
Rust 智能指针 Cell 与 RefCell 的内部可变性
开发语言·后端·rust
南無忘码至尊2 小时前
Unity学习90天 - 第 6天 - 学习协程 Coroutine并实现每隔 2 秒生成一波敌人
学习·unity·c#·游戏引擎
leaves falling3 小时前
C++模板进阶
开发语言·c++
坐吃山猪3 小时前
Python27_协程游戏理解
开发语言·python·游戏
gCode Teacher 格码致知3 小时前
Javascript提高:小数精度和随机数-由Deepseek产生
开发语言·javascript·ecmascript