Code:
/ 4.0 / 4.0 / untmp / DEVDIV_TFS / Dev10 / Releases / RTMRel / ndp / cdf / src / WCF / IdentityModel / System / IdentityModel / SafeCryptHandles.cs / 1305376 / SafeCryptHandles.cs
//------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.IdentityModel
{
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Security.Cryptography;
using System.ServiceModel.Diagnostics;
using Microsoft.Win32.SafeHandles;
class SafeProvHandle : SafeHandleZeroOrMinusOneIsInvalid
{
SafeProvHandle() : base(true) { }
// 0 is an Invalid Handle
SafeProvHandle(IntPtr handle)
: base(true)
{
DiagnosticUtility.DebugAssert(handle == IntPtr.Zero, "SafeProvHandle constructor can only be called with IntPtr.Zero.");
SetHandle(handle);
}
internal static SafeProvHandle InvalidHandle
{
get { return new SafeProvHandle(IntPtr.Zero); }
}
protected override bool ReleaseHandle()
{
// PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call.
#pragma warning suppress 56523 // We are not interested in throwing an exception here if CloseHandle fails.
return NativeMethods.CryptReleaseContext(handle, 0);
}
}
class SafeKeyHandle : SafeHandleZeroOrMinusOneIsInvalid
{
SafeProvHandle provHandle = null;
SafeKeyHandle() : base(true) { }
// 0 is an Invalid Handle
SafeKeyHandle(IntPtr handle)
: base(true)
{
DiagnosticUtility.DebugAssert(handle == IntPtr.Zero, "SafeKeyHandle constructor can only be called with IntPtr.Zero.");
SetHandle(handle);
}
internal static SafeKeyHandle InvalidHandle
{
get { return new SafeKeyHandle(IntPtr.Zero); }
}
protected override bool ReleaseHandle()
{
// PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call.
#pragma warning suppress 56523 // We are not interested in throwing an exception here if CloseHandle fails.
bool ret = NativeMethods.CryptDestroyKey(handle);
if (this.provHandle != null)
{
this.provHandle.DangerousRelease();
this.provHandle = null;
}
return ret;
}
internal static unsafe SafeKeyHandle SafeCryptImportKey(SafeProvHandle provHandle, void* pbDataPtr, int cbData)
{
bool b = false;
int err = 0;
SafeKeyHandle keyHandle = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
provHandle.DangerousAddRef(ref b);
}
catch (Exception e)
{
if (b)
{
provHandle.DangerousRelease();
b = false;
}
if (!(e is ObjectDisposedException))
throw;
}
finally
{
if (b)
{
b = NativeMethods.CryptImportKey(provHandle, pbDataPtr, (uint)cbData, IntPtr.Zero, 0, out keyHandle);
if (!b)
{
err = Marshal.GetLastWin32Error();
provHandle.DangerousRelease();
}
else
{
// Take ownership of AddRef. Will Release at Close.
keyHandle.provHandle = provHandle;
}
}
}
if (!b)
{
Utility.CloseInvalidOutSafeHandle(keyHandle);
string reason = (err != 0) ? new Win32Exception(err).Message : String.Empty;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.AESCryptImportKeyFailed, reason)));
}
return keyHandle;
}
}
}
// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
Link Menu

This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- IteratorFilter.cs
- DataRow.cs
- TypeBuilder.cs
- LinqDataSource.cs
- TreeBuilder.cs
- DesignerSerializationOptionsAttribute.cs
- ConnectivityStatus.cs
- HttpServerChannel.cs
- DocumentViewerBase.cs
- DiscoveryServerProtocol.cs
- ObfuscateAssemblyAttribute.cs
- StoreContentChangedEventArgs.cs
- FacetChecker.cs
- GenericArgumentsUpdater.cs
- Application.cs
- _Rfc2616CacheValidators.cs
- TransformedBitmap.cs
- VersionedStreamOwner.cs
- QuaternionKeyFrameCollection.cs
- DataServicePagingProviderWrapper.cs
- ToolTipAutomationPeer.cs
- XmlWrappingReader.cs
- ControlCollection.cs
- StyleModeStack.cs
- MessageVersion.cs
- WorkflowRuntimeService.cs
- BuildProvider.cs
- SqlDependency.cs
- XPathParser.cs
- UIntPtr.cs
- MasterPageCodeDomTreeGenerator.cs
- InvokeMethodDesigner.xaml.cs
- RegexCaptureCollection.cs
- OperationResponse.cs
- ProfileManager.cs
- XamlWriter.cs
- WindowsFormsHostPropertyMap.cs
- ListViewContainer.cs
- RegexCode.cs
- NavigatorOutput.cs
- FileSystemInfo.cs
- SqlDataSourceCustomCommandPanel.cs
- MouseCaptureWithinProperty.cs
- InputBinding.cs
- ContractDescription.cs
- NameValuePermission.cs
- DSASignatureFormatter.cs
- WorkflowInspectionServices.cs
- TableAdapterManagerMethodGenerator.cs
- XmlUtf8RawTextWriter.cs
- CircleHotSpot.cs
- WebPartHeaderCloseVerb.cs
- InvokeBase.cs
- LogicalTreeHelper.cs
- PermissionSetEnumerator.cs
- TreeView.cs
- HyperLinkDesigner.cs
- GridViewItemAutomationPeer.cs
- UnsafeNativeMethods.cs
- BitHelper.cs
- Point3DCollectionValueSerializer.cs
- XmlSerializerAssemblyAttribute.cs
- Int16.cs
- PrincipalPermission.cs
- ItemList.cs
- Cursor.cs
- DPAPIProtectedConfigurationProvider.cs
- BaseCollection.cs
- PathFigureCollection.cs
- LineServices.cs
- AmbientValueAttribute.cs
- RegisteredExpandoAttribute.cs
- FloatUtil.cs
- DataGridTextColumn.cs
- FactoryId.cs
- OdbcDataAdapter.cs
- SecurityUtils.cs
- StreamInfo.cs
- GeometryDrawing.cs
- XPathNavigatorKeyComparer.cs
- ConnectionsZone.cs
- SQLMoneyStorage.cs
- ServerValidateEventArgs.cs
- VScrollBar.cs
- ListBindableAttribute.cs
- HandlerBase.cs
- KeyGestureConverter.cs
- X509CertificateStore.cs
- ObjectDataSource.cs
- DoubleAnimationBase.cs
- CodeDomLocalizationProvider.cs
- BlockCollection.cs
- SqlDeflator.cs
- ConfigurationConverterBase.cs
- Relationship.cs
- LocalBuilder.cs
- SecurityException.cs
- HttpWriter.cs
- TrustLevelCollection.cs
- UserThread.cs