简单使用 RSACryptoServiceProvider KeyPassword 失败

发布于 2024-08-14 12:14:16 字数 435 浏览 2 评论 0原文

我想用密码保护我的 RSA 私钥(谁不会),但以下 C# 失败:

SecureString pw = new SecureString();
pw.AppendChar('x');
CspParameters prms = new CspParameters();
prms.KeyPassword = pw;
RSACryptoServiceProvider crypto = new RSACryptoServiceProvider(prms);
byte[] encrypted = crypto.Encrypt(Encoding.ASCII.GetBytes("encryptme"), true);

...出现 CryptographicException:“指定的类型无效”。如果我去掉 KeyPassword 分配,它就可以正常工作。

我或微软做错了什么?

I want to protect my RSA private key with a password (who wouldn't) but the following C# fails:

SecureString pw = new SecureString();
pw.AppendChar('x');
CspParameters prms = new CspParameters();
prms.KeyPassword = pw;
RSACryptoServiceProvider crypto = new RSACryptoServiceProvider(prms);
byte[] encrypted = crypto.Encrypt(Encoding.ASCII.GetBytes("encryptme"), true);

...with the CryptographicException: "Invalid type specified". If I take the KeyPassword assignment out it works fine.

What am I, or Microsoft, doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花开柳相依 2024-08-21 12:14:16

设置 CspParameters.KeyPassword 相当于使用 PP_KEYEXCHANGE_PIN(或 PP_SIGNATURE_PIN)调用 CryptSetProvParam。默认的 Microsoft 加密服务提供商不支持此标志(它旨在与基于智能卡的 CSP 一起使用)。

您可能想尝试设置

prms.Flags = CspProviderFlags.UseUserProtectedKey;

或生成非持久密钥对,将其导出并使用自己从密码派生的密钥对其进行加密。

Setting CspParameters.KeyPassword is equivalent to calling CryptSetProvParam with PP_KEYEXCHANGE_PIN (or PP_SIGNATURE_PIN). This flag is not supported by the default Microsoft crypto-service-provider (it is intended for use with smartcard-based CSPs).

You might want to try setting

prms.Flags = CspProviderFlags.UseUserProtectedKey;

or alternatively generating a non-persistent key-pair, exporting it and encrypting it with a key derived from a password yourself.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文