public CngKey GetOrGenerateKey(int keySize, CngAlgorithm algorithm) { ThrowIfDisposed(); // If our key size was changed, we need to generate a new key. if (_lazyKey != null) { if (_lazyKey.KeySize != keySize) { DisposeKey(); } } // If we don't have a key yet, we need to generate one now. if (_lazyKey == null) { CngKeyCreationParameters creationParameters = new CngKeyCreationParameters() { ExportPolicy = CngExportPolicies.AllowPlaintextExport, }; CngProperty keySizeProperty = new CngProperty(KeyPropertyName.Length, BitConverter.GetBytes(keySize), CngPropertyOptions.None); creationParameters.Parameters.Add(keySizeProperty); _lazyKey = CngKey.Create(algorithm, null, creationParameters); } return(_lazyKey); }
public static CngKey Create(CngAlgorithm algorithm, string?keyName, CngKeyCreationParameters?creationParameters) { ArgumentNullException.ThrowIfNull(algorithm); creationParameters ??= new CngKeyCreationParameters(); SafeNCryptProviderHandle providerHandle = creationParameters.Provider !.OpenStorageProvider(); SafeNCryptKeyHandle keyHandle; ErrorCode errorCode = Interop.NCrypt.NCryptCreatePersistedKey(providerHandle, out keyHandle, algorithm.Algorithm, keyName, 0, creationParameters.KeyCreationOptions); if (errorCode != ErrorCode.ERROR_SUCCESS) { // For ecc, the exception may be caught and re-thrown as PlatformNotSupportedException throw errorCode.ToCryptographicException(); } InitializeKeyProperties(keyHandle, creationParameters); errorCode = Interop.NCrypt.NCryptFinalizeKey(keyHandle, 0); if (errorCode != ErrorCode.ERROR_SUCCESS) { // For ecc, the exception may be caught and re-thrown as PlatformNotSupportedException throw errorCode.ToCryptographicException(); } CngKey key = new CngKey(providerHandle, keyHandle); // No name translates to an ephemeral key if (keyName == null) { key.IsEphemeral = true; } return(key); }
public CngKey GetOrGenerateKey(int keySize, CngAlgorithm algorithm) { ThrowIfDisposed(); // If our key size was changed, we need to generate a new key. if (_lazyKey != null) { if (_lazyKey.KeySize != keySize) { DisposeKey(); } } // If we don't have a key yet, we need to generate one now. if (_lazyKey == null) { CngKeyCreationParameters creationParameters = new CngKeyCreationParameters() { ExportPolicy = CngExportPolicies.AllowPlaintextExport, }; Span <byte> keySizeBuffer = stackalloc byte[sizeof(int)]; bool success = BitConverter.TryWriteBytes(keySizeBuffer, keySize); Debug.Assert(success); CngProperty keySizeProperty = new CngProperty(KeyPropertyName.Length, keySizeBuffer, CngPropertyOptions.None); creationParameters.Parameters.Add(keySizeProperty); _lazyKey = CngKey.Create(algorithm, null, creationParameters); } return(_lazyKey); }
private CngKey GetKey() { CngKey key = null; if (_core.IsKeyGeneratedNamedCurve()) { // Curve was previously created, so use that key = _core.GetOrGenerateKey(null); } else { CngAlgorithm algorithm = null; int keySize = 0; // Map the current key size to a CNG algorithm name keySize = KeySize; switch (keySize) { case 256: algorithm = CngAlgorithm.ECDsaP256; break; case 384: algorithm = CngAlgorithm.ECDsaP384; break; case 521: algorithm = CngAlgorithm.ECDsaP521; break; default: Debug.Fail("Should not have invalid key size"); throw new ArgumentException(SR.Cryptography_InvalidKeySize); } key = _core.GetOrGenerateKey(keySize, algorithm); } return(key); }
/// <summary> /// Map a curve name to magic number. Maps the names of the curves that worked pre-Win10 /// to the pre-Win10 magic numbers to support import on pre-Win10 environments /// that don't have the named curve functionality. /// </summary> private static KeyBlobMagicNumber CurveNameToMagicNumber(string name, bool includePrivateParameters) { CngAlgorithm alg = CngKey.EcdsaCurveNameToAlgorithm(name); if (alg == CngAlgorithm.ECDsaP256) { return(includePrivateParameters ? KeyBlobMagicNumber.BCRYPT_ECDSA_PRIVATE_P256_MAGIC : KeyBlobMagicNumber.BCRYPT_ECDSA_PUBLIC_P256_MAGIC); } if (alg == CngAlgorithm.ECDsaP384) { return(includePrivateParameters ? KeyBlobMagicNumber.BCRYPT_ECDSA_PRIVATE_P384_MAGIC : KeyBlobMagicNumber.BCRYPT_ECDSA_PUBLIC_P384_MAGIC); } if (alg == CngAlgorithm.ECDsaP521) { return(includePrivateParameters ? KeyBlobMagicNumber.BCRYPT_ECDSA_PRIVATE_P521_MAGIC : KeyBlobMagicNumber.BCRYPT_ECDSA_PUBLIC_P521_MAGIC); } // all other curves are new in Win10 so use named curves return(includePrivateParameters ? KeyBlobMagicNumber.BCRYPT_ECDSA_PRIVATE_GENERIC_MAGIC : KeyBlobMagicNumber.BCRYPT_ECDSA_PUBLIC_GENERIC_MAGIC); }
/// <summary> /// Constructs the core to use a stored CNG key. /// </summary> public CngSymmetricAlgorithmCore(ICngSymmetricAlgorithm outer, string keyName, CngProvider provider, CngKeyOpenOptions openOptions) { if (keyName == null) { throw new ArgumentNullException(nameof(keyName)); } if (provider == null) { throw new ArgumentNullException(nameof(provider)); } _outer = outer; _keyName = keyName; _provider = provider; _optionOptions = openOptions; using (CngKey cngKey = ProduceCngKey()) { CngAlgorithm actualAlgorithm = cngKey.Algorithm; string algorithm = _outer.GetNCryptAlgorithmIdentifier(); if (algorithm != actualAlgorithm.Algorithm) { throw new CryptographicException(SR.Format(SR.Cryptography_CngKeyWrongAlgorithm, actualAlgorithm.Algorithm, algorithm)); } _outer.BaseKeySize = cngKey.KeySize; } }
internal static CngKey FromXml(string xml) { CngKey key; using (TextReader reader = new StringReader(xml)) { using (XmlTextReader reader2 = new XmlTextReader(reader)) { BigInteger integer; BigInteger integer2; XPathNavigator navigator = new XPathDocument(reader2).CreateNavigator(); if (!navigator.MoveToFirstChild()) { throw new ArgumentException(System.SR.GetString("Cryptography_MissingDomainParameters")); } CngAlgorithm algorithm = ReadAlgorithm(navigator); if (!navigator.MoveToNext(XPathNodeType.Element)) { throw new ArgumentException(System.SR.GetString("Cryptography_MissingPublicKey")); } ReadPublicKey(navigator, out integer, out integer2); key = CngKey.Import(NCryptNative.BuildEccPublicBlob(algorithm.Algorithm, integer, integer2), CngKeyBlobFormat.EccPublicBlob); } } return(key); }
public BCryptHashAlgorithm(CngAlgorithm algorithm, string implementation) { if (!BCryptNative.BCryptSupported) { throw new PlatformNotSupportedException(System.SR.GetString("Cryptography_PlatformNotSupported")); } this.m_algorithmHandle = BCryptNative.OpenAlgorithm(algorithm.Algorithm, implementation); this.Initialize(); }
public ECDsaCng(int keySize) { this.m_hashAlgorithm = CngAlgorithm.Sha256; if (!NCryptNative.NCryptSupported) { throw new PlatformNotSupportedException(System.SR.GetString("Cryptography_PlatformNotSupported")); } base.LegalKeySizesValue = s_legalKeySizes; this.KeySize = keySize; }
public static CngKey Create(CngAlgorithm algorithm, string keyName, CngKeyCreationParameters creationParameters) { Contract.Ensures(Contract.Result <CngKey>() != null); if (algorithm == null) { throw new ArgumentNullException("algorithm"); } if (creationParameters == null) { creationParameters = new CngKeyCreationParameters(); } // Make sure that NCrypt is supported on this platform if (!NCryptNative.NCryptSupported) { throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported)); } // If we're not creating an ephemeral key, then we need to ensure the user has access to the key name if (keyName != null) { KeyContainerPermissionAccessEntry access = new KeyContainerPermissionAccessEntry(keyName, KeyContainerPermissionFlags.Create); access.ProviderName = creationParameters.Provider.Provider; KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); permission.AccessEntries.Add(access); permission.Demand(); } // // Create the native handles representing the new key, setup the creation parameters on it, and // finalize it for use. // SafeNCryptProviderHandle kspHandle = NCryptNative.OpenStorageProvider(creationParameters.Provider.Provider); SafeNCryptKeyHandle keyHandle = NCryptNative.CreatePersistedKey(kspHandle, algorithm.Algorithm, keyName, creationParameters.KeyCreationOptions); SetKeyProperties(keyHandle, creationParameters); NCryptNative.FinalizeKey(keyHandle); CngKey key = new CngKey(kspHandle, keyHandle); // No name translates to an ephemeral key if (keyName == null) { key.IsEphemeral = true; } return(key); }
public override void GenerateKey(ECCurve curve) { curve.Validate(); _core.DisposeKey(); if (curve.IsNamed) { if (string.IsNullOrEmpty(curve.Oid.FriendlyName)) { throw new PlatformNotSupportedException(string.Format(SR.Cryptography_InvalidCurveOid, curve.Oid.Value)); } // Map curve name to algorithm to support pre-Win10 curves CngAlgorithm alg = CngKey.EcdhCurveNameToAlgorithm(curve.Oid.FriendlyName); if (CngKey.IsECNamedCurve(alg.Algorithm)) { CngKey key = _core.GetOrGenerateKey(curve); ForceSetKeySize(key.KeySize); } else { int keySize = 0; // Get the proper KeySize from algorithm name if (alg == CngAlgorithm.ECDiffieHellmanP256) { keySize = 256; } else if (alg == CngAlgorithm.ECDiffieHellmanP384) { keySize = 384; } else if (alg == CngAlgorithm.ECDiffieHellmanP521) { keySize = 521; } else { Debug.Fail(string.Format("Unknown algorithm {0}", alg.ToString())); throw new ArgumentException(SR.Cryptography_InvalidKeySize); } CngKey key = _core.GetOrGenerateKey(keySize, alg); ForceSetKeySize(keySize); } } else if (curve.IsExplicit) { CngKey key = _core.GetOrGenerateKey(curve); ForceSetKeySize(key.KeySize); } else { throw new PlatformNotSupportedException(string.Format(SR.Cryptography_CurveNotSupported, curve.CurveType.ToString())); } }
public BCryptHashAlgorithm(CngAlgorithm algorithm, string implementation) { Contract.Requires(algorithm != null); Contract.Requires(!String.IsNullOrEmpty(implementation)); Contract.Ensures(m_algorithmHandle != null && !m_algorithmHandle.IsInvalid && !m_algorithmHandle.IsClosed); Contract.Ensures(m_hashHandle != null && !m_hashHandle.IsInvalid && !m_hashHandle.IsClosed); if (_algorithmCache == null) { _algorithmCache = new BCryptAlgorithmHandleCache(); } m_algorithmHandle = _algorithmCache.GetCachedAlgorithmHandle(algorithm.Algorithm, implementation); Initialize(); }
private static string GetCurveUrn(CngAlgorithm algorithm) { if ((algorithm == CngAlgorithm.ECDsaP256) || (algorithm == CngAlgorithm.ECDiffieHellmanP256)) { return("urn:oid:1.2.840.10045.3.1.7"); } if ((algorithm == CngAlgorithm.ECDsaP384) || (algorithm == CngAlgorithm.ECDiffieHellmanP384)) { return("urn:oid:1.3.132.0.34"); } if (!(algorithm == CngAlgorithm.ECDsaP521) && !(algorithm == CngAlgorithm.ECDiffieHellmanP521)) { throw new ArgumentException(System.SR.GetString("Cryptography_UnknownEllipticCurve"), "algorithm"); } return("urn:oid:1.3.132.0.35"); }
public ECDsaCng(CngKey key) { this.m_hashAlgorithm = CngAlgorithm.Sha256; if (key == null) { throw new ArgumentNullException("key"); } if (key.AlgorithmGroup != CngAlgorithmGroup.ECDsa) { throw new ArgumentException(System.SR.GetString("Cryptography_ArgECDsaRequiresECDsaKey"), "key"); } if (!NCryptNative.NCryptSupported) { throw new PlatformNotSupportedException(System.SR.GetString("Cryptography_PlatformNotSupported")); } base.LegalKeySizesValue = s_legalKeySizes; new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); this.Key = CngKey.Open(key.Handle, key.IsEphemeral ? CngKeyHandleOpenOptions.EphemeralKey : CngKeyHandleOpenOptions.None); CodeAccessPermission.RevertAssert(); this.KeySize = this.m_key.KeySize; }
/// <summary> /// Get the OID which represents an elliptic curve /// </summary> private static string GetCurveUrn(CngAlgorithm algorithm) { Contract.Requires(algorithm != null); if (algorithm == CngAlgorithm.ECDsaP256 || algorithm == CngAlgorithm.ECDiffieHellmanP256) { return(Prime256CurveUrn); } else if (algorithm == CngAlgorithm.ECDsaP384 || algorithm == CngAlgorithm.ECDiffieHellmanP384) { return(Prime384CurveUrn); } else if (algorithm == CngAlgorithm.ECDsaP521 || algorithm == CngAlgorithm.ECDiffieHellmanP521) { return(Prime521CurveUrn); } else { throw new ArgumentException(SR.GetString(SR.Cryptography_UnknownEllipticCurve), "algorithm"); } }
public static CngKey Create(CngAlgorithm algorithm, string keyName, CngKeyCreationParameters creationParameters) { if (algorithm == null) { throw new ArgumentNullException(nameof(algorithm)); } if (creationParameters == null) { creationParameters = new CngKeyCreationParameters(); } SafeNCryptProviderHandle providerHandle = creationParameters.Provider.OpenStorageProvider(); SafeNCryptKeyHandle keyHandle; ErrorCode errorCode = Interop.NCrypt.NCryptCreatePersistedKey(providerHandle, out keyHandle, algorithm.Algorithm, keyName, 0, creationParameters.KeyCreationOptions); if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } InitializeKeyProperties(keyHandle, creationParameters); errorCode = Interop.NCrypt.NCryptFinalizeKey(keyHandle, 0); if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } CngKey key = new CngKey(providerHandle, keyHandle); // No name translates to an ephemeral key if (keyName == null) { key.IsEphemeral = true; } return(key); }
public BCryptHashAlgorithm(CngAlgorithm algorithm, string implementation) { Contract.Requires(algorithm != null); Contract.Requires(!String.IsNullOrEmpty(implementation)); Contract.Ensures(m_algorithmHandle != null && !m_algorithmHandle.IsInvalid && !m_algorithmHandle.IsClosed); Contract.Ensures(m_hashHandle != null && !m_hashHandle.IsInvalid && !m_hashHandle.IsClosed); // Make sure CNG is supported on this platform if (!BCryptNative.BCryptSupported) { throw new PlatformNotSupportedException("SR.Cryptography_PlatformNotSupported"); } if (_algorithmCache == null) { _algorithmCache = new BCryptAlgorithmHandleCache(); } m_algorithmHandle = _algorithmCache.GetCachedAlgorithmHandle(algorithm.Algorithm, implementation); Initialize(); }
public static CngKey Create(CngAlgorithm algorithm, string keyName, CngKeyCreationParameters creationParameters) { if (algorithm == null) { throw new ArgumentNullException("algorithm"); } if (creationParameters == null) { creationParameters = new CngKeyCreationParameters(); } if (!NCryptNative.NCryptSupported) { throw new PlatformNotSupportedException(System.SR.GetString("Cryptography_PlatformNotSupported")); } if (keyName != null) { KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(keyName, KeyContainerPermissionFlags.Create) { ProviderName = creationParameters.Provider.Provider }; KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); permission.AccessEntries.Add(accessEntry); permission.Demand(); } SafeNCryptProviderHandle provider = NCryptNative.OpenStorageProvider(creationParameters.Provider.Provider); SafeNCryptKeyHandle keyHandle = NCryptNative.CreatePersistedKey(provider, algorithm.Algorithm, keyName, creationParameters.KeyCreationOptions); SetKeyProperties(keyHandle, creationParameters); NCryptNative.FinalizeKey(keyHandle); CngKey key = new CngKey(provider, keyHandle); if (keyName == null) { key.IsEphemeral = true; } return(key); }
/// <summary> /// Restore a key from XML /// </summary> internal static CngKey FromXml(string xml) { Contract.Requires(xml != null); Contract.Ensures(Contract.Result <CngKey>() != null); // Load the XML into an XPathNavigator to access sub elements using (TextReader textReader = new StringReader(xml)) using (XmlTextReader xmlReader = new XmlTextReader(textReader)) { XPathDocument document = new XPathDocument(xmlReader); XPathNavigator navigator = document.CreateNavigator(); // Move into the root element - we don't do a specific namespace check here for compatibility // with XML that Windows generates. if (!navigator.MoveToFirstChild()) { throw new ArgumentException(SR.GetString(SR.Cryptography_MissingDomainParameters)); } // First figure out which algorithm this key belongs to CngAlgorithm algorithm = ReadAlgorithm(navigator); // Then read out the public key value if (!navigator.MoveToNext(XPathNodeType.Element)) { throw new ArgumentException(SR.GetString(SR.Cryptography_MissingPublicKey)); } BigInteger x; BigInteger y; ReadPublicKey(navigator, out x, out y); // Finally, convert them into a key blob to import into a CngKey byte[] keyBlob = NCryptNative.BuildEccPublicBlob(algorithm.Algorithm, x, y); return(CngKey.Import(keyBlob, CngKeyBlobFormat.EccPublicBlob)); } }
public static CngKey Create(CngAlgorithm algorithm, string keyName) { Contract.Ensures(Contract.Result <System.Security.Cryptography.CngKey>() != null); return(default(CngKey)); }
public static CngKey Create(CngAlgorithm algorithm !!, string?keyName, CngKeyCreationParameters?creationParameters)
// // Creation factory methods // public static CngKey Create(CngAlgorithm algorithm) { return(Create(algorithm, keyName: null)); }
public static CngKey Create(CngAlgorithm algorithm, string keyName) { return(Create(algorithm, keyName, creationParameters: null)); }
private CngKey GetKey( #if !NETNATIVE ECCurve?curve = null #endif ) { CngKey key = null; CngAlgorithm algorithm = null; int keySize = 0; #if !NETNATIVE if (curve != null) { if (curve.Value.IsNamed) { // Map curve name to algorithm to support pre-Win10 curves CngAlgorithm alg = CngKey.EcdsaCurveNameToAlgorithm(curve.Value.Oid.FriendlyName); if (CngKey.IsECNamedCurve(alg.Algorithm)) { key = _core.GetOrGenerateKey(curve.Value); } else { // Get the proper KeySize from algorithm name if (alg == CngAlgorithm.ECDsaP256) { keySize = 256; } else if (alg == CngAlgorithm.ECDsaP384) { keySize = 384; } else if (alg == CngAlgorithm.ECDsaP521) { keySize = 521; } else { Debug.Fail(string.Format("Unknown algorithm {0}", alg.ToString())); throw new ArgumentException(SR.Cryptography_InvalidKeySize); } key = _core.GetOrGenerateKey(keySize, alg); } ForceSetKeySize(key.KeySize); } else if (curve.Value.IsExplicit) { key = _core.GetOrGenerateKey(curve.Value); ForceSetKeySize(key.KeySize); } else { throw new PlatformNotSupportedException(string.Format(SR.Cryptography_CurveNotSupported, curve.Value.CurveType.ToString())); } } else if (_core.IsKeyGeneratedNamedCurve()) { key = _core.GetOrGenerateKey(null); } else #endif { // Map the current key size to a CNG algorithm name keySize = KeySize; switch (keySize) { case 256: algorithm = CngAlgorithm.ECDsaP256; break; case 384: algorithm = CngAlgorithm.ECDsaP384; break; case 521: algorithm = CngAlgorithm.ECDsaP521; break; default: Debug.Fail("Should not have invalid key size"); throw new ArgumentException(SR.Cryptography_InvalidKeySize); } key = _core.GetOrGenerateKey(keySize, algorithm); } return(key); }
public static CngKey Create(CngAlgorithm algorithm, string keyName) { Contract.Ensures(Contract.Result <CngKey>() != null); return(Create(algorithm, keyName, null)); }
public static CngKey Create(CngAlgorithm algorithm, string keyName, CngKeyCreationParameters creationParameters) { throw new NotImplementedException(); }
public static CngKey Create(CngAlgorithm algorithm) { throw new NotImplementedException(); }
public static CngKey Create(CngAlgorithm algorithm, string keyName) { return(Create(algorithm, keyName, null)); }