Imported Upstream version 4.0.0~alpha1

Former-commit-id: 806294f5ded97629b74c85c09952f2a74fe182d9
This commit is contained in:
Jo Shields
2015-04-07 09:35:12 +01:00
parent 283343f570
commit 3c1f479b9d
22469 changed files with 2931443 additions and 869343 deletions

View File

@@ -0,0 +1,6 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("infocard, PublicKey=00000000000000000400000000000000")]
[assembly: InternalsVisibleTo("infocardsvc, PublicKey=00000000000000000400000000000000")]

View File

@@ -0,0 +1,89 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace Microsoft.InfoCards.Diagnostics
{
using System;
using System.Xml;
using System.Diagnostics;
//
// Summary
// An InfoCardTraceRecord represents an ETW tracerecord plus some infocard specific
// schema information. The class is called back by the diagnostics infrastructure through
// its WriteTo() method in order to serialize the infocard specific contents into the traceRecord structure.
// as part of a tracing request. the TraceRecord base class is repsonsible for embedding the correct headers etc.
//
// Trace records look like this:
//
//<TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Critical">
// <TraceIdentifier>StoreSignatureCollision</TraceIdentifier>
// <Description>rabbits</Description>
// <ResourceReference>http://schemas.microsoft.com/2004/03/System/AppDomain/{2bd64add-212d-4385-9f8e-6d9ab976c182}</ResourceReference>
// <ExtendedData xmlns="http://schemas.microsoft.com/2004/11/InfoCard/StoreSignatureCollisionTraceRecord">
// <message>rabbit%s</message>
// </ExtendedData>
//</TraceRecord>
//
class InfoCardTraceRecord : System.Runtime.Diagnostics.TraceRecord
{
//
// The eventID, a string representation of the traceCode. Normally something like
// 'StoreSignatureCollision' - used to derive the trace uri.
//
private string m_eventID;
//
// A descriptive message about the error schematized as xmlAny
//
private string m_message;
const string InfoCardEventIdBase = "http://schemas.microsoft.com/2004/11/InfoCard/";
public InfoCardTraceRecord( string eventID, string message )
{
InfoCardTrace.Assert( !String.IsNullOrEmpty( eventID ), "null eventid" );
InfoCardTrace.Assert( !String.IsNullOrEmpty( message ), "null message" );
m_eventID = eventID;
m_message = message;
}
//
// Summary:
// Returns the unique identifier for this event. Represented as a uri under the stanard e2e logging
// schema - configured as <uriPath> + <infocard event code> + <standard suffix>
// for example
// "http://schemas.microsoft.com/2004/11/InfoCard/" + "StoreSignatureCollision" + TraceRecord
//
internal override string EventId
{
get
{
return InfoCardEventIdBase + m_eventID + System.Runtime.Diagnostics.TraceRecord.NamespaceSuffix;
}
}
//
// Summary:
// Called back by the indigo diagnostic trace infrastructure during etw trace logging.
// Writes the extendedData section out to the TraceRecord.
//
//
internal override void WriteTo( XmlWriter writer )
{
InfoCardTrace.Assert( null != writer, "null writer" );
writer.WriteElementString( "message", m_message );
}
//
// Override tostring to give a better event logging experience.
//
public override string ToString()
{
return SR.GetString( SR.EventLogMessage, m_eventID, m_message );
}
}
}

View File

@@ -0,0 +1,135 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace Microsoft.InfoCards.Diagnostics
{
//
// Summary:
// Used to define the set of trace codes used by the infocard system. The codes
// are used in a couple of ways:
// 1) To uniquely identify the traces for use in the event log, etw traces etc.
// 2) To enable easy resource lookup - the intention is that code.ToString() maps
// directly to a resource identifier, allowing usage such as.
//
// IDT.TraceCritical( InfoCardTraceCode.ServiceInformation, "service started" );
// where the infocard.txt resource file contains the line
// ServiceInformation The following occured: %s
//
internal enum InfoCardTraceCode : int
{
//
// The component offsets in the enum array. Used to partition the eventid space also.
//
None = 0,
General = 5000,
Store = 10000,
UIAgent = 20000,
Engine = 30000,
Client = 40000,
Service = 50000,
//
// General enums. these all take a single string parameter.
//
GeneralInformation = General + 1,
//
// Store enums. The names are used doubly for string lookup into the resources.txt file.
//
StoreLoading = Store + 1,
StoreBeginTransaction,
StoreCommitTransaction,
StoreRollbackTransaction,
StoreClosing,
StoreFailedToOpenStore,
StoreSignatureNotValid,
StoreInvalidKey,
StoreDeleting,
//
// UIAgent enums.
//
AgentInfoCardSelected = UIAgent + 1,
AgentPiiDisclosed,
//
// Service enums.
//
//
// Client enums.
//
ClientInformation = Client + 1,
}
internal enum EventCode
{
//
// Audit codes
//
AUDIT_CARD_WRITTEN = 0x40050200,
AUDIT_CARD_DELETE = 0x40050201,
AUDIT_CARD_IMPORT = 0x40050202,
AUDIT_STORE_IMPORT = 0x40050203,
AUDIT_STORE_EXPORT = 0x40050204,
AUDIT_STORE_DELETE = 0x40050205,
AUDIT_SERVICE_IDLE_STOP = 0x40050206,
//
// Error codes
//
E_ICARD_COMMUNICATION = unchecked((int)0xC0050100),
E_ICARD_DATA_ACCESS = unchecked((int)0xC0050101),
E_ICARD_EXPORT = unchecked((int)0xC0050102),
E_ICARD_IDENTITY = unchecked((int)0xC0050103),
E_ICARD_IMPORT = unchecked((int)0xC0050104),
E_ICARD_ARGUMENT = unchecked((int)0xC0050105),
E_ICARD_REQUEST = unchecked((int)0xC0050106),
E_ICARD_INFORMATIONCARD = unchecked((int)0xC0050107),
E_ICARD_STOREKEY = unchecked((int)0xC0050108),
E_ICARD_LOGOVALIDATION = unchecked((int)0xC0050109), //also defined in agent\common.h
E_ICARD_PASSWORDVALIDATION = unchecked((int)0xC005010A),
E_ICARD_POLICY = unchecked((int)0xC005010B),
E_ICARD_PROCESSDIED = unchecked((int)0xC005010C),
E_ICARD_SERVICEBUSY = unchecked((int)0xC005010D),
E_ICARD_SERVICE = unchecked((int)0xC005010E),
E_ICARD_SHUTTINGDOWN = unchecked((int)0xC005010F),
E_ICARD_TOKENCREATION = unchecked((int)0xC0050110),
E_ICARD_TRUSTEXCHANGE = unchecked((int)0xC0050111),
E_ICARD_UNTRUSTED = unchecked((int)0xC0050112),
E_ICARD_USERCANCELLED = unchecked((int)0xC0050113),
E_ICARD_STORE_IMPORT = unchecked((int)0xC0050114),
E_ICARD_FAILEDUISTART = unchecked((int)0xC0050115),
E_ICARD_UNSUPPORTED = unchecked((int)0xC0050116),
E_ICARD_MAXSESSIONCOUNT = unchecked((int)0xC0050117),
E_ICARD_FILE_ACCESS = unchecked((int)0xC0050118),
E_ICARD_MALFORMED_REQUEST = unchecked((int)0xC0050119),
E_ICARD_UI_INITIALIZATION = unchecked((int)0xC005011A), // also defined in agent\common.h
//
// Trust exchange messages returned from the ip sts.
//
E_ICARD_REFRESH_REQUIRED = unchecked((int)0xC0050180),
E_ICARD_MISSING_APPLIESTO = unchecked((int)0xC0050181),
E_ICARD_INVALID_PROOF_KEY = unchecked((int)0xC0050182),
E_ICARD_UNKNOWN_REFERENCE = unchecked((int)0xC0050183),
E_ICARD_FAILED_REQUIRED_CLAIMS = unchecked((int)0xC0050184),
//
// Events that we reuse from other places.
//
E_INVALIDARG = unchecked((int)0x80000003),
E_OUTOFMEMORY = unchecked((int)0x8007000E),
SCARD_W_CANCELLED_BY_USER = unchecked((int)0x8010006E),
}
internal enum InfoCardEventCategory : short
{
General = 1
}
}

View File

@@ -0,0 +1,41 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.IdentityModel.Selectors
{
using System;
using System.Runtime.InteropServices;
using System.Threading;
using IDT = Microsoft.InfoCards.Diagnostics.InfoCardTrace;
//
// For common & resources
//
using Microsoft.InfoCards;
//
// Summary:
// Wraps an AsymmetricCryptoSession.
//
internal class AsymmetricCryptoHandle : ProofTokenCryptoHandle
{
public AsymmetricCryptoHandle(InternalRefCountedHandle nativeHandle, DateTime expiration, IntPtr parameters)
: base(nativeHandle, expiration, parameters, typeof(RpcAsymmetricCryptoParameters))
{
}
private AsymmetricCryptoHandle(InternalRefCountedHandle internalHandle) : base(internalHandle) { }
protected override CryptoHandle OnDuplicate()
{
return new AsymmetricCryptoHandle(InternalHandle);
}
protected override InfoCardProofToken OnCreateProofToken()
{
return new InfoCardProofToken(this, Expiration);
}
}
}

View File

@@ -0,0 +1,86 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.IdentityModel.Selectors
{
using System;
using System.Runtime.Serialization;
using Microsoft.InfoCards.Diagnostics;
using IDT = Microsoft.InfoCards.Diagnostics.InfoCardTrace;
using Microsoft.InfoCards;
internal static class ExceptionHelper
{
public static void ThrowIfCardSpaceException(int status)
{
switch (status)
{
case (int)EventCode.E_ICARD_COMMUNICATION:
throw IDT.ThrowHelperError(new CardSpaceException(SR.GetString(SR.ClientAPIInfocardError)));
case (int)EventCode.E_ICARD_USERCANCELLED:
throw IDT.ThrowHelperError(new UserCancellationException(SR.GetString(SR.ClientAPIUserCancellationError)));
case (int)EventCode.E_ICARD_SERVICE:
throw IDT.ThrowHelperError(new ServiceNotStartedException(SR.GetString(SR.ClientAPIServiceNotStartedError)));
case (int)EventCode.E_ICARD_UNTRUSTED:
throw IDT.ThrowHelperError(new UntrustedRecipientException(SR.GetString(SR.ClientAPIUntrustedRecipientError)));
case (int)EventCode.E_ICARD_TRUSTEXCHANGE:
throw IDT.ThrowHelperError(new StsCommunicationException(SR.GetString(SR.ClientStsCommunicationException)));
case (int)EventCode.E_ICARD_IDENTITY:
throw IDT.ThrowHelperError(new IdentityValidationException(SR.GetString(SR.ClientAPIInvalidIdentity)));
case (int)EventCode.E_ICARD_SERVICEBUSY:
throw IDT.ThrowHelperError(new ServiceBusyException(SR.GetString(SR.ClientAPIServiceBusy)));
case (int)EventCode.E_ICARD_POLICY:
throw IDT.ThrowHelperError(new PolicyValidationException(SR.GetString(SR.ClientAPIInvalidPolicy)));
case (int)EventCode.E_ICARD_UNSUPPORTED:
throw IDT.ThrowHelperError(new UnsupportedPolicyOptionsException(SR.GetString(SR.ClientAPIUnsupportedPolicyOptions)));
case (int)EventCode.E_ICARD_UI_INITIALIZATION:
throw IDT.ThrowHelperError(new UIInitializationException(SR.GetString(SR.ClientAPIUIInitializationFailed)));
case (int)EventCode.E_ICARD_IMPORT:
throw IDT.ThrowHelperError(new CardSpaceException(SR.GetString(SR.ClientAPICannotImport)));
default:
//
// In current implementation, caller will determine what to do in the default case.
//
break;
}
}
}
//
// Summary
// Generic Infocard Exception class used to indicate failures in teh Infocard system
//
[Serializable]
public class CardSpaceException : System.Exception
{
public CardSpaceException()
: base()
{
}
public CardSpaceException(string message)
: base(message)
{
}
public CardSpaceException(string message, Exception innerException)
: base(message, innerException)
{
}
protected CardSpaceException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
}

View File

@@ -0,0 +1,86 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.IdentityModel.Selectors
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Xml;
using IDT = Microsoft.InfoCards.Diagnostics.InfoCardTrace;
//
// Summary:
// This is the managed representation of the native POLICY_ELEMENT struct.
//
public class CardSpacePolicyElement
{
XmlElement m_target;
XmlElement m_issuer;
Collection<XmlElement> m_parameters;
Uri m_policyNoticeLink;
int m_policyNoticeVersion;
bool m_isManagedIssuer;
public bool IsManagedIssuer
{
get { return m_isManagedIssuer; }
set { m_isManagedIssuer = value; }
}
public XmlElement Target
{
get { return m_target; }
set { m_target = value; }
}
public XmlElement Issuer
{
get { return m_issuer; }
set { m_issuer = value; }
}
public Collection<XmlElement> Parameters
{
get { return m_parameters; }
// set { m_parameters = value; }
}
public Uri PolicyNoticeLink
{
get { return m_policyNoticeLink; }
set { m_policyNoticeLink = value; }
}
public int PolicyNoticeVersion
{
get { return m_policyNoticeVersion; }
set { m_policyNoticeVersion = value; }
}
//
// Parameters:
// target - The target of the token being described.
// parameters - describes the type of token required by the target.
//
public CardSpacePolicyElement(XmlElement target, XmlElement issuer, Collection<XmlElement> parameters, Uri privacyNoticeLink, int privacyNoticeVersion, bool isManagedIssuer)
{
//
// Ensure that if a version is specified( value != 0 ), that a valid url is specified.
//
IDT.ThrowInvalidArgumentConditional(0 == privacyNoticeVersion && null != privacyNoticeLink, "privacyNoticeVersion");
IDT.ThrowInvalidArgumentConditional(0 != privacyNoticeVersion && null == privacyNoticeLink, "privacyNoticeLink");
m_target = target;
m_issuer = issuer;
m_parameters = parameters;
m_policyNoticeLink = privacyNoticeLink;
m_policyNoticeVersion = privacyNoticeVersion;
m_isManagedIssuer = isManagedIssuer;
}
}
}

View File

@@ -0,0 +1,377 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
//
// Presharp uses the c# pragma mechanism to supress its warnings.
// These are not recognised by the base compiler so we need to explictly
// disable the following warnings. See http://winweb/cse/Tools/PREsharp/userguide/default.asp
// for details.
//
#pragma warning disable 1634, 1691 // unknown message, unknown pragma
namespace System.IdentityModel.Selectors
{
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.IdentityModel.Claims;
using System.Text;
using System.Xml;
using System.IdentityModel.Tokens;
using System.ServiceProcess;
using System.Globalization;
using System.Runtime.ConstrainedExecution;
using System.Runtime.CompilerServices;
using Microsoft.InfoCards.Diagnostics;
using Microsoft.Win32;
using IDT = Microsoft.InfoCards.Diagnostics.InfoCardTrace;
//
// For common & resources
//
using Microsoft.InfoCards;
//
// Summary
// This structure is the native version of the GenericXmlSecurityToken
//
// Remark
// When adding new fields to this structure, add pointers to the end to make
// sure that alignment is done correctly
//
[StructLayout(LayoutKind.Sequential)]
struct RpcGenericXmlToken
{
public Int64 createDate; // Date the token was created on
public Int64 expiryDate; // Date the token will expire on
[MarshalAs(UnmanagedType.LPWStr)]
public string xmlToken; // Token
[MarshalAs(UnmanagedType.LPWStr)]
public string internalTokenReference; // Internal Token reference
[MarshalAs(UnmanagedType.LPWStr)]
public string externalTokenReference; // External Token reference
}
//
// Summary
// This class implements the client API for the Infocard system
//
public static class CardSpaceSelector
{
static CardSpaceShim s_cardSpaceShim = new CardSpaceShim();
//
// The default quotas we apply to incoming xml messages
//
private static XmlDictionaryReaderQuotas DefaultQuotas = new XmlDictionaryReaderQuotas();
//
// Used by infocard.exe as well.
//
internal const int MaxPolicyChainLength = 50;
static CardSpaceSelector()
{
//
// Quotas for xml readers
//
DefaultQuotas.MaxDepth = 32; // max depth of elements
DefaultQuotas.MaxStringContentLength = 8192; // maximum string read
DefaultQuotas.MaxArrayLength = 20 * 1024 * 1024; // maximum byte array
DefaultQuotas.MaxBytesPerRead = 4096; // max start element tag
DefaultQuotas.MaxNameTableCharCount = 16384; // max size of name table
}
// Summary
// Request a security token from the infocard system
//
// Parameters
// endPoint - The token recipient end point.
// policy - Policy stating the requirements for the token.
// requiredRemoteTokenIssuer - The returned token should be issued by this
// specific issuer.
//
public static GenericXmlSecurityToken GetToken(XmlElement endpoint,
IEnumerable<XmlElement> policy,
XmlElement requiredRemoteTokenIssuer,
SecurityTokenSerializer tokenSerializer)
{
if (null == endpoint)
{
throw IDT.ThrowHelperArgumentNull("endpoint");
}
if (null == policy)
{
throw IDT.ThrowHelperArgumentNull("policy");
}
if (null == tokenSerializer)
{
throw IDT.ThrowHelperArgumentNull("tokenSerializer");
}
Collection<XmlElement> policyCollection = new Collection<XmlElement>();
foreach (XmlElement element in policy)
{
policyCollection.Add(element);
}
return GetToken(new CardSpacePolicyElement[] { new CardSpacePolicyElement(endpoint, requiredRemoteTokenIssuer, policyCollection, null, 0, false) }, tokenSerializer);
}
// Summary
// Request a security token from the infocard system
//
// Parameters
// policyChain - an array of PolicyElements that describe the federated security chain that the client
// needs a final token to unwind.
//
public static GenericXmlSecurityToken GetToken(CardSpacePolicyElement[] policyChain, SecurityTokenSerializer tokenSerializer)
{
IDT.TraceDebug("ICARDCLIENT: GetToken called with a policy chain of length {0}", policyChain.Length);
InfoCardProofToken proofToken = null;
InternalRefCountedHandle nativeCryptoHandle = null;
GenericXmlSecurityToken token = null;
RpcGenericXmlToken infocardToken = new RpcGenericXmlToken();
SafeTokenHandle nativeToken = null;
Int32 result = 0;
if (null == policyChain || 0 == policyChain.Length)
{
throw IDT.ThrowHelperArgumentNull("policyChain");
}
if (null == tokenSerializer)
{
throw IDT.ThrowHelperArgumentNull("tokenSerializer");
}
if (null == tokenSerializer)
{
throw IDT.ThrowHelperArgumentNull("tokenSerializer");
}
try
{
RuntimeHelpers.PrepareConstrainedRegions();
bool mustRelease = false;
try
{
}
finally
{
//
// The PolicyChain class will do the marshalling and native buffer management for us.
//
try
{
using (PolicyChain tmpChain = new PolicyChain(policyChain))
{
IDT.TraceDebug("ICARDCLIENT: PInvoking the native GetToken call");
result = GetShim().m_csShimGetToken(
tmpChain.Length,
tmpChain.DoMarshal(),
out nativeToken,
out nativeCryptoHandle);
}
if (0 == result)
{
IDT.TraceDebug("ICARDCLIENT: The PInvoke of GetToken succeeded");
nativeToken.DangerousAddRef(ref mustRelease);
infocardToken = (RpcGenericXmlToken)Marshal.PtrToStructure(
nativeToken.DangerousGetHandle(),
typeof(RpcGenericXmlToken));
}
}
finally
{
if (mustRelease)
{
nativeToken.DangerousRelease();
}
}
}
if (0 == result)
{
using (ProofTokenCryptoHandle crypto =
(ProofTokenCryptoHandle)CryptoHandle.Create(nativeCryptoHandle))
{
proofToken = crypto.CreateProofToken();
}
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(infocardToken.xmlToken);
SecurityKeyIdentifierClause internalTokenReference = null;
if (null != infocardToken.internalTokenReference)
{
internalTokenReference = tokenSerializer.ReadKeyIdentifierClause(
CreateReaderWithQuotas(infocardToken.internalTokenReference));
}
SecurityKeyIdentifierClause externalTokenReference = null;
if (null != infocardToken.externalTokenReference)
{
externalTokenReference = tokenSerializer.ReadKeyIdentifierClause(
CreateReaderWithQuotas(infocardToken.externalTokenReference));
}
IDT.TraceDebug("ICARDCLIENT: Constructing a new GenericXmlSecurityToken");
token = new GenericXmlSecurityToken(
xmlDoc.DocumentElement,
proofToken,
DateTime.FromFileTimeUtc(infocardToken.createDate),
DateTime.FromFileTimeUtc(infocardToken.expiryDate),
internalTokenReference,
externalTokenReference,
null);
}
else
{
IDT.TraceDebug("ICARDCLIENT: The PInvoke of GetToken failed with a return code of {0}", result);
//
// Convert the HRESULTS to exceptions
//
ExceptionHelper.ThrowIfCardSpaceException((int)result);
throw IDT.ThrowHelperError(new CardSpaceException(SR.GetString(SR.ClientAPIInfocardError)));
}
}
catch
{
if (null != nativeCryptoHandle)
{
nativeCryptoHandle.Dispose();
}
if (null != proofToken)
{
proofToken.Dispose();
}
throw;
}
finally
{
if (null != nativeToken)
{
nativeToken.Dispose();
}
}
return token;
}
//
// Summary
// Start the management user interface
//
public static void Manage()
{
Int32 result = CardSpaceSelector.GetShim().m_csShimManageCardSpace();
//
// Convert HRESULTS to errors
//
if (0 != result)
{
//
// Convert the HRESULTS to exceptions
//
ExceptionHelper.ThrowIfCardSpaceException((int)result);
throw IDT.ThrowHelperError(new CardSpaceException(SR.GetString(SR.ClientAPIInfocardError)));
}
}
//
// Summary
// Start the import card user interface
//
public static void Import(string fileName)
{
if (String.IsNullOrEmpty(fileName))
{
throw IDT.ThrowHelperArgumentNull("fileName");
}
IDT.TraceDebug("Import Infocard has been called");
Int32 result = CardSpaceSelector.GetShim().m_csShimImportInformationCard(fileName);
//
// Convert HRESULTS to errors
//
if (0 != result)
{
//
// Convert the HRESULTS to exceptions
//
ExceptionHelper.ThrowIfCardSpaceException((int)result);
throw IDT.ThrowHelperError(new CardSpaceException(SR.GetString(SR.ClientAPIInfocardError)));
}
}
internal static CardSpaceShim GetShim()
{
s_cardSpaceShim.InitializeIfNecessary();
return s_cardSpaceShim;
}
//
// Summary
// Convert the XML data to a string
//
// Parameter
// xml - The xml data to be converted into a string
//
// Returns
// A string format of the XML
//
internal static string XmlToString(IEnumerable<XmlElement> xml)
{
StringBuilder builder = new StringBuilder();
foreach (XmlElement element in xml)
{
if (null == element)
{
throw IDT.ThrowHelperError(new ArgumentException(SR.GetString(SR.ClientAPIInvalidPolicy)));
}
builder.Append(element.OuterXml);
}
return builder.ToString();
}
private static XmlDictionaryReader CreateReaderWithQuotas(string root)
{
UTF8Encoding utf8 = new UTF8Encoding();
byte[] rootbytes = utf8.GetBytes(root);
return XmlDictionaryReader.CreateTextReader(
rootbytes, 0, rootbytes.GetLength(0), null, DefaultQuotas, null);
}
}
}

View File

@@ -0,0 +1,443 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.IdentityModel.Selectors
{
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.IdentityModel.Claims;
using System.Text;
using System.Xml;
using System.IdentityModel.Tokens;
using System.ServiceProcess;
using System.Globalization;
using System.Runtime.ConstrainedExecution;
using System.Runtime.CompilerServices;
using Microsoft.InfoCards.Diagnostics;
using Microsoft.Win32;
using System.Text.RegularExpressions;
using IDT = Microsoft.InfoCards.Diagnostics.InfoCardTrace;
//
// For common & resources
//
using Microsoft.InfoCards;
using System.Security;
//
// Summary:
// If v2 is installed, this class will route calls to the native dll that was installed with v2.
// This class essentially mimics the behavior in CSD Main 58552 which has been checked into the .Net branch for Win7
//
class CardSpaceShim
{
private const string REDIRECT_DLL_REG_KEY = @"software\microsoft\cardspace\v1";
private const string REDIRECT_DLL_IMPLEMENTATION_VALUE = "ImplementationDLL";
private const string REDIRECT_DLL_IMPLEMENTATION_VALUE_DEFAULT = "infocardapi2";
private const string REDIRECT_DLL_CARDSPACE_V1 = "infocardapi";
private object m_syncRoot = new Object();
private bool m_isInitialized = false;
//
// Delegates defined as public for convenience in invocation
//
public CsV2ManageCardSpace m_csShimManageCardSpace;
public CsV2GetToken m_csShimGetToken;
public CsV2ImportInformationCard m_csShimImportInformationCard;
public CsV2Encrypt m_csShimEncrypt;
public CsV2Decrypt m_csShimDecrypt;
public CsV2SignHash m_csShimSignHash;
public CsV2VerifyHash m_csShimVerifyHash;
public CsV2GenerateDerivedKey m_csShimGenerateDerivedKey;
public CsV2GetCryptoTransform m_csShimGetCryptoTransform;
public CsV2TransformBlock m_csShimTransformBlock;
public CsV2TransformFinalBlock m_csShimTransformFinalBlock;
public CsV2GetKeyedHash m_csShimGetKeyedHash;
public CsV2HashCore m_csShimHashCore;
public CsV2HashFinal m_csShimHashFinal;
public CsV2FreeToken m_csShimFreeToken;
public CsV2CloseCryptoHandle m_csShimCloseCryptoHandle;
SafeLibraryHandle m_implementationDll;
//
// GetBrowserToken not required because that is accomplished via Pheonix bit etc. (not exposed thru
// managed interface).
//
//
// Summary:
// Performs initialization of the CardSpaceShim if necessary.
// The v1 service will only allow one request from the user,
// however locking anyway in case we change our behavior in v2.
//
public void InitializeIfNecessary()
{
if (!m_isInitialized)
{
lock (m_syncRoot)
{
if (!m_isInitialized)
{
string implDllPath = GetCardSpaceImplementationDll();
m_implementationDll = SafeLibraryHandle.LoadLibraryW(implDllPath);
if (m_implementationDll.IsInvalid)
{
throw NativeMethods.ThrowWin32ExceptionWithContext(new Win32Exception(), implDllPath);
}
try
{
//
// Functions are listed in alphabetical order
//
IntPtr procaddr1 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "CloseCryptoHandle");
m_csShimCloseCryptoHandle =
(CsV2CloseCryptoHandle)Marshal.GetDelegateForFunctionPointer(
procaddr1, typeof(CsV2CloseCryptoHandle));
IntPtr procaddr2 = NativeMethods.GetProcAddressWrapper(
m_implementationDll, "Decrypt");
m_csShimDecrypt =
(CsV2Decrypt)Marshal.GetDelegateForFunctionPointer(
procaddr2, typeof(CsV2Decrypt));
IntPtr procaddr3 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "Encrypt");
m_csShimEncrypt =
(CsV2Encrypt)Marshal.GetDelegateForFunctionPointer(
procaddr3, typeof(CsV2Encrypt));
IntPtr procaddr4 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "FreeToken");
m_csShimFreeToken =
(CsV2FreeToken)Marshal.GetDelegateForFunctionPointer(
procaddr4, typeof(CsV2FreeToken));
IntPtr procaddr5 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "GenerateDerivedKey");
m_csShimGenerateDerivedKey =
(CsV2GenerateDerivedKey)Marshal.GetDelegateForFunctionPointer(
procaddr5, typeof(CsV2GenerateDerivedKey));
IntPtr procaddr6 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "GetCryptoTransform");
m_csShimGetCryptoTransform =
(CsV2GetCryptoTransform)Marshal.GetDelegateForFunctionPointer(
procaddr6, typeof(CsV2GetCryptoTransform));
IntPtr procaddr7 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "GetKeyedHash");
m_csShimGetKeyedHash =
(CsV2GetKeyedHash)Marshal.GetDelegateForFunctionPointer(
procaddr7, typeof(CsV2GetKeyedHash));
IntPtr procaddr8 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "GetToken");
m_csShimGetToken =
(CsV2GetToken)Marshal.GetDelegateForFunctionPointer(
procaddr8, typeof(CsV2GetToken));
IntPtr procaddr9 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "HashCore");
m_csShimHashCore =
(CsV2HashCore)Marshal.GetDelegateForFunctionPointer(
procaddr9, typeof(CsV2HashCore));
IntPtr procaddr10 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "HashFinal");
m_csShimHashFinal =
(CsV2HashFinal)Marshal.GetDelegateForFunctionPointer(
procaddr10, typeof(CsV2HashFinal));
IntPtr procaddr11 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "ImportInformationCard");
m_csShimImportInformationCard =
(CsV2ImportInformationCard)Marshal.GetDelegateForFunctionPointer(
procaddr11, typeof(CsV2ImportInformationCard));
IntPtr procaddr12 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "ManageCardSpace");
m_csShimManageCardSpace =
(CsV2ManageCardSpace)Marshal.GetDelegateForFunctionPointer(
procaddr12, typeof(CsV2ManageCardSpace));
IntPtr procaddr13 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "SignHash");
m_csShimSignHash =
(CsV2SignHash)Marshal.GetDelegateForFunctionPointer(
procaddr13, typeof(CsV2SignHash));
IntPtr procaddr14 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "TransformBlock");
m_csShimTransformBlock =
(CsV2TransformBlock)Marshal.GetDelegateForFunctionPointer(
procaddr14, typeof(CsV2TransformBlock));
IntPtr procaddr15 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "TransformFinalBlock");
m_csShimTransformFinalBlock =
(CsV2TransformFinalBlock)Marshal.GetDelegateForFunctionPointer(
procaddr15, typeof(CsV2TransformFinalBlock));
IntPtr procaddr16 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "VerifyHash");
m_csShimVerifyHash =
(CsV2VerifyHash)Marshal.GetDelegateForFunctionPointer(
procaddr16, typeof(CsV2VerifyHash));
}
catch (Win32Exception)
{
//
// NB: IDT.ThrowHelperError would have logged for the Win32Exception
//
IDT.Assert(!m_isInitialized, "If an exception occurred, we expect this to be false");
throw;
}
m_isInitialized = true;
}
}
}
}
//
// Summary:
// Returns true if fileName has only alphanumeric characters
//
bool IsSafeFile(string fileName)
{
//
// If any match from outside the range of [A-Za-z0-9] then we will not use this file
//
return Regex.IsMatch(fileName, "^[A-Za-z0-9]+$");
}
//
// Summary:
// Return the path to the v2 (or a version above v2) implementation dll.
// We expect this to be infocardapi2.dll unless overriden by a registry key
//
// Remarks: It is left upto the caller to check if the v2+ implementation
// dll actually exists or not.
//
private string GetV2ImplementationDllPath()
{
string v2AndAboveImplementationDll = String.Empty;
//
// First look in the registry key to see if this is defined
//
using (RegistryKey implDllKey = Registry.LocalMachine.OpenSubKey(REDIRECT_DLL_REG_KEY))
{
if (null != implDllKey)
{
v2AndAboveImplementationDll = (string)implDllKey.GetValue(REDIRECT_DLL_IMPLEMENTATION_VALUE);
if (!String.IsNullOrEmpty(v2AndAboveImplementationDll))
{
string v2RegPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.System),
v2AndAboveImplementationDll + ".dll");
//
// Is the filename safe (use alphanumeric like the CSD Main 58552). Does it exist?
// If not, discard the registry key we just read.
//
if (!IsSafeFile(v2AndAboveImplementationDll) || !File.Exists(v2RegPath))
{
v2AndAboveImplementationDll = String.Empty;
}
}
}
}
//
// If reg key was not found or not safe, or value was not found, or found to be empty,
// then use the default of infocardapi2.dll
//
if (String.IsNullOrEmpty(v2AndAboveImplementationDll))
{
v2AndAboveImplementationDll = REDIRECT_DLL_IMPLEMENTATION_VALUE_DEFAULT;
}
IDT.Assert(!String.IsNullOrEmpty(v2AndAboveImplementationDll), "v2AndAboveImplementationDll should not be empty");
//
// Get the full path to the v2Above dll
//
return Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.System),
v2AndAboveImplementationDll + ".dll");
}
//
// Summary:
// Return handle to the CardSpace implementation dll.
// We will first check to see if a v2 (or above) redirection dll has been installed.
// If not we will check to see if the v1 infocardapi.dll is installed.
// If that's not found as well, an exception is thrown
//
private string GetCardSpaceImplementationDll()
{
string implDllFullPath = GetV2ImplementationDllPath();
if (!File.Exists(implDllFullPath))
{
//
// Choose infocardapi.dll, if v2+ dll does not exist
//
implDllFullPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.System),
REDIRECT_DLL_CARDSPACE_V1 + ".dll");
if (!File.Exists(implDllFullPath))
{
//
// If this does not exist either, then even CardSpace v1 is NOT installed
// on this machine. Note: Throwing an exception using IDT.ThrowHelperError
// does not log to event log unless it derives from InfoCardBaseException.
// This seems fine given that we don't want to be logging as "CardSpace X.0.0.0",
// rather we'll let the client application log to event log if desired.
//
throw IDT.ThrowHelperError(
new CardSpaceException(SR.GetString(SR.ClientAPIServiceNotInstalledError)));
}
}
return implDllFullPath;
}
//
// Delegate definitions ported from NativeMethods.cs
//
internal delegate System.Int32 CsV2ManageCardSpace();
//[ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )]
internal delegate System.Int32 CsV2GetToken(
int cPolicyChain,
SafeHandle pPolicyChain,
out SafeTokenHandle securityToken,
out InternalRefCountedHandle pCryptoHandle);
internal delegate System.Int32 CsV2ImportInformationCard(
[MarshalAs(UnmanagedType.LPWStr)]
string nativeFileName);
//[ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )]
internal delegate int CsV2Encrypt(
InternalRefCountedHandle nativeCryptoHandle,
bool fOAEP,
[MarshalAs(UnmanagedType.U4)]
int cbInData,
SafeHandle pInData,
[MarshalAs(UnmanagedType.U4)]
out int pcbOutData,
out GlobalAllocSafeHandle pOutData);
//[ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )]
internal delegate int CsV2Decrypt(
InternalRefCountedHandle nativeCryptoHandle,
bool fOAEP,
[MarshalAs(UnmanagedType.U4)]
int cbInData,
SafeHandle pInData,
[MarshalAs(UnmanagedType.U4)]
out int pcbOutData,
out GlobalAllocSafeHandle pOutData);
//[ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )]
internal delegate int CsV2SignHash(
InternalRefCountedHandle nativeCryptoHandle,
[MarshalAs(UnmanagedType.U4)]
int cbHash,
SafeHandle pInData,
SafeHandle pHashAlgOid,
[MarshalAs(UnmanagedType.U4)]
out int pcbSig,
out GlobalAllocSafeHandle pSig);
//[ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )]
internal delegate int CsV2VerifyHash(
InternalRefCountedHandle nativeCryptoHandle,
[MarshalAs(UnmanagedType.U4)]
int cbHash,
SafeHandle pInData,
SafeHandle pHashAlgOid,
[MarshalAs(UnmanagedType.U4)]
int pcbSig,
SafeHandle pSig,
out bool verified);
//[ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )]
internal delegate int CsV2GenerateDerivedKey(InternalRefCountedHandle nativeCryptoHandle,
int cbLabel,
SafeHandle pLabel,
int cbNonce,
SafeHandle pNonce,
int derivedKeyLength,
int offset,
[MarshalAs(UnmanagedType.LPWStr)]
string derivationAlgUri,
out int cbDerivedKey,
out GlobalAllocSafeHandle pDerivedKey);
//[ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )]
internal delegate int CsV2GetCryptoTransform(
InternalRefCountedHandle nativeCryptoHandle,
int mode,
int padding,
int feedbackSize,
int direction,
int cbIV,
SafeHandle pIV,
out InternalRefCountedHandle nativeTransformHandle);
//[ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )]
internal delegate int CsV2TransformBlock(InternalRefCountedHandle nativeCryptoHandle,
int cbInData,
SafeHandle pInData,
out int cbOutData,
out GlobalAllocSafeHandle pOutData);
//[ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )]
internal delegate int CsV2TransformFinalBlock(InternalRefCountedHandle nativeCryptoHandle,
int cbInData,
SafeHandle pInData,
out int cbOutData,
out GlobalAllocSafeHandle pOutData);
//[ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )]
internal delegate int CsV2GetKeyedHash(
InternalRefCountedHandle nativeCryptoHandle,
out InternalRefCountedHandle nativeHashHandle);
//[ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )]
internal delegate int CsV2HashCore(InternalRefCountedHandle nativeCryptoHandle,
int cbInData,
SafeHandle pInData);
//[ReliabilityContract( Consistency.WillNotCorruptState, Cer.MayFail )]
internal delegate int CsV2HashFinal(InternalRefCountedHandle nativeCryptoHandle,
int cbInData,
SafeHandle pInData,
out int cbOutData,
out GlobalAllocSafeHandle pOutData);
[SuppressUnmanagedCodeSecurity]
//[ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
internal delegate bool CsV2CloseCryptoHandle([In] IntPtr hKey);
[SuppressUnmanagedCodeSecurity]
//[ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )]
internal delegate System.Int32 CsV2FreeToken([In] IntPtr token);
}
}

View File

@@ -0,0 +1,279 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
//
// Presharp uses the c# pragma mechanism to supress its warnings.
// These are not recognised by the base compiler so we need to explictly
// disable the following warnings. See http://winweb/cse/Tools/PREsharp/userguide/default.asp
// for details.
//
#pragma warning disable 1634, 1691 // unknown message, unknown pragma
namespace System.IdentityModel.Selectors
{
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Security;
using System.Runtime.ConstrainedExecution;
using System.Runtime.CompilerServices;
using IDT = Microsoft.InfoCards.Diagnostics.InfoCardTrace;
//
// For common & resources
//
using Microsoft.InfoCards;
//
// Summary:
// Wraps and manages the lifetime of a native crypto handle passed back from the native InfoCard API.
//
internal abstract class CryptoHandle : IDisposable
{
bool m_isDisposed;
InternalRefCountedHandle m_internalHandle;
//
// Summary:
// Creates a new CryptoHandle. ParamType has information as to what
// nativeParameters has to be marshaled into.
//
protected CryptoHandle(InternalRefCountedHandle nativeHandle, DateTime expiration, IntPtr nativeParameters, Type paramType)
{
m_internalHandle = nativeHandle;
m_internalHandle.Initialize(expiration, Marshal.PtrToStructure(nativeParameters, paramType));
}
//
// Summary:
// This constructor creates a new CryptoHandle instance with the same InternalRefCountedHandle and adds
// a ref count to that InternalRefCountedHandle.
//
protected CryptoHandle(InternalRefCountedHandle internalHandle)
{
m_internalHandle = internalHandle;
m_internalHandle.AddRef();
}
public InternalRefCountedHandle InternalHandle
{
get
{
ThrowIfDisposed();
return m_internalHandle;
}
}
public DateTime Expiration
{
get
{
ThrowIfDisposed();
return m_internalHandle.Expiration;
}
}
public object Parameters
{
get
{
ThrowIfDisposed();
return m_internalHandle.Parameters;
}
}
//
// Summary:
// Creates a new CryptoHandle with same InternalRefCountedCryptoHandle.
//
public CryptoHandle Duplicate()
{
ThrowIfDisposed();
return OnDuplicate();
}
//
// Summary:
// Allows subclasses to create a duplicate of their particular class.
//
protected abstract CryptoHandle OnDuplicate();
protected void ThrowIfDisposed()
{
if (m_isDisposed)
{
throw IDT.ThrowHelperError(new ObjectDisposedException(SR.GetString(SR.ClientCryptoSessionDisposed)));
}
}
public void Dispose()
{
if (m_isDisposed)
{
return;
}
m_internalHandle.Release();
m_internalHandle = null;
m_isDisposed = true;
}
//
// Summary:
// Given a pointer to a native cryptosession this method creates the appropriate CryptoHandle type.
//
static internal CryptoHandle Create(InternalRefCountedHandle nativeHandle)
{
CryptoHandle handle = null;
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
nativeHandle.DangerousAddRef(ref mustRelease);
RpcInfoCardCryptoHandle hCrypto =
(RpcInfoCardCryptoHandle)Marshal.PtrToStructure(nativeHandle.DangerousGetHandle(),
typeof(RpcInfoCardCryptoHandle));
DateTime expiration = DateTime.FromFileTimeUtc(hCrypto.expiration);
switch (hCrypto.type)
{
case RpcInfoCardCryptoHandle.HandleType.Asymmetric:
handle = new AsymmetricCryptoHandle(nativeHandle, expiration, hCrypto.cryptoParameters);
break;
case RpcInfoCardCryptoHandle.HandleType.Symmetric:
handle = new SymmetricCryptoHandle(nativeHandle, expiration, hCrypto.cryptoParameters);
break;
case RpcInfoCardCryptoHandle.HandleType.Transform:
handle = new TransformCryptoHandle(nativeHandle, expiration, hCrypto.cryptoParameters);
break;
case RpcInfoCardCryptoHandle.HandleType.Hash:
handle = new HashCryptoHandle(nativeHandle, expiration, hCrypto.cryptoParameters);
break;
default:
IDT.DebugAssert(false, "Invalid crypto operation type");
throw IDT.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.GeneralExceptionMessage)));
}
return handle;
}
finally
{
if (mustRelease)
{
nativeHandle.DangerousRelease();
}
}
}
}
//
// Summary:
// This class manages the lifetime of a native crypto handle through ref counts. Any number of CryptoHandles
// may refer to a single InternalRefCountedHandle, but once they are all disposed this object will dispose
// itself as well.
//
internal class InternalRefCountedHandle : SafeHandle
{
int m_refcount = 0;
DateTime m_expiration;
object m_parameters = null;
[DllImport("infocardapi.dll",
EntryPoint = "CloseCryptoHandle",
CharSet = CharSet.Unicode,
CallingConvention = CallingConvention.StdCall,
ExactSpelling = true,
SetLastError = true)]
[SuppressUnmanagedCodeSecurity]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern bool CloseCryptoHandle([In] IntPtr hKey);
private InternalRefCountedHandle()
: base(IntPtr.Zero, true)
{
m_refcount = 1;
}
public void Initialize(DateTime expiration, object parameters)
{
m_expiration = expiration;
m_parameters = parameters;
}
//
// Summary:
// The deserialized parameters specific to a particular type of CryptoHandle.
//
public object Parameters
{
get
{
ThrowIfInvalid();
return m_parameters;
}
}
//
// Summary:
// The expiration of this CryptoHandle
//
public DateTime Expiration
{
get
{
ThrowIfInvalid();
return m_expiration;
}
}
public void AddRef()
{
ThrowIfInvalid();
Interlocked.Increment(ref m_refcount);
}
public void Release()
{
ThrowIfInvalid();
int refcount = Interlocked.Decrement(ref m_refcount);
if (0 == refcount)
{
Dispose();
}
}
private void ThrowIfInvalid()
{
if (IsInvalid)
{
throw IDT.ThrowHelperError(new ObjectDisposedException("InternalRefCountedHandle"));
}
}
public override bool IsInvalid
{
get
{
return (IntPtr.Zero == base.handle);
}
}
protected override bool ReleaseHandle()
{
#pragma warning suppress 56523
return CloseCryptoHandle(base.handle);
}
}
}

View File

@@ -0,0 +1,30 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.IdentityModel.Selectors
{
using System;
using System.Runtime.InteropServices;
using System.Threading;
using IDT = Microsoft.InfoCards.Diagnostics.InfoCardTrace;
//
// Summary:
// Wraps a HashCryptoSession
//
internal class HashCryptoHandle : CryptoHandle
{
public HashCryptoHandle(InternalRefCountedHandle nativeHandle, DateTime expiration, IntPtr parameters)
: base(nativeHandle, expiration, parameters, typeof(RpcHashCryptoParameters))
{
}
private HashCryptoHandle(InternalRefCountedHandle internalHandle) : base(internalHandle) { }
protected override CryptoHandle OnDuplicate()
{
return new HashCryptoHandle(InternalHandle);
}
}
}

View File

@@ -0,0 +1,34 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.IdentityModel.Selectors
{
using System;
using System.Runtime.Serialization;
using Microsoft.InfoCards.Diagnostics;
[Serializable]
public class IdentityValidationException : System.Exception
{
public IdentityValidationException()
: base()
{
}
public IdentityValidationException( string message )
: base( message )
{
}
public IdentityValidationException( string message, Exception innerException )
: base( message, innerException )
{
}
protected IdentityValidationException( SerializationInfo info, StreamingContext context )
: base( info, context )
{
}
}
}

View File

@@ -0,0 +1,44 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace Microsoft.InfoCards
{
using System;
using System.Runtime.Serialization;
using Microsoft.InfoCards.Diagnostics;
//
// Indicates an incorrect argument was passed to the system.
//
internal class InfoCardArgumentException : InfoCardBaseException
{
//
// This the code that this exception translates into.
//
const int HRESULT = (int)EventCode.E_ICARD_ARGUMENT;
public InfoCardArgumentException()
: base(HRESULT)
{
}
public InfoCardArgumentException(string message)
: base(HRESULT, message)
{
}
public InfoCardArgumentException(string message, Exception inner)
: base(HRESULT, message, inner)
{
}
protected InfoCardArgumentException(SerializationInfo si, StreamingContext sc)
: base(HRESULT, si, sc)
{
}
}
}

View File

@@ -0,0 +1,223 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.IdentityModel.Selectors
{
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.IdentityModel.Tokens;
using IDT = Microsoft.InfoCards.Diagnostics.InfoCardTrace;
//
// For common & resources
//
using Microsoft.InfoCards;
//
// Summary:
// This class implements the IAsymmetricCrypto interface and is used as an adapter between the
// InfoCard system and Indigo.
//
internal class InfoCardAsymmetricCrypto : AsymmetricSecurityKey, IDisposable
{
InfoCardRSACryptoProvider m_rsa;
//
// Summary:
// Constructs a new InfoCardAsymmetricCrypto given an InfoCardRSACryptoProvider.
//
// Parameters:
// cryptoHandle - the handle to the asymmetric key to base this crypto object on.
public InfoCardAsymmetricCrypto(AsymmetricCryptoHandle cryptoHandle)
{
m_rsa = new InfoCardRSACryptoProvider(cryptoHandle);
}
//
// Summary:
// Returns the size of the asymmetric key
//
public override int KeySize
{
get { return m_rsa.KeySize; }
}
//
// Summary:
// Indicates whether this IAsymmetricCrypto has access to the private key.
// In our case, that's the whole point, so it always returns true.
//
public override bool HasPrivateKey()
{
return true;
}
//
// Summary:
// Returns a reference to the InfoCardRSACryptoProvider that give Indigo access to
// the private key associated with the infocard, recipient tuple.
//
// Parameters:
// algorithmUri - The URI of the algorithm being requested.
// privateKey - set to true if access to the private key is required.
//
public override AsymmetricAlgorithm GetAsymmetricAlgorithm(string algorithmUri, bool privateKey)
{
switch (algorithmUri)
{
case SignedXml.XmlDsigRSASHA1Url:
case EncryptedXml.XmlEncRSA15Url:
case EncryptedXml.XmlEncRSAOAEPUrl:
return m_rsa;
default:
throw IDT.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ClientUnsupportedCryptoAlgorithm, algorithmUri)));
}
}
//
// Sumamry:
// Returns a HashAlgorithm
//
// Parameters:
// algorithmUri - the uri of the hash algorithm being requested.
//
public override HashAlgorithm GetHashAlgorithmForSignature(string algorithmUri)
{
switch (algorithmUri)
{
case SignedXml.XmlDsigRSASHA1Url:
return new SHA1Managed();
default:
throw IDT.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ClientUnsupportedCryptoAlgorithm, algorithmUri)));
}
}
//
// Summary:
// Returns a Signature deformatter.
//
// Parameters:
// algorithmUri - the uri of signature deformatter being requeted.
//
public override AsymmetricSignatureDeformatter GetSignatureDeformatter(string algorithmUri)
{
switch (algorithmUri)
{
case SignedXml.XmlDsigRSASHA1Url:
return new InfoCardRSAPKCS1SignatureDeformatter(m_rsa);
default:
throw IDT.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ClientUnsupportedCryptoAlgorithm, algorithmUri)));
}
}
//
// Summary:
// Returns a Signature formatter.
//
// Parameters:
// algorithmUri - the uri of signature formatter being requeted.
//
public override AsymmetricSignatureFormatter GetSignatureFormatter(string algorithmUri)
{
switch (algorithmUri)
{
case SignedXml.XmlDsigRSASHA1Url:
return new InfoCardRSAPKCS1SignatureFormatter(m_rsa);
default:
throw IDT.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ClientUnsupportedCryptoAlgorithm, algorithmUri)));
}
}
//
// Summary:
// Decrypts a symmetric key using the private key of a public/private key pair.
//
// Parameters:
// algorithmUri - The algorithm to use to decrypt the key.
// keyData - the key to decrypt.
//
public override byte[] DecryptKey(string algorithmUri, byte[] keyData)
{
AsymmetricKeyExchangeDeformatter deformatter;
switch (algorithmUri)
{
case EncryptedXml.XmlEncRSA15Url:
deformatter = new InfoCardRSAPKCS1KeyExchangeDeformatter(m_rsa);
return deformatter.DecryptKeyExchange(keyData);
case EncryptedXml.XmlEncRSAOAEPUrl:
deformatter = new InfoCardRSAOAEPKeyExchangeDeformatter(m_rsa);
return deformatter.DecryptKeyExchange(keyData);
default:
throw IDT.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ClientUnsupportedCryptoAlgorithm, algorithmUri)));
}
}
//
// Summary:
// Encrypts a symmetric key using the public key of a public/private key pair.
//
// Parameters:
// algorithmUri - The algorithm to use to encrypt the key.
// keyData - the key to encrypt.
//
public override byte[] EncryptKey(string algorithmUri, byte[] keyData)
{
AsymmetricKeyExchangeFormatter formatter;
switch (algorithmUri)
{
case EncryptedXml.XmlEncRSA15Url:
formatter = new InfoCardRSAPKCS1KeyExchangeFormatter(m_rsa);
return formatter.CreateKeyExchange(keyData);
case EncryptedXml.XmlEncRSAOAEPUrl:
formatter = new InfoCardRSAOAEPKeyExchangeFormatter(m_rsa);
return formatter.CreateKeyExchange(keyData);
default:
throw IDT.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ClientUnsupportedCryptoAlgorithm, algorithmUri)));
}
}
public override bool IsSupportedAlgorithm(string algorithmUri)
{
switch (algorithmUri)
{
case SignedXml.XmlDsigRSASHA1Url:
case EncryptedXml.XmlEncRSA15Url:
case EncryptedXml.XmlEncRSAOAEPUrl:
return true;
default:
return false;
}
}
public override bool IsSymmetricAlgorithm(string algorithmUri)
{
return InfoCardCryptoHelper.IsSymmetricAlgorithm(algorithmUri);
}
public override bool IsAsymmetricAlgorithm(string algorithmUri)
{
return InfoCardCryptoHelper.IsAsymmetricAlgorithm(algorithmUri);
}
public void Dispose()
{
((IDisposable)m_rsa).Dispose();
m_rsa = null;
}
}
}

View File

@@ -0,0 +1,70 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace Microsoft.InfoCards
{
using System;
using System.Runtime.Serialization;
[Serializable]
internal abstract class InfoCardBaseException : System.Exception
{
private bool m_logged = false;
private string m_extendedMessage; // Extended message string
protected InfoCardBaseException( int result )
: base()
{
HResult = result;
}
protected InfoCardBaseException( int result, string message )
: base( message )
{
HResult = result;
}
protected InfoCardBaseException( int result, string message, string extendedMessage )
: base( message )
{
HResult = result;
m_extendedMessage = extendedMessage;
}
protected InfoCardBaseException( int result, string message, Exception innerException )
: base( message, innerException )
{
HResult = result;
}
protected InfoCardBaseException( int result, SerializationInfo info, StreamingContext context )
: base( info, context )
{
HResult = result;
}
public int NativeHResult
{
get { return HResult; }
}
public bool Logged
{
get
{
return m_logged;
}
}
public void MarkLogged()
{
m_logged = true;
}
public string ExtendedMessage
{
get { return m_extendedMessage; }
}
}
}

View File

@@ -0,0 +1,242 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
//
// Presharp uses the c# pragma mechanism to supress its warnings.
// These are not recognised by the base compiler so we need to explictly
// disable the following warnings. See http://winweb/cse/Tools/PREsharp/userguide/default.asp
// for details.
//
#pragma warning disable 1634, 1691 // unknown message, unknown pragma
namespace System.IdentityModel.Selectors
{
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Runtime.ConstrainedExecution;
using System.Runtime.CompilerServices;
using IDT = Microsoft.InfoCards.Diagnostics.InfoCardTrace;
using DiagnosticUtility = Microsoft.InfoCards.Diagnostics.DiagnosticUtility;
//
// For common & resources
//
using Microsoft.InfoCards;
//
// Summary:
// Remotes a KeyedHashAlgorithm from the InfoCard service.
//
internal class InfoCardKeyedHashAlgorithm : KeyedHashAlgorithm
{
HashCryptoHandle m_cryptoHandle;
RpcHashCryptoParameters m_param;
byte[] m_cachedBlock;
//
// Summary:
// Creates a new InfoCardKeyedHashAlgorithm based on a SymmetricCryptoHandle.
//
// Parameters:
// cryptoHandle - The handle to the symmetric key on which to base the keyed hash.
//
public InfoCardKeyedHashAlgorithm(SymmetricCryptoHandle cryptoHandle)
{
InternalRefCountedHandle nativeHandle = null;
try
{
//
// Call native api to get a hashCryptoHandle.
//
int status = CardSpaceSelector.GetShim().m_csShimGetKeyedHash(cryptoHandle.InternalHandle, out nativeHandle);
if (0 != status)
{
IDT.CloseInvalidOutSafeHandle(nativeHandle);
ExceptionHelper.ThrowIfCardSpaceException(status);
throw IDT.ThrowHelperError(new Win32Exception(status));
}
m_cryptoHandle = (HashCryptoHandle)CryptoHandle.Create(nativeHandle);
m_param = (RpcHashCryptoParameters)m_cryptoHandle.Parameters;
}
catch
{
if (null != m_cryptoHandle)
{
m_cryptoHandle.Dispose();
}
throw;
}
}
#pragma warning disable 56503 // property gets should not throw.
public override byte[] Key
{
get { throw IDT.ThrowHelperError(new NotImplementedException()); }
}
public override int HashSize
{
get { return m_param.hashSize; }
}
public override int InputBlockSize
{
get { return m_param.transform.inputBlockSize; }
}
public override int OutputBlockSize
{
get { return m_param.transform.outputBlockSize; }
}
public override bool CanTransformMultipleBlocks
{
get { return m_param.transform.canTransformMultipleBlocks; }
}
public override bool CanReuseTransform
{
get { return m_param.transform.canReuseTransform; }
}
#pragma warning restore 56503
public override void Initialize()
{
}
//
// Summary:
// Implements the HashCore method of the KeyedHashAlgorithm class by calling the InfoCard native client.
//
// Parameters:
// array - the bytes to hash.
// ibStart - the index in the array from which to begin hashing.
// cbSize - the number of bytes after the starting index to hash.
//
protected override void HashCore(byte[] array, int ibStart, int cbSize)
{
//
// will cache one block and call TransformBlock on the previous block.
//
if (null != m_cachedBlock)
{
HGlobalSafeHandle pInData = null;
try
{
if (0 != m_cachedBlock.Length)
{
pInData = HGlobalSafeHandle.Construct(m_cachedBlock.Length);
Marshal.Copy(m_cachedBlock, 0, pInData.DangerousGetHandle(), m_cachedBlock.Length);
}
int status = CardSpaceSelector.GetShim().m_csShimHashCore(m_cryptoHandle.InternalHandle,
m_cachedBlock.Length,
null != pInData ? pInData : HGlobalSafeHandle.Construct());
if (0 != status)
{
ExceptionHelper.ThrowIfCardSpaceException(status);
throw IDT.ThrowHelperError(new Win32Exception(status));
}
}
finally
{
if (null != pInData)
{
pInData.Dispose();
}
}
}
//
// Cache the current block.
//
if (null != m_cachedBlock)
{
Array.Clear(m_cachedBlock, 0, m_cachedBlock.Length);
}
m_cachedBlock = DiagnosticUtility.Utility.AllocateByteArray(cbSize);
Array.Copy(array, ibStart, m_cachedBlock, 0, cbSize);
return;
}
//
// Summary:
// Implements the HashFinal method of the KeyedHashAlgorithm class by calling the InfoCard native client.
//
protected override byte[] HashFinal()
{
byte[] outData = null;
int cbOutData = 0;
IDT.DebugAssert(null != m_cachedBlock, "null cached block");
HGlobalSafeHandle pInData = null;
GlobalAllocSafeHandle pOutData = null;
try
{
if (null != m_cachedBlock)
{
if (0 != m_cachedBlock.Length)
{
pInData = HGlobalSafeHandle.Construct(m_cachedBlock.Length);
Marshal.Copy(m_cachedBlock, 0, pInData.DangerousGetHandle(), m_cachedBlock.Length);
}
int status = CardSpaceSelector.GetShim().m_csShimHashFinal(m_cryptoHandle.InternalHandle,
m_cachedBlock.Length,
null != pInData ? pInData : HGlobalSafeHandle.Construct(),
out cbOutData,
out pOutData);
if (0 != status)
{
ExceptionHelper.ThrowIfCardSpaceException(status);
throw IDT.ThrowHelperError(new Win32Exception(status));
}
pOutData.Length = cbOutData;
outData = DiagnosticUtility.Utility.AllocateByteArray(pOutData.Length);
using (pOutData)
{
Marshal.Copy(pOutData.DangerousGetHandle(), outData, 0, pOutData.Length);
}
}
}
finally
{
if (null != pInData)
{
pInData.Dispose();
}
Array.Clear(m_cachedBlock, 0, m_cachedBlock.Length);
m_cachedBlock = null;
}
return outData;
}
protected override void Dispose(bool disposing)
{
try
{
if (null != m_cachedBlock)
{
Array.Clear(m_cachedBlock, 0, m_cachedBlock.Length);
}
m_cryptoHandle.Dispose();
}
finally
{
base.Dispose(disposing);
}
}
}
}

View File

@@ -0,0 +1,79 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.IdentityModel.Selectors
{
using System;
using System.IdentityModel.Tokens;
using System.IdentityModel.Policy;
using System.IdentityModel.Claims;
using System.Collections.Generic;
using System.Collections.ObjectModel;
//
// Summary:
// This class implements a SecurityToken to wrap a remoted crypto key. It provides indirect
// access to the private proof key associated with a released token.
//
internal class InfoCardProofToken : SecurityToken, IDisposable
{
string m_id;
DateTime m_expiration;
ReadOnlyCollection<SecurityKey> m_securityKeys;
SecurityKey m_securityKey;
public InfoCardProofToken( AsymmetricCryptoHandle cryptoHandle, DateTime expiration ) : this( expiration )
{
InitCrypto( new InfoCardAsymmetricCrypto( cryptoHandle ) );
}
public InfoCardProofToken( SymmetricCryptoHandle cryptoHandle, DateTime expiration ) : this( expiration )
{
InitCrypto( new InfoCardSymmetricCrypto( cryptoHandle ) );
}
private InfoCardProofToken( DateTime expiration ) : base()
{
m_id = Guid.NewGuid().ToString();
m_expiration = expiration.ToUniversalTime();
}
public override string Id
{
get { return m_id; }
}
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return m_securityKeys;
}
}
public override DateTime ValidTo
{
get { return m_expiration; }
}
public override DateTime ValidFrom
{
get { return DateTime.UtcNow; }
}
private void InitCrypto(SecurityKey securityKey)
{
m_securityKey = securityKey;
List<SecurityKey> securityKeys = new List<SecurityKey>(1);
securityKeys.Add(securityKey);
m_securityKeys = securityKeys.AsReadOnly();
}
public void Dispose()
{
m_securityKeys = null;
((IDisposable)m_securityKey).Dispose();
}
}
}

View File

@@ -0,0 +1,245 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.IdentityModel.Selectors
{
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using IDT = Microsoft.InfoCards.Diagnostics.InfoCardTrace;
using DiagnosticUtility = Microsoft.InfoCards.Diagnostics.DiagnosticUtility;
//
// For common & resources
//
using Microsoft.InfoCards;
//
// Summary:
// This class provides indirect access to the private key associated with a released token via InfoCard
// native crypto functions.
//
internal class InfoCardRSACryptoProvider : RSA
{
AsymmetricCryptoHandle m_cryptoHandle;
RpcAsymmetricCryptoParameters m_params;
//
// Summary:
// Given a pointer to a CryptoHandle create a new instance of this class.
//
public InfoCardRSACryptoProvider(AsymmetricCryptoHandle cryptoHandle)
: base()
{
m_cryptoHandle = (AsymmetricCryptoHandle)cryptoHandle.Duplicate();
try
{
m_params = (RpcAsymmetricCryptoParameters)m_cryptoHandle.Parameters;
int keySize = m_params.keySize;
LegalKeySizesValue = new KeySizes[1];
KeySizeValue = keySize;
LegalKeySizesValue[0] = new KeySizes(keySize, keySize, 0);
}
catch
{
m_cryptoHandle.Dispose();
m_cryptoHandle = null;
throw;
}
}
public override String SignatureAlgorithm
{
get { return m_params.signatureAlgorithm; }
}
public override String KeyExchangeAlgorithm
{
get { return m_params.keyExchangeAlgorithm; }
}
public override byte[] EncryptValue(byte[] rgb)
{
throw IDT.ThrowHelperError(new NotSupportedException());
}
public override byte[] DecryptValue(byte[] rgb)
{
throw IDT.ThrowHelperError(new NotSupportedException());
}
public byte[] Decrypt(byte[] inData, bool fAOEP)
{
GlobalAllocSafeHandle pOutData = null;
int cbOutData = 0;
byte[] outData;
IDT.ThrowInvalidArgumentConditional(null == inData, "indata");
using (HGlobalSafeHandle pInData = HGlobalSafeHandle.Construct(inData.Length))
{
Marshal.Copy(inData, 0, pInData.DangerousGetHandle(), inData.Length);
int status = CardSpaceSelector.GetShim().m_csShimDecrypt(m_cryptoHandle.InternalHandle,
fAOEP,
inData.Length,
pInData,
out cbOutData,
out pOutData);
if (0 != status)
{
ExceptionHelper.ThrowIfCardSpaceException(status);
throw IDT.ThrowHelperError(new Win32Exception(status));
}
pOutData.Length = cbOutData;
outData = DiagnosticUtility.Utility.AllocateByteArray(pOutData.Length);
using (pOutData)
{
Marshal.Copy(pOutData.DangerousGetHandle(), outData, 0, pOutData.Length);
}
}
return outData;
}
public byte[] Encrypt(byte[] inData, bool fAOEP)
{
GlobalAllocSafeHandle pOutData = null;
int cbOutData = 0;
byte[] outData;
IDT.ThrowInvalidArgumentConditional(null == inData, "indata");
using (HGlobalSafeHandle pInData = HGlobalSafeHandle.Construct(inData.Length))
{
Marshal.Copy(inData, 0, pInData.DangerousGetHandle(), inData.Length);
int status = CardSpaceSelector.GetShim().m_csShimEncrypt(m_cryptoHandle.InternalHandle,
fAOEP,
inData.Length,
pInData,
out cbOutData,
out pOutData);
if (0 != status)
{
ExceptionHelper.ThrowIfCardSpaceException(status);
throw IDT.ThrowHelperError(new Win32Exception(status));
}
pOutData.Length = cbOutData;
outData = DiagnosticUtility.Utility.AllocateByteArray(pOutData.Length);
Marshal.Copy(pOutData.DangerousGetHandle(), outData, 0, pOutData.Length);
}
return outData;
}
public byte[] SignHash(byte[] hash, string hashAlgOid)
{
IDT.ThrowInvalidArgumentConditional(null == hash || 0 == hash.Length, "hash");
IDT.ThrowInvalidArgumentConditional(String.IsNullOrEmpty(hashAlgOid), "hashAlgOid");
int cbSig = 0;
GlobalAllocSafeHandle pSig = null;
byte[] sig;
using (HGlobalSafeHandle pHash = HGlobalSafeHandle.Construct(hash.Length))
{
using (HGlobalSafeHandle pHashAlgOid = HGlobalSafeHandle.Construct(hashAlgOid))
{
Marshal.Copy(hash, 0, pHash.DangerousGetHandle(), hash.Length);
RuntimeHelpers.PrepareConstrainedRegions();
int status = CardSpaceSelector.GetShim().m_csShimSignHash(m_cryptoHandle.InternalHandle,
hash.Length,
pHash,
pHashAlgOid,
out cbSig,
out pSig);
if (0 != status)
{
ExceptionHelper.ThrowIfCardSpaceException(status);
throw IDT.ThrowHelperError(new Win32Exception(status));
}
pSig.Length = cbSig;
sig = DiagnosticUtility.Utility.AllocateByteArray(pSig.Length);
using (pSig)
{
Marshal.Copy(pSig.DangerousGetHandle(), sig, 0, pSig.Length);
}
}
}
return sig;
}
public bool VerifyHash(byte[] hash, string hashAlgOid, byte[] sig)
{
IDT.ThrowInvalidArgumentConditional(null == hash || 0 == hash.Length, "hash");
IDT.ThrowInvalidArgumentConditional(String.IsNullOrEmpty(hashAlgOid), "hashAlgOid");
IDT.ThrowInvalidArgumentConditional(null == sig || 0 == sig.Length, "sig");
bool verified = false;
using (HGlobalSafeHandle pHash = HGlobalSafeHandle.Construct(hash.Length))
{
using (HGlobalSafeHandle pHashAlgOid = HGlobalSafeHandle.Construct(hashAlgOid))
{
Marshal.Copy(hash, 0, pHash.DangerousGetHandle(), hash.Length);
int status = 0;
using (HGlobalSafeHandle pSig = HGlobalSafeHandle.Construct(sig.Length))
{
Marshal.Copy(sig, 0, pSig.DangerousGetHandle(), sig.Length);
status = CardSpaceSelector.GetShim().m_csShimVerifyHash(m_cryptoHandle.InternalHandle,
hash.Length,
pHash,
pHashAlgOid,
sig.Length,
pSig,
out verified);
}
if (0 != status)
{
ExceptionHelper.ThrowIfCardSpaceException(status);
throw IDT.ThrowHelperError(new Win32Exception(status));
}
}
}
return verified;
}
public override RSAParameters ExportParameters(bool includePrivateParameters)
{
throw IDT.ThrowHelperError(new NotSupportedException());
}
public override string ToXmlString(bool includePrivateParameters)
{
throw IDT.ThrowHelperError(new NotSupportedException());
}
public override void FromXmlString(string xmlString)
{
throw IDT.ThrowHelperError(new NotSupportedException());
}
public override void ImportParameters(System.Security.Cryptography.RSAParameters parameters)
{
throw IDT.ThrowHelperError(new NotSupportedException());
}
protected override void Dispose(bool disposing)
{
m_cryptoHandle.Dispose();
}
}
}

View File

@@ -0,0 +1,47 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.IdentityModel.Selectors
{
using System;
using System.Security.Cryptography;
internal class InfoCardRSAOAEPKeyExchangeDeformatter : RSAOAEPKeyExchangeDeformatter
{
private RSA m_rsaKey; // RSA Key value to do decrypt operation
//
// public constructors
//
public InfoCardRSAOAEPKeyExchangeDeformatter() : base() { }
public InfoCardRSAOAEPKeyExchangeDeformatter(AsymmetricAlgorithm key)
: base(key)
{
m_rsaKey = (RSA)key;
}
//
// public methods
//
public override byte[] DecryptKeyExchange(byte[] rgbData)
{
if (null != m_rsaKey && m_rsaKey is InfoCardRSACryptoProvider)
{
return ((InfoCardRSACryptoProvider)m_rsaKey).Decrypt(rgbData, true);
}
else
{
return base.DecryptKeyExchange(rgbData);
}
}
public override void SetKey(AsymmetricAlgorithm key)
{
base.SetKey(key);
m_rsaKey = (RSA)key;
}
}
}

View File

@@ -0,0 +1,47 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.IdentityModel.Selectors
{
using System;
using System.Security.Cryptography;
internal class InfoCardRSAOAEPKeyExchangeFormatter : RSAOAEPKeyExchangeFormatter
{
private RSA m_rsaKey;
//
// public constructors
//
public InfoCardRSAOAEPKeyExchangeFormatter() : base() { }
public InfoCardRSAOAEPKeyExchangeFormatter(AsymmetricAlgorithm key)
: base(key)
{
m_rsaKey = (RSA)key;
}
//
// public methods
//
public override void SetKey(AsymmetricAlgorithm key)
{
base.SetKey(key);
m_rsaKey = (RSA)key;
}
public override byte[] CreateKeyExchange(byte[] rgbData)
{
if (null != m_rsaKey && m_rsaKey is InfoCardRSACryptoProvider)
{
return ((InfoCardRSACryptoProvider)m_rsaKey).Encrypt(rgbData, true);
}
else
{
return base.CreateKeyExchange(rgbData);
}
}
}
}

Some files were not shown because too many files have changed in this diff Show More