private byte[] SignHash(byte[] hash) { if (hash == null) { throw ExceptionUtility.ArgumentNull("hash"); } if (hash.Length != 32) { throw ExceptionUtility.ArgumentOutOfRange("hash", Resources.InvalidHashSize); } if (IsPublicKeyOnly) { throw ExceptionUtility.CryptographicException(Resources.NoPrivateKey); } GetKeyPair(); if (!CspKeyContainerInfo.RandomlyGenerated) { var keyContainerPermission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); var keyContainerAccessEntry = new KeyContainerPermissionAccessEntry(_providerParameters, KeyContainerPermissionFlags.Sign); keyContainerPermission.AccessEntries.Add(keyContainerAccessEntry); keyContainerPermission.Demand(); } return(CryptoApiHelper.SignValue(_providerHandle, _providerParameters.KeyNumber, hash)); }
internal static void ImportCspBlobHelper(CspAlgorithmType keyType, byte[] keyBlob, bool publicOnly, ref CspParameters parameters, bool randomKeyContainer, ref SafeProvHandle safeProvHandle, ref SafeKeyHandle safeKeyHandle) { if (safeKeyHandle != null && !safeKeyHandle.IsClosed) { safeKeyHandle.Dispose(); } safeKeyHandle = SafeKeyHandle.InvalidHandle; if (publicOnly) { parameters.KeyNumber = Utils._ImportCspBlob(keyBlob, keyType == CspAlgorithmType.Dss ? Utils.StaticDssProvHandle : Utils.StaticProvHandle, CspProviderFlags.NoFlags, ref safeKeyHandle); } else { if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermission containerPermission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Import); containerPermission.AccessEntries.Add(accessEntry); containerPermission.Demand(); } if (safeProvHandle == null) { safeProvHandle = Utils.CreateProvHandle(parameters, randomKeyContainer); } parameters.KeyNumber = Utils._ImportCspBlob(keyBlob, safeProvHandle, parameters.Flags, ref safeKeyHandle); } }
public byte[] Decrypt(byte[] rgb, bool fOAEP) { if (rgb == null) { throw new ArgumentNullException("rgb"); } this.GetKeyPair(); if (rgb.Length > this.KeySize / 8) { throw new CryptographicException(Environment.GetResourceString("Cryptography_Padding_DecDataTooBig", new object[] { this.KeySize / 8 })); } if (!this.CspKeyContainerInfo.RandomlyGenerated && !CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermission keyContainerPermission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(this._parameters, KeyContainerPermissionFlags.Decrypt); keyContainerPermission.AccessEntries.Add(accessEntry); keyContainerPermission.Demand(); } byte[] result = null; RSACryptoServiceProvider.DecryptKey(this._safeKeyHandle, rgb, rgb.Length, fOAEP, JitHelpers.GetObjectHandleOnStack <byte[]>(ref result)); return(result); }
public override void ImportParameters(DSAParameters parameters) { DSACspObject cspObject = DSAStructToObject(parameters); if ((this._safeKeyHandle != null) && !this._safeKeyHandle.IsClosed) { this._safeKeyHandle.Dispose(); } this._safeKeyHandle = SafeKeyHandle.InvalidHandle; if (IsPublic(parameters)) { Utils._ImportKey(Utils.StaticDssProvHandle, 0x2200, CspProviderFlags.NoFlags, cspObject, ref this._safeKeyHandle); } else { KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(this._parameters, KeyContainerPermissionFlags.Import); permission.AccessEntries.Add(accessEntry); permission.Demand(); if (this._safeProvHandle == null) { this._safeProvHandle = Utils.CreateProvHandle(this._parameters, this._randomKeyContainer); } Utils._ImportKey(this._safeProvHandle, 0x2200, this._parameters.Flags, cspObject, ref this._safeKeyHandle); } }
[System.Security.SecuritySafeCritical] // auto-generated public byte[] SignHash(byte[] rgbHash, string str) { if (rgbHash == null) { throw new ArgumentNullException("rgbHash"); } Contract.EndContractBlock(); if (PublicOnly) { throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_NoPrivateKey")); } int calgHash = X509Utils.NameOrOidToAlgId(str, OidGroup.HashAlgorithm); if (rgbHash.Length != _sha1.HashSize / 8) { throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidHashSize", "SHA1", _sha1.HashSize / 8)); } GetKeyPair(); if (!CspKeyContainerInfo.RandomlyGenerated) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Sign); kp.AccessEntries.Add(entry); kp.Demand(); } return(Utils.SignValue(_safeKeyHandle, _parameters.KeyNumber, Constants.CALG_DSS_SIGN, calgHash, rgbHash)); }
public byte[] Decrypt(byte[] rgb, bool fOAEP) { if (rgb == null) { throw new ArgumentNullException("rgb"); } this.GetKeyPair(); if (rgb.Length > this.KeySize / 8) { throw new CryptographicException(Environment.GetResourceString("Cryptography_Padding_DecDataTooBig", (object)(this.KeySize / 8))); } if (!this.CspKeyContainerInfo.RandomlyGenerated && !CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermission containerPermission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(this._parameters, KeyContainerPermissionFlags.Decrypt); containerPermission.AccessEntries.Add(accessEntry); containerPermission.Demand(); } byte[] o = (byte[])null; SafeKeyHandle pKeyContext = this._safeKeyHandle; byte[] pbEncryptedKey = rgb; int length = pbEncryptedKey.Length; int num = fOAEP ? 1 : 0; ObjectHandleOnStack objectHandleOnStack = JitHelpers.GetObjectHandleOnStack <byte[]>(ref o); RSACryptoServiceProvider.DecryptKey(pKeyContext, pbEncryptedKey, length, num != 0, objectHandleOnStack); return(o); }
private unsafe void CounterSign(CmsSigner signer) { // Sanity check. Debug.Assert(signer != null); // CspParameters parameters = new CspParameters(); if (X509Utils.GetPrivateKeyInfo(X509Utils.GetCertContext(signer.Certificate), ref parameters) == false) { throw new CryptographicException(Marshal.GetLastWin32Error()); } KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Sign); kp.AccessEntries.Add(entry); kp.Demand(); // Get the signer's index. uint index = (uint)PkcsUtils.GetSignerIndex(m_signedCms.GetCryptMsgHandle(), this, 0); // Create CMSG_SIGNER_ENCODE_INFO structure. SafeLocalAllocHandle pSignerEncodeInfo = CAPI.LocalAlloc(CAPI.LPTR, new IntPtr(Marshal.SizeOf(typeof(CAPI.CMSG_SIGNER_ENCODE_INFO)))); CAPI.CMSG_SIGNER_ENCODE_INFO signerEncodeInfo = PkcsUtils.CreateSignerEncodeInfo(signer); try { // Marshal to unmanaged memory. Marshal.StructureToPtr(signerEncodeInfo, pSignerEncodeInfo.DangerousGetHandle(), false); // Counter sign. if (!CAPI.CryptMsgCountersign(m_signedCms.GetCryptMsgHandle(), index, 1, pSignerEncodeInfo.DangerousGetHandle())) { throw new CryptographicException(Marshal.GetLastWin32Error()); } // CAPI requires that the messge be re-encoded if any unauthenticated // attribute has been added. So, let's re-open it to decode to work // around this limitation. m_signedCms.ReopenToDecode(); } finally { Marshal.DestroyStructure(pSignerEncodeInfo.DangerousGetHandle(), typeof(CAPI.CMSG_SIGNER_ENCODE_INFO)); pSignerEncodeInfo.Dispose(); // and don't forget to dispose of resources allocated for the structure. signerEncodeInfo.Dispose(); } // Finally, add certs to bag of certs. PkcsUtils.AddCertsToMessage(m_signedCms.GetCryptMsgHandle(), m_signedCms.Certificates, PkcsUtils.CreateBagOfCertificates(signer)); return; }
public override void ImportParameters(RSAParameters parameters) { if (this._safeKeyHandle != null && !this._safeKeyHandle.IsClosed) { this._safeKeyHandle.Dispose(); this._safeKeyHandle = (SafeKeyHandle)null; } RSACspObject @object = RSACryptoServiceProvider.RSAStructToObject(parameters); this._safeKeyHandle = SafeKeyHandle.InvalidHandle; if (RSACryptoServiceProvider.IsPublic(parameters)) { Utils._ImportKey(Utils.StaticProvHandle, 41984, CspProviderFlags.NoFlags, (object)@object, ref this._safeKeyHandle); } else { if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermission containerPermission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(this._parameters, KeyContainerPermissionFlags.Import); containerPermission.AccessEntries.Add(accessEntry); containerPermission.Demand(); } if (this._safeProvHandle == null) { this._safeProvHandle = Utils.CreateProvHandle(this._parameters, this._randomKeyContainer); } Utils._ImportKey(this._safeProvHandle, 41984, this._parameters.Flags, (object)@object, ref this._safeKeyHandle); } }
private void CounterSign(CmsSigner signer) { CspParameters parameters = new CspParameters(); if (!X509Utils.GetPrivateKeyInfo(X509Utils.GetCertContext(signer.Certificate), ref parameters)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } KeyContainerPermission containerPermission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Sign); containerPermission.AccessEntries.Add(accessEntry); containerPermission.Demand(); uint dwIndex = (uint)PkcsUtils.GetSignerIndex(this.m_signedCms.GetCryptMsgHandle(), this, 0); SafeLocalAllocHandle localAllocHandle = CAPI.LocalAlloc(64U, new IntPtr(Marshal.SizeOf(typeof(CAPI.CMSG_SIGNER_ENCODE_INFO)))); CAPI.CMSG_SIGNER_ENCODE_INFO signerEncodeInfo = PkcsUtils.CreateSignerEncodeInfo(signer); try { Marshal.StructureToPtr((object)signerEncodeInfo, localAllocHandle.DangerousGetHandle(), false); if (!CAPI.CryptMsgCountersign(this.m_signedCms.GetCryptMsgHandle(), dwIndex, 1U, localAllocHandle.DangerousGetHandle())) { throw new CryptographicException(Marshal.GetLastWin32Error()); } this.m_signedCms.ReopenToDecode(); } finally { Marshal.DestroyStructure(localAllocHandle.DangerousGetHandle(), typeof(CAPI.CMSG_SIGNER_ENCODE_INFO)); localAllocHandle.Dispose(); signerEncodeInfo.Dispose(); } int num = (int)PkcsUtils.AddCertsToMessage(this.m_signedCms.GetCryptMsgHandle(), this.m_signedCms.Certificates, PkcsUtils.CreateBagOfCertificates(signer)); }
void DemandRefusedPermission() { try { KeyContainerPermission kCP = new KeyContainerPermission( KeyContainerPermissionFlags.Import); kCP.Demand(); } catch (SecurityException sE) { //<Snippet10> Display("The refused permission set is: " + (sE.RefusedSet).ToString()); //</Snippet10> //<Snippet11> Display("The exception message is: " + sE.Message); //</Snippet11> //<Snippet12> Display("The failed assembly is: " + sE.FailedAssemblyInfo.EscapedCodeBase); //</Snippet12> //<Snippet13> Display("The granted set is: \n" + sE.GrantedSet); //</Snippet13> Display("The permission that failed is: " + sE.FirstPermissionThatFailed); Display("The permission type is: " + sE.PermissionType.ToString()); //<Snippet14> Display("The source is: " + sE.Source); //</Snippet14> } }
internal static SafeProvHandle CreateProvHandle(CspParameters parameters, bool randomKeyContainer) { SafeProvHandle invalidHandle = SafeProvHandle.InvalidHandle; int hr = Utils._OpenCSP(parameters, 0U, ref invalidHandle); KeyContainerPermission containerPermission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); if (hr != 0) { if ((parameters.Flags & CspProviderFlags.UseExistingKey) != CspProviderFlags.NoFlags || hr != -2146893799 && hr != -2146893802 && hr != -2147024894) { throw new CryptographicException(hr); } if (!randomKeyContainer && !CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Create); containerPermission.AccessEntries.Add(accessEntry); containerPermission.Demand(); } Utils._CreateCSP(parameters, randomKeyContainer, ref invalidHandle); } else if (!randomKeyContainer && !CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open); containerPermission.AccessEntries.Add(accessEntry); containerPermission.Demand(); } return(invalidHandle); }
private static void DenyOpen() { try { //<Snippet20> // Create a KeyContainerPermission with the right // to open the key container. KeyContainerPermission keyContainerPerm = new KeyContainerPermission(KeyContainerPermissionFlags.Open); //</Snippet20> // Demonstrate the results of a deny for an open action. keyContainerPerm.Deny(); // The next line causes an exception to be thrown when the // infrastructure code attempts to open the key container. CspKeyContainerInfo info = new CspKeyContainerInfo(cspParams); } catch (Exception e) { Console.WriteLine("Expected exception thrown: " + e.Message); } // Revert the deny. CodeAccessPermission.RevertDeny(); }
[System.Security.SecuritySafeCritical] // auto-generated public override void ImportParameters(DSAParameters parameters) { DSACspObject dsaCspObject = DSAStructToObject(parameters); // Free the current key handle if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed) { _safeKeyHandle.Dispose(); } _safeKeyHandle = SafeKeyHandle.InvalidHandle; if (IsPublic(parameters)) { // Use our CRYPT_VERIFYCONTEXT handle, CRYPT_EXPORTABLE is not applicable to public only keys, so pass false Utils._ImportKey(Utils.StaticDssProvHandle, Constants.CALG_DSS_SIGN, (CspProviderFlags)0, dsaCspObject, ref _safeKeyHandle); } else { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Import); kp.AccessEntries.Add(entry); kp.Demand(); if (_safeProvHandle == null) { _safeProvHandle = Utils.CreateProvHandle(_parameters, _randomKeyContainer); } // Now, import the key into the CSP; _ImportKey will check for failures. Utils._ImportKey(_safeProvHandle, Constants.CALG_DSS_SIGN, _parameters.Flags, dsaCspObject, ref _safeKeyHandle); } }
public byte[] SignHash(byte[] rgbHash, string str) { if (rgbHash == null) { throw new ArgumentNullException("rgbHash"); } if (this.PublicOnly) { throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_NoPrivateKey")); } int calgHash = X509Utils.OidToAlgId(str); if (rgbHash.Length != (this._sha1.HashSize / 8)) { throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidHashSize", new object[] { "SHA1", this._sha1.HashSize / 8 })); } this.GetKeyPair(); if (!this.CspKeyContainerInfo.RandomlyGenerated) { KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(this._parameters, KeyContainerPermissionFlags.Sign); permission.AccessEntries.Add(accessEntry); permission.Demand(); } return(Utils.SignValue(this._safeKeyHandle, this._parameters.KeyNumber, 0x2200, calgHash, rgbHash)); }
internal KeyContainerPermission BuildKeyContainerPermission(KeyContainerPermissionFlags flags) { KeyContainerPermission permission = null; if (this.IsEphemeral) { return(permission); } string keyContainerName = null; string str2 = null; try { keyContainerName = this.KeyName; str2 = NCryptNative.GetPropertyAsString(this.m_kspHandle, "Name", CngPropertyOptions.None); } catch (CryptographicException) { } if (keyContainerName != null) { KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(keyContainerName, flags) { ProviderName = str2 }; permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); permission.AccessEntries.Add(accessEntry); return(permission); } return(new KeyContainerPermission(flags)); }
public override byte[] SignHash(byte[] hash) { if (hash == null) { throw new ArgumentNullException("hash"); } // Make sure we're allowed to sign using this key KeyContainerPermission permission = Key.BuildKeyContainerPermission(KeyContainerPermissionFlags.Sign); if (permission != null) { permission.Demand(); } // Now that know we have permission to use this key for signing, pull the key value out, which // will require unmanaged code permission new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); // This looks odd, but the key handle is actually a duplicate so we need to dispose it using (SafeNCryptKeyHandle keyHandle = Key.Handle) { CodeAccessPermission.RevertAssert(); return(NCryptNative.SignHash(keyHandle, hash)); } }
internal static SafeProvHandle CreateProvHandle(CspParameters parameters, bool randomKeyContainer) { SafeProvHandle invalidHandle = SafeProvHandle.InvalidHandle; int hr = _OpenCSP(parameters, 0, ref invalidHandle); KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); if (hr != 0) { if (((parameters.Flags & CspProviderFlags.UseExistingKey) != CspProviderFlags.NoFlags) || (((hr != -2146893799) && (hr != -2146893802)) && (hr != -2147024894))) { throw new CryptographicException(hr); } if (!randomKeyContainer) { KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Create); permission.AccessEntries.Add(accessEntry); permission.Demand(); } _CreateCSP(parameters, randomKeyContainer, ref invalidHandle); return(invalidHandle); } if (!randomKeyContainer) { KeyContainerPermissionAccessEntry entry2 = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open); permission.AccessEntries.Add(entry2); permission.Demand(); } return(invalidHandle); }
[System.Security.SecuritySafeCritical] // auto-generated public byte [] Decrypt(byte[] rgb, bool fOAEP) { if (rgb == null) { throw new ArgumentNullException("rgb"); } Contract.EndContractBlock(); GetKeyPair(); // size check -- must be at most the modulus size if (rgb.Length > (KeySize / 8)) { throw new CryptographicException(Environment.GetResourceString("Cryptography_Padding_DecDataTooBig", KeySize / 8)); } if (!CspKeyContainerInfo.RandomlyGenerated) { if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(_parameters, KeyContainerPermissionFlags.Decrypt); kp.AccessEntries.Add(entry); kp.Demand(); } } byte[] decryptedKey = null; DecryptKey(_safeKeyHandle, rgb, rgb.Length, fOAEP, JitHelpers.GetObjectHandleOnStack(ref decryptedKey)); return(decryptedKey); }
public static CngKey Open(string keyName, CngProvider provider, CngKeyOpenOptions openOptions) { if (keyName == null) { throw new ArgumentNullException("keyName"); } if (provider == null) { throw new ArgumentNullException("provider"); } if (!NCryptNative.NCryptSupported) { throw new PlatformNotSupportedException(System.SR.GetString("Cryptography_PlatformNotSupported")); } KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(keyName, KeyContainerPermissionFlags.Open) { ProviderName = provider.Provider }; KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); permission.AccessEntries.Add(accessEntry); permission.Demand(); SafeNCryptProviderHandle kspHandle = NCryptNative.OpenStorageProvider(provider.Provider); return(new CngKey(kspHandle, NCryptNative.OpenKey(kspHandle, keyName, openOptions))); }
public static CngKey Open(string keyName, CngProvider provider, CngKeyOpenOptions openOptions) { Contract.Ensures(Contract.Result <CngKey>() != null); if (keyName == null) { throw new ArgumentNullException("keyName"); } if (provider == null) { throw new ArgumentNullException("provider"); } // Make sure that NCrypt is supported on this platform if (!NCryptNative.NCryptSupported) { throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported)); } // Ensure the user has access to the key name KeyContainerPermissionAccessEntry access = new KeyContainerPermissionAccessEntry(keyName, KeyContainerPermissionFlags.Open); access.ProviderName = provider.Provider; KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); permission.AccessEntries.Add(access); permission.Demand(); // Open the key SafeNCryptProviderHandle kspHandle = NCryptNative.OpenStorageProvider(provider.Provider); SafeNCryptKeyHandle keyHandle = NCryptNative.OpenKey(kspHandle, keyName, openOptions); return(new CngKey(kspHandle, keyHandle)); }
private byte[] SignHash(byte[] hash) { ValidateHashParameter(hash); if (IsPublicKeyOnly) { throw ExceptionUtility.CryptographicException(Resources.NoPrivateKey); } GetKeyPair(); if (!CspKeyContainerInfo.RandomlyGenerated) { var keyContainerPermission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); var keyContainerAccessEntry = new KeyContainerPermissionAccessEntry(_providerParameters, KeyContainerPermissionFlags.Sign); keyContainerPermission.AccessEntries.Add(keyContainerAccessEntry); keyContainerPermission.Demand(); } using (var hashAlgorithm = CreateHashAlgorithm()) { var hashHandleProvider = (ISafeHandleProvider <SafeHashHandleImpl>)hashAlgorithm; return(CryptoApiHelper.SignValue(_providerHandle, hashHandleProvider.SafeHandle, _providerParameters.KeyNumber, hash)); } }
internal unsafe static void GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, bool randomKeyContainer, int dwKeySize, ref SafeProvHandle safeProvHandle, ref SafeKeyHandle safeKeyHandle) { SafeProvHandle safeProvHandle2 = Utils.CreateProvHandle(parameters, randomKeyContainer); if (parameters.CryptoKeySecurity != null) { KeyContainerPermission keyContainerPermission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.ChangeAcl); keyContainerPermission.AccessEntries.Add(accessEntry); keyContainerPermission.Demand(); Utils.SetKeySetSecurityInfo(safeProvHandle2, parameters.CryptoKeySecurity, parameters.CryptoKeySecurity.ChangedAccessControlSections); } if (parameters.ParentWindowHandle != IntPtr.Zero) { IntPtr parentWindowHandle = parameters.ParentWindowHandle; IntPtr pbData = parentWindowHandle; if (!AppContextSwitches.DoNotAddrOfCspParentWindowHandle) { pbData = new IntPtr((void *)(&parentWindowHandle)); } Utils.SetProviderParameter(safeProvHandle2, parameters.KeyNumber, 10U, pbData); } else if (parameters.KeyPassword != null) { IntPtr intPtr = Marshal.SecureStringToCoTaskMemAnsi(parameters.KeyPassword); try { Utils.SetProviderParameter(safeProvHandle2, parameters.KeyNumber, 11U, intPtr); } finally { if (intPtr != IntPtr.Zero) { Marshal.ZeroFreeCoTaskMemAnsi(intPtr); } } } safeProvHandle = safeProvHandle2; SafeKeyHandle invalidHandle = SafeKeyHandle.InvalidHandle; int num = Utils._GetUserKey(safeProvHandle, parameters.KeyNumber, ref invalidHandle); if (num != 0) { if ((parameters.Flags & CspProviderFlags.UseExistingKey) != CspProviderFlags.NoFlags || num != -2146893811) { throw new CryptographicException(num); } Utils._GenerateKey(safeProvHandle, parameters.KeyNumber, parameters.Flags, dwKeySize, ref invalidHandle); } byte[] array = Utils._GetKeyParameter(invalidHandle, 9U); int num2 = (int)array[0] | (int)array[1] << 8 | (int)array[2] << 16 | (int)array[3] << 24; if ((keyType == CspAlgorithmType.Rsa && num2 != 41984 && num2 != 9216) || (keyType == CspAlgorithmType.Dss && num2 != 8704)) { invalidHandle.Dispose(); throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_WrongKeySpec")); } safeKeyHandle = invalidHandle; }
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 void Unrestricted() { KeyContainerPermissionAttribute a = Empty(); a.Unrestricted = true; Assert.AreEqual(KeyContainerPermissionFlags.NoFlags, a.Flags, "Flags"); KeyContainerPermission perm = (KeyContainerPermission)a.CreatePermission(); Assert.AreEqual(KeyContainerPermissionFlags.AllFlags, perm.Flags, "CreatePermission.Flags"); }
public void Delete() { KeyContainerPermission permission = this.BuildKeyContainerPermission(KeyContainerPermissionFlags.Delete); if (permission != null) { permission.Demand(); } NCryptNative.DeleteKey(this.m_keyHandle); this.Dispose(); }
internal static void GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, bool randomKeyContainer, int dwKeySize, ref SafeProvHandle safeProvHandle, ref SafeKeyHandle safeKeyHandle) { SafeProvHandle provHandle = Utils.CreateProvHandle(parameters, randomKeyContainer); if (parameters.CryptoKeySecurity != null) { KeyContainerPermission containerPermission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.ChangeAcl); containerPermission.AccessEntries.Add(accessEntry); containerPermission.Demand(); Utils.SetKeySetSecurityInfo(provHandle, parameters.CryptoKeySecurity, parameters.CryptoKeySecurity.ChangedAccessControlSections); } if (parameters.ParentWindowHandle != IntPtr.Zero) { Utils.SetProviderParameter(provHandle, parameters.KeyNumber, 10U, parameters.ParentWindowHandle); } else if (parameters.KeyPassword != null) { IntPtr coTaskMemAnsi = Marshal.SecureStringToCoTaskMemAnsi(parameters.KeyPassword); try { Utils.SetProviderParameter(provHandle, parameters.KeyNumber, 11U, coTaskMemAnsi); } finally { if (coTaskMemAnsi != IntPtr.Zero) { Marshal.ZeroFreeCoTaskMemAnsi(coTaskMemAnsi); } } } safeProvHandle = provHandle; SafeKeyHandle invalidHandle = SafeKeyHandle.InvalidHandle; int userKey = Utils._GetUserKey(safeProvHandle, parameters.KeyNumber, ref invalidHandle); if (userKey != 0) { if ((parameters.Flags & CspProviderFlags.UseExistingKey) != CspProviderFlags.NoFlags || userKey != -2146893811) { throw new CryptographicException(userKey); } Utils._GenerateKey(safeProvHandle, parameters.KeyNumber, parameters.Flags, dwKeySize, ref invalidHandle); } byte[] keyParameter = Utils._GetKeyParameter(invalidHandle, 9U); int num = (int)keyParameter[0] | (int)keyParameter[1] << 8 | (int)keyParameter[2] << 16 | (int)keyParameter[3] << 24; if (keyType == CspAlgorithmType.Rsa && num != 41984 && num != 9216 || keyType == CspAlgorithmType.Dss && num != 8704) { invalidHandle.Dispose(); throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_WrongKeySpec")); } safeKeyHandle = invalidHandle; }
[System.Security.SecurityCritical] // auto-generated private byte[] ExportHelper(X509ContentType contentType, object password) { switch (contentType) { case X509ContentType.Cert: break; #if FEATURE_CORECLR case (X509ContentType)0x02 /* X509ContentType.SerializedCert */: case (X509ContentType)0x03 /* X509ContentType.Pkcs12 */: throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_InvalidContentType"), new NotSupportedException()); #else // FEATURE_CORECLR case X509ContentType.SerializedCert: break; #if !FEATURE_PAL case X509ContentType.Pkcs12: KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Export); kp.Demand(); break; #endif // !FEATURE_PAL #endif // FEATURE_CORECLR else default: throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_InvalidContentType")); } #if !FEATURE_CORECLR IntPtr szPassword = IntPtr.Zero; byte[] encodedRawData = null; SafeCertStoreHandle safeCertStoreHandle = X509Utils.ExportCertToMemoryStore(this); RuntimeHelpers.PrepareConstrainedRegions(); try { szPassword = X509Utils.PasswordToHGlobalUni(password); encodedRawData = X509Utils._ExportCertificatesToBlob(safeCertStoreHandle, contentType, szPassword); } finally { if (szPassword != IntPtr.Zero) { Marshal.ZeroFreeGlobalAllocUnicode(szPassword); } safeCertStoreHandle.Dispose(); } if (encodedRawData == null) { throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_ExportFailed")); } return(encodedRawData); #else // !FEATURE_CORECLR return(RawData); #endif // !FEATURE_CORECLR }
internal byte[] SignHash(byte[] rgbHash, int calgHash) { this.GetKeyPair(); if (!this.CspKeyContainerInfo.RandomlyGenerated && !CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { KeyContainerPermission containerPermission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(this._parameters, KeyContainerPermissionFlags.Sign); containerPermission.AccessEntries.Add(accessEntry); containerPermission.Demand(); } return(Utils.SignValue(this._safeKeyHandle, this._parameters.KeyNumber, 9216, calgHash, rgbHash)); }
private static void DisplayPermissionMembers( KeyContainerPermission keyContainerPermParam, KeyContainerPermissionAccessEntry[] keyContainerPermAccEntryArrayParam) { KeyContainerPermission keyContainerPerm2 = keyContainerPermParam; KeyContainerPermissionAccessEntry[] keyContainerPermAccEntryArray = keyContainerPermAccEntryArrayParam; // Display the KeyContainerPermission properties. //<Snippet12> Console.WriteLine("\nFlags value is " + keyContainerPerm2.Flags.ToString()); //</Snippet12> //<Snippet14> KeyContainerPermission keyContainerPerm3 = (KeyContainerPermission)keyContainerPerm2.Copy(); Console.WriteLine("Is the copy equal to the original? " + keyContainerPerm3.Equals(keyContainerPerm2)); //</Snippet14> //<Snippet15> // Perform an XML roundtrip. keyContainerPerm3.FromXml(keyContainerPerm2.ToXml()); Console.WriteLine("Was the XML roundtrip successful? " + keyContainerPerm3.Equals(keyContainerPerm2)); //</Snippet15> KeyContainerPermission keyContainerPerm4 = new KeyContainerPermission(KeyContainerPermissionFlags.Open, keyContainerPermAccEntryArray); //<Snippet16> KeyContainerPermission keyContainerPerm5 = (KeyContainerPermission)keyContainerPerm2.Intersect( keyContainerPerm4); Console.WriteLine("Flags value after the intersection is " + keyContainerPerm5.Flags.ToString()); //</Snippet16> //<Snippet17> keyContainerPerm5 = (KeyContainerPermission)keyContainerPerm2.Union( keyContainerPerm4); //</Snippet17> //<Snippet18> Console.WriteLine("Flags value after the union is " + keyContainerPerm5.Flags.ToString()); //</Snippet18> //<Snippet19> Console.WriteLine("Is one permission a subset of the other? " + keyContainerPerm4.IsSubsetOf(keyContainerPerm2)); //</Snippet19> }
internal static void GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, bool randomKeyContainer, int dwKeySize, ref SafeProvHandle safeProvHandle, ref SafeKeyHandle safeKeyHandle) { SafeProvHandle hProv = CreateProvHandle(parameters, randomKeyContainer); if (parameters.CryptoKeySecurity != null) { KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.ChangeAcl); permission.AccessEntries.Add(accessEntry); permission.Demand(); SetKeySetSecurityInfo(hProv, parameters.CryptoKeySecurity, parameters.CryptoKeySecurity.ChangedAccessControlSections); } if (parameters.ParentWindowHandle != IntPtr.Zero) { SetProviderParameter(hProv, parameters.KeyNumber, 10, parameters.ParentWindowHandle); } else if (parameters.KeyPassword != null) { IntPtr pbData = Marshal.SecureStringToCoTaskMemAnsi(parameters.KeyPassword); try { SetProviderParameter(hProv, parameters.KeyNumber, 11, pbData); } finally { if (pbData != IntPtr.Zero) { Marshal.ZeroFreeCoTaskMemAnsi(pbData); } } } safeProvHandle = hProv; SafeKeyHandle invalidHandle = SafeKeyHandle.InvalidHandle; int hr = _GetUserKey(safeProvHandle, parameters.KeyNumber, ref invalidHandle); if (hr != 0) { if (((parameters.Flags & CspProviderFlags.UseExistingKey) != CspProviderFlags.NoFlags) || (hr != -2146893811)) { throw new CryptographicException(hr); } _GenerateKey(safeProvHandle, parameters.KeyNumber, parameters.Flags, dwKeySize, ref invalidHandle); } byte[] buffer = _GetKeyParameter(invalidHandle, 9); int num2 = ((buffer[0] | (buffer[1] << 8)) | (buffer[2] << 0x10)) | (buffer[3] << 0x18); if ((((keyType == CspAlgorithmType.Rsa) && (num2 != 0xa400)) && (num2 != 0x2400)) || ((keyType == CspAlgorithmType.Dss) && (num2 != 0x2200))) { invalidHandle.Dispose(); throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_WrongKeySpec")); } safeKeyHandle = invalidHandle; }