Import a Public key from somewhere else to CngKey?

前端 未结 4 603
面向向阳花
面向向阳花 2020-11-29 06:31

I am looking for a cross platform way to share public keys for ECDSA signing. I had a great thing going from a performance perspective with CngKey and the standard .NET cry

4条回答
  •  春和景丽
    2020-11-29 07:08

    Thanks to you I was able to import a ECDSA_P256 public key from a certificate with this code:

        private static CngKey ImportCngKeyFromCertificate(X509Certificate2 cert)
        {
            var keyType = new byte[] {0x45, 0x43, 0x53, 0x31};
            var keyLength = new byte[] {0x20, 0x00, 0x00, 0x00};
    
            var key = cert.PublicKey.EncodedKeyValue.RawData.Skip(1);
    
            var keyImport = keyType.Concat(keyLength).Concat(key).ToArray();
    
            var cngKey = CngKey.Import(keyImport, CngKeyBlobFormat.EccPublicBlob);
            return cngKey;
        }
    

    The 65 byte keys (public key only) start with 0x04 which needs to be removed. Then the header you described is added.

    then I was able to verify a signature like that:

    var crypto = ECDsaCng(cngKey);
    var verify = crypto.VerifyHash(hash, sig);
    

提交回复
热议问题