我正在尝试了解有关 RSA 如何在 .NET 中运行的更多信息,并发现了这篇有用的帖子,该帖子表明默认情况下 key 存储在 Windows 中: https://stackoverflow.com/a/5845191/1181412
我的问题引用了下面的示例代码。假设目的是仅在应用程序 session 的生命周期内生成一次性 key 。
问题 1:在下面的结构中,每次在类中的任何位置创建 RSACryptoServiceProvider 时,是否都需要将 PersistKeyInCsp 标志设置为 false,即使它正在访问同一个 CspParameters 对象?
问题 2:在 CspParameters 对象上设置 CreateEphemeralKey 标志是否取代了在此示例中使用 PersistKeyInCsp 的需要?
Public Class RSACrypto
Private RSAKey As CspParameters
Public Sub New(KeySize As Integer)
MyBase.New()
RSAKey = New CspParameters
Using RSA As New RSACryptoServiceProvider(KeySize, RSAKey)
RSA.PersistKeyInCsp = False
End Using
End Sub
Public Function PublicKey() As Byte()
Using RSA As New RSACryptoServiceProvider(RSAKey)
RSA.PersistKeyInCsp = False
Return RSA.ExportCspBlob(False)
End Using
End Function
End Class
最佳答案
如果您在 CspParameters 结构中将 key 容器名称保留为 null
(并且您不断言 UseDefaultKeyContainer
).
对于使用 CreateEphemeralKey
(或隐式地通过 null
名称)创建的 key ,PersistKeyInCsp
属性没有任何意义或作用。对于命名(持久化)键,当对象被处置或完成时,它会导致键从磁盘中删除。 (请注意,异常终止意味着 key 永远不会被删除)
Question 1: In the below structure, does the PersistKeyInCsp flag need to be set to false every time an RSACryptoServiceProvider is created anywhere within the class even if it is accessing the same CspParameters object?
如果 key 被保留,那么您第一次设置 PersistKeyInCsp=false
并调用 Dispose()
(直接或通过 using
语句),或者让 key 被垃圾收集并最终确定,那么后续访问要么失败,要么创建一个不同的 key (取决于是否声明了 UseExistingKey
标志)。所以,说“不,你不应该那样做”是最正确的。
Question 2: Does setting the CreateEphemeralKey flag on the CspParameters object supersede the need to use PersistKeyInCsp in this example?
是的。
隐式问题 3:为什么我的代码不起作用?
在您的构造函数中,您有以下三种行为之一,具体取决于 CspParameters.KeyContainerName
的值和系统状态:
KeyContainerName == null
:- 您创建了一个大小为
KeySize
的临时 key 。然后丢弃了它。没有人会知道您的 key 是什么。
- 您创建了一个大小为
- 指定的 key 不存在:
- 您生成了一个大小为
KeySize
的 key 对,将其保存到磁盘,然后将其删除。没有人会知道您的 key 是什么。
- 您生成了一个大小为
- 指定的 key 确实存在:
- 您打开了 key 对(
KeySize
被忽略)。然后你把它从磁盘上删除了。希望你不需要它。
- 您打开了 key 对(
在您的 PublicKey
方法中,您可以创建一个 1024 位的临时 key (如果 RSAKey.KeyContainerName == null
)或打开一个现有 key ,或者生成一个 1024-位 key 并将其保存到磁盘。然后导出公钥的 CAPI blob,并且(如果是临时的)丢弃 key 或(如果持久存在)将其从系统中删除。 (1024 位是因为您使用了没有键大小值的 CspParameters ctor,所以来自 ctor 的 KeySize
值是无关紧要的)
您可能想要保存的不是 CspParameters,而是实际的 RSA/RSACryptoServiceProvider 对象。
关于vb.net - .NET RSA CreateEphemeralKey 与 PersistKeyInCsp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13486715/