/// <summary> /// Method take BCrypt handle as input and returns the CNGKey /// </summary> /// <param name="bcryptKeyHandle">Accepts BCrypt Handle</param> /// <returns>Returns CNG key with NCrypt Handle</returns> private static CngKey LegacyBCryptHandleToNCryptHandle(SafeBCryptKeyHandle bcryptKeyHandle) { byte[] keyBlob = BCryptNative.ExportBCryptKey(bcryptKeyHandle, BCryptNative.BCRYPT_ECCPUBLIC_BLOB); //Now Import the key blob as NCRYPT_KEY_HANDLE CngKey Key = CngKey.Import(keyBlob, CngKeyBlobFormat.EccPublicBlob); return(Key); }
public static ECDsa GetECDsaPublicKey(this X509Certificate2 certificate) { if (LocalAppContextSwitches.UseLegacyPublicKeyBehavior) { return(LegacyGetECDsaPublicKey(certificate)); } if (certificate == null) { throw new ArgumentNullException("certificate"); } if (!IsECDsa(certificate)) { return(null); } using (SafeCertContextHandle safeCertContext = X509Native.GetCertificateContext(certificate)) using (SafeBCryptKeyHandle bcryptKeyHandle = ImportPublicKeyInfo(safeCertContext)) { if (bcryptKeyHandle.IsInvalid) { throw new CryptographicException("SR.GetString(SR.Cryptography_OpenInvalidHandle)"); } string curveName = GetCurveName(bcryptKeyHandle); if (curveName == null) { CngKeyBlobFormat blobFormat = HasExplicitParameters(bcryptKeyHandle) ? CngKeyBlobFormat.EccFullPublicBlob : CngKeyBlobFormat.EccPublicBlob; byte[] keyBlob = BCryptNative.ExportBCryptKey(bcryptKeyHandle, blobFormat.Format); using (CngKey key = CngKey.Import(keyBlob, blobFormat)) { return(new ECDsaCng(key)); } } else { CngKeyBlobFormat blobFormat = CngKeyBlobFormat.EccPublicBlob; byte[] keyBlob = BCryptNative.ExportBCryptKey(bcryptKeyHandle, blobFormat.Format); ECParameters ecparams = new ECParameters(); ExportNamedCurveParameters(ref ecparams, keyBlob, false); ecparams.Curve = ECCurve.CreateFromFriendlyName(curveName); ECDsaCng ecdsa = new ECDsaCng(); ecdsa.ImportParameters(ecparams); return(ecdsa); } } }