简体   繁体   English

.NET 5 加密签名异常 密钥不存在

[英].NET 5 Cryptographic Signatures exception Key does not exist

I've implemented Digital Signature verification as per msdn verifying-signatures我已经按照msdn verifying-signatures实现了数字签名验证

Please don't let the fact it is in f# detract from the problem.请不要让它在 f# 中的事实影响问题。 I'm using the standard cryptography libraries from the .NET 5 framework我正在使用 .NET 5 框架中的标准密码库

module GenericCryptography =
  let createRsa (res: GenericPublicKey) =
    let rsa = RSA.Create()

    // create params
    let mutable rsaParams = RSAParameters()
    rsaParams.Modulus <- res.Modulus
    rsaParams.Exponent <- res.Exponent

    rsa.ImportParameters(rsaParams)

    // export final RSA class
    rsa

  let rsaFormatter = 
    let r = RSAPKCS1SignatureFormatter(rsa)
    r.SetHashAlgorithm("SHA1") |> ignore
    r
  let rsaDeformatter = 
    let r = RSAPKCS1SignatureDeformatter(rsa)
    r.SetHashAlgorithm("SHA1") |> ignore
    r
  let sha1 = 
    let crytProv = new SHA1CryptoServiceProvider()
    crytProv.Initialize()
    crytProv

  let encrypt (data: byte[]) = 
    let hash = sha1.ComputeHash(data)
    rsaFormatter.CreateSignature(hash)

  let verify (data: byte[]) (signature: byte[]) = 
    let hash = sha1.ComputeHash(data)
    rsaDeformatter.VerifySignature(hash, signature)

The encrypt & verify method is used like so encryptverify方法是这样使用的

let signature = GenericCryptography.encrypt (message |> Helpers.getUTF8Bytes)
let encryptedMessage = GenericCryptography.encrypt (message |> Helpers.getUTF8Bytes)
let verifiedSignature = GenericCryptography.verify encryptedMessage signature 

This fails with这失败了

Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: Key does not exist. Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException:密钥不存在。

This isn't mentioned in the docs for verifying... I'm not sure why I'm getting that - I know I import the public key, and has something to do with that, but what is the question验证文档中没有提到这一点......我不确定我为什么会得到这个 - 我知道我导入了公钥,并且与此有关,但问题是什么


To repro, just do var rsa = RSA.Create() and do rsa.ExportParameters(false) , this will return you a structure where you can get the Modulus and Exponent from to pass to the createRsa function要重现,只需执行var rsa = RSA.Create()并执行rsa.ExportParameters(false) ,这将返回一个结构,您可以从中获取ModulusExponent以传递给createRsa function


Further Analysis进一步的分析

This happens on this line:这发生在这一行:

let encrypt (data: byte[]) = 
  let hash = sha1.ComputeHash(data)
  rsaFormatter.CreateSignature(hash) //<-- this line

The issue as stated in the comments, is that when importing the RSA Parameters, only the public key was set, and in order encrypt it would need private key as well.评论中指出的问题是,在导入 RSA 参数时,只设置了公钥,为了加密它还需要私钥。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM