简体   繁体   中英

.NET 5 Cryptographic Signatures exception Key does not exist

I've implemented Digital Signature verification as per msdn verifying-signatures

Please don't let the fact it is in f# detract from the problem. I'm using the standard cryptography libraries from the .NET 5 framework

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

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.

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


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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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