protected override SecurityKeyIdentifier ReadKeyIdentifierCore(XmlReader reader) { var result = new SecurityKeyIdentifier(); reader.ReadStartElement("KeyInfo", SignedXml.XmlDsigNamespaceUrl); while (reader.IsStartElement()) { if (reader.IsStartElement("X509Data", SignedXml.XmlDsigNamespaceUrl)) { foreach (var clause in ReadX509Data(reader)) { result.Add(clause); } } else { if (reader.IsStartElement("KeyName", SignedXml.XmlDsigNamespaceUrl)) { result.Add(ReadKeyNameClause(reader)); } else { reader.Skip(); } } } reader.ReadEndElement(); return(result); }
protected override SecurityKeyIdentifier ReadKeyIdentifierCore(XmlReader reader) { var result = new SecurityKeyIdentifier(); reader.ReadStartElement("KeyInfo", SignedXml.XmlDsigNamespaceUrl); while (reader.IsStartElement()) { if (reader.IsStartElement("X509Data", SignedXml.XmlDsigNamespaceUrl)) { foreach (var clause in ReadX509Data(reader)) { result.Add(clause); } } else { if (reader.IsStartElement("KeyName", SignedXml.XmlDsigNamespaceUrl)) { result.Add(ReadKeyNameClause(reader)); } else { reader.Skip(); } } } reader.ReadEndElement(); return result; }
private SecurityKeyIdentifier ReadGenericXmlSecurityKeyIdentifier(XmlDictionaryReader localReader, Exception previousException) { if (!localReader.IsStartElement(XD.XmlSignatureDictionary.KeyInfo, XD.XmlSignatureDictionary.Namespace)) { return(null); } localReader.ReadStartElement(XD.XmlSignatureDictionary.KeyInfo, XD.XmlSignatureDictionary.Namespace); SecurityKeyIdentifier keyIdentifier = new SecurityKeyIdentifier(); if (localReader.IsStartElement()) { SecurityKeyIdentifierClause clause = null; string strId = localReader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace); XmlDocument doc = new XmlDocument(); XmlElement keyIdentifierReferenceXml = (doc.ReadNode(localReader) as XmlElement); clause = new GenericXmlSecurityKeyIdentifierClause(keyIdentifierReferenceXml); if (!string.IsNullOrEmpty(strId)) { clause.Id = strId; } keyIdentifier.Add(clause); } if (keyIdentifier.Count == 0) { throw previousException; } localReader.ReadEndElement(); return(keyIdentifier); }
private SecurityKeyIdentifier ReadGenericXmlSecurityKeyIdentifier(XmlDictionaryReader localReader, Exception previousException) { if (!localReader.IsStartElement(System.IdentityModel.XD.XmlSignatureDictionary.KeyInfo, System.IdentityModel.XD.XmlSignatureDictionary.Namespace)) { return((SecurityKeyIdentifier)null); } localReader.ReadStartElement(System.IdentityModel.XD.XmlSignatureDictionary.KeyInfo, System.IdentityModel.XD.XmlSignatureDictionary.Namespace); SecurityKeyIdentifier securityKeyIdentifier = new SecurityKeyIdentifier(); if (localReader.IsStartElement()) { #if FEATURE_CORECLR throw new NotImplementedException("GenericXmlSecurityKeyIdentifierClause not supported"); #else string attribute = localReader.GetAttribute(System.IdentityModel.XD.UtilityDictionary.IdAttribute, System.IdentityModel.XD.UtilityDictionary.Namespace); SecurityKeyIdentifierClause clause = (SecurityKeyIdentifierClause) new GenericXmlSecurityKeyIdentifierClause(new XmlDocument().ReadNode((XmlReader)localReader) as XmlElement); if (!string.IsNullOrEmpty(attribute)) { clause.Id = attribute; } securityKeyIdentifier.Add(clause); #endif } if (securityKeyIdentifier.Count == 0) { throw previousException; } localReader.ReadEndElement(); return(securityKeyIdentifier); }
WrappedKeySecurityToken ReadWrappedKeySecurityTokenCore( XmlReader reader, SecurityTokenResolver tokenResolver) { if (tokenResolver == null) { throw new ArgumentNullException("tokenResolver"); } EncryptedKey ek = new EncryptedKey(); ek.LoadXml(new XmlDocument().ReadNode(reader) as XmlElement); SecurityKeyIdentifier ki = new SecurityKeyIdentifier(); foreach (KeyInfoClause kic in ek.KeyInfo) { ki.Add(ReadKeyIdentifierClause(new XmlNodeReader(kic.GetXml()))); } SecurityToken token = tokenResolver.ResolveToken(ki); string alg = ek.EncryptionMethod.KeyAlgorithm; foreach (SecurityKey skey in token.SecurityKeys) { if (skey.IsSupportedAlgorithm(alg)) { byte [] key = skey.DecryptKey(alg, ek.CipherData.CipherValue); WrappedKeySecurityToken wk = new WrappedKeySecurityToken(ek.Id, key, alg, token, ki); // FIXME: This should not be required. wk.SetWrappedKey(ek.CipherData.CipherValue); wk.ReferenceList = ek.ReferenceList; return(wk); } } throw new InvalidOperationException(String.Format("Cannot resolve security key with the resolved SecurityToken specified by the key identifier in the EncryptedKey XML. The key identifier is: {0}", ki)); }
public void ReadOnlyAdd() { SecurityKeyIdentifier ki = new SecurityKeyIdentifier(); ki.MakeReadOnly(); ki.Add(new LocalIdKeyIdentifierClause("foo")); }
protected override SecurityKey ResolveIssuerSigningKey(string token, SecurityToken securityToken, SecurityKeyIdentifier keyIdentifier, TokenValidationParameters validationParameters) { var certificate = ((JwtSecurityToken)securityToken).GetCertificateFromToken(); if (certificate != null) { keyIdentifier.Add(new X509RawDataKeyIdentifierClause(certificate)); } return base.ResolveIssuerSigningKey(token, securityToken, keyIdentifier, validationParameters); }
protected override SecurityKey ResolveIssuerSigningKey(string token, SecurityToken securityToken, SecurityKeyIdentifier keyIdentifier, TokenValidationParameters validationParameters) { var certificate = ((JwtSecurityToken)securityToken).GetCertificateFromToken(); if (certificate != null) { keyIdentifier.Add(new X509RawDataKeyIdentifierClause(certificate)); } return(base.ResolveIssuerSigningKey(token, securityToken, keyIdentifier, validationParameters)); }
private WrappedKeySecurityToken CreateWrappedKeyToken(SecurityToken wrappingToken, SecurityTokenParameters wrappingTokenParameters, SecurityTokenReferenceStyle wrappingTokenReferenceStyle) { int keyLength = Math.Max(0x80, this.Factory.OutgoingAlgorithmSuite.DefaultSymmetricKeyLength); CryptoHelper.ValidateSymmetricKeyLength(keyLength, this.Factory.OutgoingAlgorithmSuite); byte[] buffer = new byte[keyLength / 8]; CryptoHelper.FillRandomBytes(buffer); string id = System.ServiceModel.Security.SecurityUtils.GenerateId(); string defaultAsymmetricKeyWrapAlgorithm = this.Factory.OutgoingAlgorithmSuite.DefaultAsymmetricKeyWrapAlgorithm; SecurityKeyIdentifierClause clause = wrappingTokenParameters.CreateKeyIdentifierClause(wrappingToken, wrappingTokenReferenceStyle); SecurityKeyIdentifier wrappingTokenReference = new SecurityKeyIdentifier(); wrappingTokenReference.Add(clause); return new WrappedKeySecurityToken(id, buffer, defaultAsymmetricKeyWrapAlgorithm, wrappingToken, wrappingTokenReference); }
internal static XmlDocument GetPlainAsertion(SecurityTokenResolver securityTokenResolver, XmlElement el) { var encryptedDataElement = GetElement(HttpRedirectBindingConstants.EncryptedData, Saml20Constants.Xenc, el); var encryptedData = new System.Security.Cryptography.Xml.EncryptedData(); encryptedData.LoadXml(encryptedDataElement); var encryptedKey = new System.Security.Cryptography.Xml.EncryptedKey(); var encryptedKeyElement = GetElement(HttpRedirectBindingConstants.EncryptedKey, Saml20Constants.Xenc, el); encryptedKey.LoadXml(encryptedKeyElement); var securityKeyIdentifier = new SecurityKeyIdentifier(); foreach (KeyInfoX509Data v in encryptedKey.KeyInfo) { foreach (X509Certificate2 cert in v.Certificates) { var cl = new X509RawDataKeyIdentifierClause(cert); securityKeyIdentifier.Add(cl); } } var clause = new EncryptedKeyIdentifierClause(encryptedKey.CipherData.CipherValue, encryptedKey.EncryptionMethod.KeyAlgorithm, securityKeyIdentifier); SecurityKey key; var success = securityTokenResolver.TryResolveSecurityKey(clause, out key); if (!success) { throw new InvalidOperationException("Cannot locate security key"); } SymmetricSecurityKey symmetricSecurityKey = key as SymmetricSecurityKey; if (symmetricSecurityKey == null) { throw new InvalidOperationException("Key must be symmentric key"); } SymmetricAlgorithm symmetricAlgorithm = symmetricSecurityKey.GetSymmetricAlgorithm(encryptedData.EncryptionMethod.KeyAlgorithm); var encryptedXml = new System.Security.Cryptography.Xml.EncryptedXml(); var plaintext = encryptedXml.DecryptData(encryptedData, symmetricAlgorithm); var assertion = new XmlDocument { PreserveWhitespace = true }; assertion.Load(new StringReader(Encoding.UTF8.GetString(plaintext))); return(assertion); }
private WrappedKeySecurityToken CreateWrappedKeyToken(SecurityToken wrappingToken, SecurityTokenParameters wrappingTokenParameters, SecurityTokenReferenceStyle wrappingTokenReferenceStyle) { int keyLength = Math.Max(0x80, this.Factory.OutgoingAlgorithmSuite.DefaultSymmetricKeyLength); CryptoHelper.ValidateSymmetricKeyLength(keyLength, this.Factory.OutgoingAlgorithmSuite); byte[] buffer = new byte[keyLength / 8]; CryptoHelper.FillRandomBytes(buffer); string id = System.ServiceModel.Security.SecurityUtils.GenerateId(); string defaultAsymmetricKeyWrapAlgorithm = this.Factory.OutgoingAlgorithmSuite.DefaultAsymmetricKeyWrapAlgorithm; SecurityKeyIdentifierClause clause = wrappingTokenParameters.CreateKeyIdentifierClause(wrappingToken, wrappingTokenReferenceStyle); SecurityKeyIdentifier wrappingTokenReference = new SecurityKeyIdentifier(); wrappingTokenReference.Add(clause); return(new WrappedKeySecurityToken(id, buffer, defaultAsymmetricKeyWrapAlgorithm, wrappingToken, wrappingTokenReference)); }
WrappedKeySecurityToken CreateWrappedKeyToken(SecurityToken wrappingToken, SecurityTokenParameters wrappingTokenParameters, SecurityTokenReferenceStyle wrappingTokenReferenceStyle) { int keyLength = Math.Max(128, this.Factory.OutgoingAlgorithmSuite.DefaultSymmetricKeyLength); CryptoHelper.ValidateSymmetricKeyLength(keyLength, this.Factory.OutgoingAlgorithmSuite); byte[] key = new byte[keyLength / 8]; CryptoHelper.FillRandomBytes(key); string tokenId = SecurityUtils.GenerateId(); string wrappingAlgorithm = this.Factory.OutgoingAlgorithmSuite.DefaultAsymmetricKeyWrapAlgorithm; SecurityKeyIdentifierClause clause = wrappingTokenParameters.CreateKeyIdentifierClause(wrappingToken, wrappingTokenReferenceStyle); SecurityKeyIdentifier identifier = new SecurityKeyIdentifier(); identifier.Add(clause); return(new WrappedKeySecurityToken(tokenId, key, wrappingAlgorithm, wrappingToken, identifier)); }
public virtual void ReadXml(XmlDictionaryReader reader) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } reader.MoveToContent(); if (reader.IsStartElement(XD.XmlSignatureDictionary.KeyInfo.Value, XD.XmlSignatureDictionary.Namespace.Value)) { // <KeyInfo> reader.ReadStartElement(); while (reader.IsStartElement()) { // <RetrievalMethod> if (reader.IsStartElement(XmlSignatureConstants.Elements.RetrievalMethod, XD.XmlSignatureDictionary.Namespace.Value)) { string method = reader.GetAttribute(XD.XmlSignatureDictionary.URI.Value); if (!string.IsNullOrEmpty(method)) { _retrieval = method; } reader.Skip(); } // check if internal serializer can handle clause else if (_keyInfoSerializer.CanReadKeyIdentifierClause(reader)) { _ski.Add(_keyInfoSerializer.ReadKeyIdentifierClause(reader)); } // trace we skipped over an element else if (reader.IsStartElement()) { string xml = reader.ReadOuterXml(); if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceString(System.Diagnostics.TraceEventType.Warning, SR.GetString(SR.ID8023, reader.Name, reader.NamespaceURI, xml)); } } reader.MoveToContent(); } reader.MoveToContent(); reader.ReadEndElement(); } }
public SecurityKeyIdentifier MakeSecurityKeyIdentifier() { var ski = new SecurityKeyIdentifier(); foreach (var keyValue in KeyValues) { if (keyValue is RsaKeyValue rsaKeyValue) { ski.Add(new RsaKeyIdentifierClause(rsaKeyValue.Parameters)); } else if (keyValue is DsaKeyValue dsaKeyValue) { ski.Add(new DsaKeyIdentifierClause(dsaKeyValue.Parameters)); } #if !NET461 else if (keyValue is EcKeyValue ecKeyValue) { ski.Add(new EcKeyIdentifierClause(ecKeyValue.Parameters)); } #endif } foreach (string keyName in KeyNames) { ski.Add(new KeyNameIdentifierClause(keyName)); } foreach (var keyData in Data) { if (keyData is X509Data x509Data) { foreach (var cert in x509Data.Certificates) { ski.Add(new X509RawDataKeyIdentifierClause(cert)); } if (x509Data.IssuerSerial != null) { ski.Add(new X509IssuerSerialKeyIdentifierClause( x509Data.IssuerSerial.Name, x509Data.IssuerSerial.Serial)); } } } return(ski); }
public override SecurityKeyIdentifier ReadKeyIdentifierCore( XmlDictionaryReader reader ) { reader.ReadStartElement( LocalName, NamespaceUri ); SecurityKeyIdentifier keyIdentifier = new SecurityKeyIdentifier(); while ( reader.IsStartElement() ) { SecurityKeyIdentifierClause clause = this.securityTokenSerializer.ReadKeyIdentifierClause( reader ); if ( clause == null ) { reader.Skip(); } else { keyIdentifier.Add( clause ); } } if ( keyIdentifier.Count == 0 ) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new XmlException( SR.GetString( SR.ErrorDeserializingKeyIdentifierClause ) ) ); } reader.ReadEndElement(); return keyIdentifier; }
public override SecurityKeyIdentifier ReadKeyIdentifierCore(XmlDictionaryReader reader) { reader.ReadStartElement(this.LocalName, this.NamespaceUri); SecurityKeyIdentifier identifier = new SecurityKeyIdentifier(); while (reader.IsStartElement()) { SecurityKeyIdentifierClause clause = this.tokenSerializer.ReadKeyIdentifierClause(reader); if (clause == null) { reader.Skip(); } else { identifier.Add(clause); } } if (identifier.Count == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.ServiceModel.SR.GetString("ErrorDeserializingKeyIdentifierClause"))); } reader.ReadEndElement(); return(identifier); }
WrappedKeySecurityToken CreateWrappedKeyToken(SecurityToken wrappingToken, SecurityTokenParameters wrappingTokenParameters, SecurityTokenReferenceStyle wrappingTokenReferenceStyle) { int keyLength = Math.Max(128, this.Factory.OutgoingAlgorithmSuite.DefaultSymmetricKeyLength); CryptoHelper.ValidateSymmetricKeyLength(keyLength, this.Factory.OutgoingAlgorithmSuite); byte[] key = new byte[keyLength / 8]; CryptoHelper.FillRandomBytes(key); string tokenId = SecurityUtils.GenerateId(); string wrappingAlgorithm = this.Factory.OutgoingAlgorithmSuite.DefaultAsymmetricKeyWrapAlgorithm; SecurityKeyIdentifierClause clause = wrappingTokenParameters.CreateKeyIdentifierClause(wrappingToken, wrappingTokenReferenceStyle); SecurityKeyIdentifier identifier = new SecurityKeyIdentifier(); identifier.Add(clause); return new WrappedKeySecurityToken(tokenId, key, wrappingAlgorithm, wrappingToken, identifier); }
EncryptedKeyIdentifierClause ReadEncryptedKeyIdentifierClause( XmlReader reader) { string encNS = EncryptedXml.XmlEncNamespaceUrl; string id = reader.GetAttribute("Id", Constants.WsuNamespace); reader.Read(); reader.MoveToContent(); string encMethod = reader.GetAttribute("Algorithm"); bool isEmpty = reader.IsEmptyElement; reader.ReadStartElement("EncryptionMethod", encNS); string digMethod = null; if (!isEmpty) { reader.MoveToContent(); if (reader.LocalName == "DigestMethod" && reader.NamespaceURI == SignedXml.XmlDsigNamespaceUrl) { digMethod = reader.GetAttribute("Algorithm"); } while (reader.NodeType != XmlNodeType.EndElement) { reader.Skip(); reader.MoveToContent(); } reader.ReadEndElement(); } reader.MoveToContent(); SecurityKeyIdentifier ki = null; if (!reader.IsEmptyElement) { reader.ReadStartElement("KeyInfo", SignedXml.XmlDsigNamespaceUrl); reader.MoveToContent(); SecurityKeyIdentifierClause kic = ReadKeyIdentifierClauseCore(reader); ki = new SecurityKeyIdentifier(); ki.Add(kic); reader.MoveToContent(); reader.ReadEndElement(); // </ds:KeyInfo> reader.MoveToContent(); } byte [] keyValue = null; if (!reader.IsEmptyElement) { reader.ReadStartElement("CipherData", encNS); reader.MoveToContent(); keyValue = Convert.FromBase64String(reader.ReadElementContentAsString("CipherValue", encNS)); reader.MoveToContent(); reader.ReadEndElement(); // CipherData } string carriedKeyName = null; if (!reader.IsEmptyElement && reader.LocalName == "CarriedKeyName" && reader.NamespaceURI == encNS) { carriedKeyName = reader.ReadElementContentAsString(); reader.MoveToContent(); } // FIXME: handle derived keys?? return(new EncryptedKeyIdentifierClause(keyValue, encMethod, ki, carriedKeyName)); }
public void WriteEncryptedKeyIdentifierClause2 () // derived key { StringWriter sw = new StringWriter (); byte [] bytes = new byte [32]; SecurityKeyIdentifier cki = new SecurityKeyIdentifier (); cki.Add (new X509ThumbprintKeyIdentifierClause (cert)); EncryptedKeyIdentifierClause ic = new EncryptedKeyIdentifierClause (bytes, SecurityAlgorithms.Aes256KeyWrap, cki, "carriedKeyNaaaaame", new byte [32], 32); using (XmlWriter w = XmlWriter.Create (sw, GetWriterSettings ())) { WSSecurityTokenSerializer.DefaultInstance.WriteKeyIdentifierClause (w, ic); } string expected = String.Format ("<e:EncryptedKey xmlns:e=\"{0}\"><e:EncryptionMethod Algorithm=\"{1}\" /><KeyInfo xmlns=\"{2}\"><o:SecurityTokenReference xmlns:o=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><o:KeyIdentifier ValueType=\"{3}\">GQ3YHlGQhDF1bvMixHliX4uLjlY=</o:KeyIdentifier></o:SecurityTokenReference></KeyInfo><e:CipherData><e:CipherValue>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</e:CipherValue></e:CipherData><e:CarriedKeyName>carriedKeyNaaaaame</e:CarriedKeyName></e:EncryptedKey>", EncryptedXml.XmlEncNamespaceUrl, SecurityAlgorithms.Aes256KeyWrap, SignedXml.XmlDsigNamespaceUrl, "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#ThumbprintSHA1"); Assert.AreEqual (expected, sw.ToString ()); }
public void WriteEncryptedKeyIdentifierClause4 () { StringWriter sw = new StringWriter (); byte [] bytes = new byte [32]; SecurityKeyIdentifier cki = new SecurityKeyIdentifier (); cki.Add (new BinarySecretKeyIdentifierClause (bytes)); EncryptedKeyIdentifierClause ic = new EncryptedKeyIdentifierClause (bytes, SecurityAlgorithms.Aes256Encryption); using (XmlWriter w = XmlWriter.Create (sw, GetWriterSettings ())) { WSSecurityTokenSerializer.DefaultInstance.WriteKeyIdentifierClause (w, ic); } string expected = String.Format ("<e:EncryptedKey xmlns:e=\"{0}\"><e:EncryptionMethod Algorithm=\"{1}\" /><e:CipherData><e:CipherValue>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</e:CipherValue></e:CipherData></e:EncryptedKey>", EncryptedXml.XmlEncNamespaceUrl, SecurityAlgorithms.Aes256Encryption, SignedXml.XmlDsigNamespaceUrl, "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#ThumbprintSHA1"); Assert.AreEqual (expected, sw.ToString ()); }
private SecurityKeyIdentifier ReadGenericXmlSecurityKeyIdentifier(XmlDictionaryReader localReader, Exception previousException) { if (!localReader.IsStartElement(XD.XmlSignatureDictionary.KeyInfo, XD.XmlSignatureDictionary.Namespace)) { return null; } localReader.ReadStartElement(XD.XmlSignatureDictionary.KeyInfo, XD.XmlSignatureDictionary.Namespace); SecurityKeyIdentifier keyIdentifier = new SecurityKeyIdentifier(); if (localReader.IsStartElement()) { SecurityKeyIdentifierClause clause = null; string strId = localReader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace); XmlDocument doc = new XmlDocument(); XmlElement keyIdentifierReferenceXml = (doc.ReadNode(localReader) as XmlElement); clause = new GenericXmlSecurityKeyIdentifierClause(keyIdentifierReferenceXml); if (!string.IsNullOrEmpty(strId)) clause.Id = strId; keyIdentifier.Add(clause); } if (keyIdentifier.Count == 0) throw previousException; localReader.ReadEndElement(); return keyIdentifier; }
public void ReadWrappedKeySecurityTokenImplCheck () { SecurityTokenResolver tokenResolver = GetResolver (new X509SecurityToken (cert)); XmlReader reader = XmlReader.Create (new StringReader (wrapped_key1)); WSSecurityTokenSerializer serializer = WSSecurityTokenSerializer.DefaultInstance; EncryptedKey ek = new EncryptedKey (); ek.LoadXml (new XmlDocument ().ReadNode (reader) as XmlElement); SecurityKeyIdentifier ki = new SecurityKeyIdentifier (); foreach (KeyInfoClause kic in ek.KeyInfo) ki.Add (serializer.ReadKeyIdentifierClause (new XmlNodeReader (kic.GetXml ()))); SecurityToken token = tokenResolver.ResolveToken (ki); string alg = ek.EncryptionMethod.KeyAlgorithm; SecurityKey skey = token.SecurityKeys [0]; Assert.IsTrue (skey is X509AsymmetricSecurityKey, "#1"); Assert.IsTrue (skey.IsSupportedAlgorithm (alg), "#2"); Assert.AreEqual ( EncryptedXml.DecryptKey (ek.CipherData.CipherValue, cert.PrivateKey as RSA, true), skey.DecryptKey (alg, ek.CipherData.CipherValue), "#3"); byte [] key = skey.DecryptKey (alg, ek.CipherData.CipherValue); WrappedKeySecurityToken wk = new WrappedKeySecurityToken (ek.Id, key, alg, token, ki); Assert.AreEqual ( EncryptedXml.DecryptKey (ek.CipherData.CipherValue, cert.PrivateKey as RSA, true), skey.DecryptKey (alg, wk.GetWrappedKey ()), "#4"); }
public static void ReadRSTXml(XmlReader reader, RequestSecurityToken rst, WSTrustSerializationContext context, WSTrustConstantsAdapter trustConstants) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } if (rst == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rst"); } if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); } if (trustConstants == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("trustConstants"); } bool isEmptyElement = false; if (reader.IsStartElement(trustConstants.Elements.TokenType, trustConstants.NamespaceURI)) { rst.TokenType = reader.ReadElementContentAsString(); if (!UriUtil.CanCreateValidUri(rst.TokenType, UriKind.Absolute)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3135, trustConstants.Elements.TokenType, trustConstants.NamespaceURI, rst.TokenType))); } return; } if (reader.IsStartElement(trustConstants.Elements.RequestType, trustConstants.NamespaceURI)) { rst.RequestType = WSTrustSerializationHelper.ReadRequestType(reader, trustConstants); return; } if (reader.IsStartElement(WSPolicyConstants.ElementNames.AppliesTo, WSPolicyConstants.NamespaceURI)) { rst.AppliesTo = WSTrustSerializationHelper.ReadAppliesTo(reader, trustConstants); return; } if (reader.IsStartElement(trustConstants.Elements.Issuer, trustConstants.NamespaceURI)) { rst.Issuer = WSTrustSerializationHelper.ReadOnBehalfOfIssuer(reader, trustConstants); return; } if (reader.IsStartElement(trustConstants.Elements.ProofEncryption, trustConstants.NamespaceURI)) { if (!reader.IsEmptyElement) { rst.ProofEncryption = new SecurityTokenElement(WSTrustSerializationHelper.ReadInnerXml(reader), context.SecurityTokenHandlers); } if (rst.ProofEncryption == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3218))); } return; } if (reader.IsStartElement(trustConstants.Elements.Encryption, trustConstants.NamespaceURI)) { if (!reader.IsEmptyElement) { rst.Encryption = new SecurityTokenElement(WSTrustSerializationHelper.ReadInnerXml(reader), context.SecurityTokenHandlers); } if (rst.Encryption == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3268))); } return; } if (reader.IsStartElement(trustConstants.Elements.DelegateTo, trustConstants.NamespaceURI)) { if (!reader.IsEmptyElement) { rst.DelegateTo = new SecurityTokenElement(WSTrustSerializationHelper.ReadInnerXml(reader), context.SecurityTokenHandlers); } if (rst.DelegateTo == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3219))); } return; } if (reader.IsStartElement(trustConstants.Elements.Claims, trustConstants.NamespaceURI)) { // According to trust specification, Trust13 requires Claims\@Dialect attribute but not TrustFeb2005. // Even for Trust13, the Dialect Uri is open. After research, "http://schemas.xmlsoap.org/ws/2005/05/identity" // seems to be the most common and IDFx will use that if none defined. // Our implementation is, for reading/writing, we will be looking specifically for // "http://docs.oasis-open.org/wsfed/authorization/200706/authclaims" (as defined in ws-federation) // and fallback to "http://schemas.xmlsoap.org/ws/2005/05/identity" for others. // This would also tolerate WCF Orcas which send us "http://schemas.xmlsoap.org/ws/2005/05/IdentityClaims" // as dialect. rst.Claims.Dialect = reader.GetAttribute(trustConstants.Attributes.Dialect); if ((rst.Claims.Dialect != null) && !UriUtil.CanCreateValidUri(rst.Claims.Dialect, UriKind.Absolute)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3136, trustConstants.Attributes.Dialect, reader.LocalName, reader.NamespaceURI, rst.Claims.Dialect))); } string ns = WSTrustSerializationHelper.GetRequestClaimNamespace(rst.Claims.Dialect); isEmptyElement = reader.IsEmptyElement; reader.ReadStartElement(trustConstants.Elements.Claims, trustConstants.NamespaceURI); if (!isEmptyElement) { while (reader.IsStartElement(WSIdentityConstants.Elements.ClaimType, ns)) { isEmptyElement = reader.IsEmptyElement; string claimType = reader.GetAttribute(WSIdentityConstants.Attributes.Uri); if (string.IsNullOrEmpty(claimType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3009))); } bool isOptional = false; string optionalAttributeVal = reader.GetAttribute(WSIdentityConstants.Attributes.Optional); if (!string.IsNullOrEmpty(optionalAttributeVal)) { isOptional = XmlConvert.ToBoolean(optionalAttributeVal); } reader.Read(); reader.MoveToContent(); string value = null; if (!isEmptyElement) { if (reader.IsStartElement(WSAuthorizationConstants.Elements.Value, ns)) { if (!StringComparer.Ordinal.Equals(rst.Claims.Dialect, WSAuthorizationConstants.Dialect)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3258, rst.Claims.Dialect, WSAuthorizationConstants.Dialect))); } else { // Value only supported for ws-federation authclaims value = reader.ReadElementContentAsString(WSAuthorizationConstants.Elements.Value, ns); } } reader.ReadEndElement(); } rst.Claims.Add(new RequestClaim(claimType, isOptional, value)); } reader.ReadEndElement(); } return; } if (reader.IsStartElement(trustConstants.Elements.Entropy, trustConstants.NamespaceURI)) { isEmptyElement = reader.IsEmptyElement; reader.ReadStartElement(trustConstants.Elements.Entropy, trustConstants.NamespaceURI); if (!isEmptyElement) { ProtectedKey protectedKey = ReadProtectedKey(reader, context, trustConstants); if (protectedKey == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3026))); } rst.Entropy = new Entropy(protectedKey); reader.ReadEndElement(); } if (rst.Entropy == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3026))); } return; } if (reader.IsStartElement(trustConstants.Elements.BinaryExchange, trustConstants.NamespaceURI)) { rst.BinaryExchange = ReadBinaryExchange(reader, trustConstants); return; } if (reader.IsStartElement(trustConstants.Elements.Lifetime, trustConstants.NamespaceURI)) { rst.Lifetime = WSTrustSerializationHelper.ReadLifetime(reader, trustConstants); return; } if (reader.IsStartElement(trustConstants.Elements.RenewTarget, trustConstants.NamespaceURI)) { isEmptyElement = reader.IsEmptyElement; if (!isEmptyElement) { rst.RenewTarget = new SecurityTokenElement(WSTrustSerializationHelper.ReadInnerXml(reader), context.SecurityTokenHandlers); } if (rst.RenewTarget == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3151))); } return; } if (reader.IsStartElement(trustConstants.Elements.OnBehalfOf, trustConstants.NamespaceURI)) { if (!reader.IsEmptyElement) { // Check that we have the SecurityTokenHandlerCollection that we need for OnBehalfOf. If not, then fail now. if (context.SecurityTokenHandlerCollectionManager.ContainsKey(SecurityTokenHandlerCollectionManager.Usage.OnBehalfOf)) { rst.OnBehalfOf = new SecurityTokenElement(WSTrustSerializationHelper.ReadInnerXml(reader), context.SecurityTokenHandlerCollectionManager[SecurityTokenHandlerCollectionManager.Usage.OnBehalfOf]); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3264))); } } if (rst.OnBehalfOf == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3152))); } return; } if (reader.IsStartElement(WSTrust14Constants.ElementNames.ActAs, WSTrust14Constants.NamespaceURI)) { if (!reader.IsEmptyElement) { // Check that we have the SecurityTokenHandlerCollection that we need for ActAs. If not, then fail now. if (context.SecurityTokenHandlerCollectionManager.ContainsKey(SecurityTokenHandlerCollectionManager.Usage.ActAs)) { rst.ActAs = new SecurityTokenElement(WSTrustSerializationHelper.ReadInnerXml(reader), context.SecurityTokenHandlerCollectionManager[SecurityTokenHandlerCollectionManager.Usage.ActAs]); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3265))); } } if (rst.ActAs == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3153))); } return; } if (reader.IsStartElement(trustConstants.Elements.KeyType, trustConstants.NamespaceURI)) { rst.KeyType = WSTrustSerializationHelper.ReadKeyType(reader, trustConstants); return; } if (reader.IsStartElement(trustConstants.Elements.KeySize, trustConstants.NamespaceURI)) { if (!reader.IsEmptyElement) { rst.KeySizeInBits = int.Parse(reader.ReadElementContentAsString(), CultureInfo.InvariantCulture); } if (rst.KeySizeInBits == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3154))); } return; } if (reader.IsStartElement(trustConstants.Elements.UseKey, trustConstants.NamespaceURI)) { isEmptyElement = reader.IsEmptyElement; reader.ReadStartElement(); if (!isEmptyElement) { if (!context.SecurityTokenHandlers.CanReadToken(reader)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3165))); } SecurityToken originalUseKeyToken = context.SecurityTokenHandlers.ReadToken(reader); SecurityKeyIdentifier useKeySki = new SecurityKeyIdentifier(); if (originalUseKeyToken.CanCreateKeyIdentifierClause<RsaKeyIdentifierClause>()) { useKeySki.Add(originalUseKeyToken.CreateKeyIdentifierClause<RsaKeyIdentifierClause>()); } else if (originalUseKeyToken.CanCreateKeyIdentifierClause<X509RawDataKeyIdentifierClause>()) { useKeySki.Add(originalUseKeyToken.CreateKeyIdentifierClause<X509RawDataKeyIdentifierClause>()); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3166))); } // Ensure that the provided UseKey SKI can be resolved by the UseKeyTokenResolver. // This provides proof of possession because the keys in that resolver are ones that the client has used for signature. SecurityToken resolvedUseKeyToken; if (!context.UseKeyTokenResolver.TryResolveToken(useKeySki, out resolvedUseKeyToken)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID3092, useKeySki))); } rst.UseKey = new UseKey(useKeySki, resolvedUseKeyToken); reader.ReadEndElement(); } if (rst.UseKey == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3155))); } return; } if (reader.IsStartElement(trustConstants.Elements.SignWith, trustConstants.NamespaceURI)) { rst.SignWith = reader.ReadElementContentAsString(); if (!UriUtil.CanCreateValidUri(rst.SignWith, UriKind.Absolute)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3135, trustConstants.Elements.SignWith, trustConstants.NamespaceURI, rst.SignWith))); } return; } if (reader.IsStartElement(trustConstants.Elements.EncryptWith, trustConstants.NamespaceURI)) { rst.EncryptWith = reader.ReadElementContentAsString(); if (!UriUtil.CanCreateValidUri(rst.EncryptWith, UriKind.Absolute)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3135, trustConstants.Elements.EncryptWith, trustConstants.NamespaceURI, rst.EncryptWith))); } return; } if (reader.IsStartElement(trustConstants.Elements.ComputedKeyAlgorithm, trustConstants.NamespaceURI)) { rst.ComputedKeyAlgorithm = ReadComputedKeyAlgorithm(reader, trustConstants); return; } if (reader.IsStartElement(trustConstants.Elements.AuthenticationType, trustConstants.NamespaceURI)) { rst.AuthenticationType = reader.ReadElementContentAsString(trustConstants.Elements.AuthenticationType, trustConstants.NamespaceURI); if (!UriUtil.CanCreateValidUri(rst.AuthenticationType, UriKind.Absolute)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3135, trustConstants.Elements.AuthenticationType, trustConstants.NamespaceURI, rst.AuthenticationType))); } return; } if (reader.IsStartElement(trustConstants.Elements.EncryptionAlgorithm, trustConstants.NamespaceURI)) { rst.EncryptionAlgorithm = reader.ReadElementContentAsString(trustConstants.Elements.EncryptionAlgorithm, trustConstants.NamespaceURI); if (!UriUtil.CanCreateValidUri(rst.EncryptionAlgorithm, UriKind.Absolute)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3135, trustConstants.Elements.EncryptionAlgorithm, trustConstants.NamespaceURI, rst.EncryptionAlgorithm))); } return; } if (reader.IsStartElement(trustConstants.Elements.CanonicalizationAlgorithm, trustConstants.NamespaceURI)) { rst.CanonicalizationAlgorithm = reader.ReadElementContentAsString(trustConstants.Elements.CanonicalizationAlgorithm, trustConstants.NamespaceURI); if (!UriUtil.CanCreateValidUri(rst.CanonicalizationAlgorithm, UriKind.Absolute)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3135, trustConstants.Elements.CanonicalizationAlgorithm, trustConstants.NamespaceURI, rst.CanonicalizationAlgorithm))); } return; } if (reader.IsStartElement(trustConstants.Elements.SignatureAlgorithm, trustConstants.NamespaceURI)) { rst.SignatureAlgorithm = reader.ReadElementContentAsString(trustConstants.Elements.SignatureAlgorithm, trustConstants.NamespaceURI); if (!UriUtil.CanCreateValidUri(rst.SignatureAlgorithm, UriKind.Absolute)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3135, trustConstants.Elements.SignatureAlgorithm, trustConstants.NamespaceURI, rst.SignatureAlgorithm))); } return; } if (reader.IsStartElement(trustConstants.Elements.Forwardable, trustConstants.NamespaceURI)) { rst.Forwardable = reader.ReadElementContentAsBoolean(); return; } if (reader.IsStartElement(trustConstants.Elements.Delegatable, trustConstants.NamespaceURI)) { rst.Delegatable = reader.ReadElementContentAsBoolean(); return; } if (reader.IsStartElement(trustConstants.Elements.AllowPostdating, trustConstants.NamespaceURI)) { rst.AllowPostdating = true; isEmptyElement = reader.IsEmptyElement; reader.Read(); reader.MoveToContent(); if (!isEmptyElement) { reader.ReadEndElement(); } return; } if (reader.IsStartElement(trustConstants.Elements.Renewing, trustConstants.NamespaceURI)) { isEmptyElement = reader.IsEmptyElement; string attrValue = reader.GetAttribute(trustConstants.Attributes.Allow); bool allowRenewal = true; bool renewalAfterExpiration = false; if (!string.IsNullOrEmpty(attrValue)) { allowRenewal = XmlConvert.ToBoolean(attrValue); } attrValue = reader.GetAttribute(trustConstants.Attributes.OK); if (!string.IsNullOrEmpty(attrValue)) { renewalAfterExpiration = XmlConvert.ToBoolean(attrValue); } rst.Renewing = new Renewing(allowRenewal, renewalAfterExpiration); reader.Read(); reader.MoveToContent(); if (!isEmptyElement) { reader.ReadEndElement(); } return; } if (reader.IsStartElement(trustConstants.Elements.CancelTarget, trustConstants.NamespaceURI)) { if (!reader.IsEmptyElement) { rst.CancelTarget = new SecurityTokenElement(WSTrustSerializationHelper.ReadInnerXml(reader), context.SecurityTokenHandlers); } if (rst.CancelTarget == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3220))); } return; } if (reader.IsStartElement(trustConstants.Elements.Participants, trustConstants.NamespaceURI)) { EndpointReference primary = null; List<EndpointReference> participants = new List<EndpointReference>(); isEmptyElement = reader.IsEmptyElement; reader.Read(); reader.MoveToContent(); if (!isEmptyElement) { if (reader.IsStartElement(trustConstants.Elements.Primary, trustConstants.NamespaceURI)) { reader.ReadStartElement(trustConstants.Elements.Primary, trustConstants.NamespaceURI); primary = EndpointReference.ReadFrom(XmlDictionaryReader.CreateDictionaryReader(reader)); reader.ReadEndElement(); } while (reader.IsStartElement(trustConstants.Elements.Participant, trustConstants.NamespaceURI)) { reader.ReadStartElement(trustConstants.Elements.Participant, trustConstants.NamespaceURI); participants.Add(EndpointReference.ReadFrom(XmlDictionaryReader.CreateDictionaryReader(reader))); reader.ReadEndElement(); } if (reader.IsStartElement()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3223, trustConstants.Elements.Participants, trustConstants.NamespaceURI, reader.LocalName, reader.NamespaceURI))); } rst.Participants = new Participants(); rst.Participants.Primary = primary; rst.Participants.Participant.AddRange(participants); reader.ReadEndElement(); } return; } if (reader.IsStartElement(WSAuthorizationConstants.Elements.AdditionalContext, WSAuthorizationConstants.Namespace)) { rst.AdditionalContext = new AdditionalContext(); isEmptyElement = reader.IsEmptyElement; reader.Read(); reader.MoveToContent(); if (!isEmptyElement) { while (reader.IsStartElement(WSAuthorizationConstants.Elements.ContextItem, WSAuthorizationConstants.Namespace)) { Uri name = null; Uri scope = null; string value = null; string attrValue = reader.GetAttribute(WSAuthorizationConstants.Attributes.Name); if (string.IsNullOrEmpty(attrValue) || !UriUtil.TryCreateValidUri(attrValue, UriKind.Absolute, out name)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException( SR.GetString(SR.ID3136, WSAuthorizationConstants.Attributes.Name, reader.LocalName, reader.NamespaceURI, attrValue))); } attrValue = reader.GetAttribute(WSAuthorizationConstants.Attributes.Scope); if (!string.IsNullOrEmpty(attrValue) && !UriUtil.TryCreateValidUri(attrValue, UriKind.Absolute, out scope)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException( SR.GetString(SR.ID3136, WSAuthorizationConstants.Attributes.Scope, reader.LocalName, reader.NamespaceURI, attrValue))); } if (reader.IsEmptyElement) { reader.Read(); } else { reader.Read(); if (reader.IsStartElement(WSAuthorizationConstants.Elements.Value, WSAuthorizationConstants.Namespace)) { value = reader.ReadElementContentAsString(WSAuthorizationConstants.Elements.Value, WSAuthorizationConstants.Namespace); } reader.ReadEndElement(); } rst.AdditionalContext.Items.Add(new ContextItem(name, value, scope)); } if (reader.IsStartElement()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3223, WSAuthorizationConstants.Elements.AdditionalContext, WSAuthorizationConstants.Namespace, reader.LocalName, reader.NamespaceURI))); } reader.ReadEndElement(); } return; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3007, reader.LocalName, reader.NamespaceURI))); }
WrappedKeySecurityToken ReadWrappedKeySecurityTokenCore ( XmlReader reader, SecurityTokenResolver tokenResolver) { if (tokenResolver == null) throw new ArgumentNullException ("tokenResolver"); EncryptedKey ek = new EncryptedKey (); ek.LoadXml (new XmlDocument ().ReadNode (reader) as XmlElement); SecurityKeyIdentifier ki = new SecurityKeyIdentifier (); foreach (KeyInfoClause kic in ek.KeyInfo) ki.Add (ReadKeyIdentifierClause (new XmlNodeReader (kic.GetXml ()))); SecurityToken token = tokenResolver.ResolveToken (ki); string alg = ek.EncryptionMethod.KeyAlgorithm; foreach (SecurityKey skey in token.SecurityKeys) if (skey.IsSupportedAlgorithm (alg)) { byte [] key = skey.DecryptKey (alg, ek.CipherData.CipherValue); WrappedKeySecurityToken wk = new WrappedKeySecurityToken (ek.Id, key, alg, token, ki); // FIXME: This should not be required. wk.SetWrappedKey (ek.CipherData.CipherValue); wk.ReferenceList = ek.ReferenceList; return wk; } throw new InvalidOperationException (String.Format ("Cannot resolve security key with the resolved SecurityToken specified by the key identifier in the EncryptedKey XML. The key identifier is: {0}", ki)); }
protected override SecurityKeyIdentifier ReadKeyIdentifierCore(XmlReader reader) { XmlDictionaryReader localReader = XmlDictionaryReader.CreateDictionaryReader(reader); localReader.ReadStartElement(XD.XmlSignatureDictionary.KeyInfo, XD.XmlSignatureDictionary.Namespace); SecurityKeyIdentifier keyIdentifier = new SecurityKeyIdentifier(); while (localReader.IsStartElement()) { SecurityKeyIdentifierClause clause = this.InnerSecurityTokenSerializer.ReadKeyIdentifierClause(localReader); if (clause == null) { localReader.Skip(); } else { keyIdentifier.Add(clause); } } if (keyIdentifier.Count == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ErrorDeserializingKeyIdentifierClause))); } localReader.ReadEndElement(); return keyIdentifier; }
/// <summary> /// Adds a specific <see cref="SecurityKey"/> to sign tokens issued by the OpenID Connect server. /// </summary> /// <param name="credentials">The options used to configure the OpenID Connect server.</param> /// <param name="key">The key used to sign security tokens issued by the server.</param> /// <returns>The signing credentials.</returns> public static IList <SigningCredentials> AddKey( [NotNull] this IList <SigningCredentials> credentials, [NotNull] SecurityKey key) { if (credentials == null) { throw new ArgumentNullException(nameof(credentials)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } if (key.IsSupportedAlgorithm(SecurityAlgorithms.RsaSha256Signature)) { var x509SecurityKey = key as X509SecurityKey; if (x509SecurityKey != null) { return(credentials.AddCertificate(x509SecurityKey.Certificate)); } var x509AsymmetricSecurityKey = key as X509AsymmetricSecurityKey; if (x509AsymmetricSecurityKey != null) { // The X.509 certificate is not directly accessible when using X509AsymmetricSecurityKey. // Reflection is the only way to get the certificate used to create the security key. var field = typeof(X509AsymmetricSecurityKey).GetField( name: "certificate", bindingAttr: BindingFlags.Instance | BindingFlags.NonPublic); Debug.Assert(field != null); return(credentials.AddCertificate((X509Certificate2)field.GetValue(x509AsymmetricSecurityKey))); } // Create an empty security key identifier. var identifier = new SecurityKeyIdentifier(); var rsaSecurityKey = key as RsaSecurityKey; if (rsaSecurityKey != null) { // Resolve the underlying algorithm from the security key. var algorithm = (RSA)rsaSecurityKey.GetAsymmetricAlgorithm( algorithm: SecurityAlgorithms.RsaSha256Signature, requiresPrivateKey: false); Debug.Assert(algorithm != null, "SecurityKey.GetAsymmetricAlgorithm() shouldn't return a null algorithm."); // Export the RSA public key to extract a key identifier based on the modulus component. var parameters = algorithm.ExportParameters(includePrivateParameters: false); Debug.Assert(parameters.Modulus != null, "RSA.ExportParameters() shouldn't return a null modulus."); // Only use the 40 first chars of the base64url-encoded modulus. var kid = Base64UrlEncoder.Encode(parameters.Modulus); kid = kid.Substring(0, Math.Min(kid.Length, 40)).ToUpperInvariant(); identifier.Add(new RsaKeyIdentifierClause(algorithm)); identifier.Add(new LocalIdKeyIdentifierClause(kid)); } // Mark the security key identifier as read-only to // ensure it can't be altered during a request. identifier.MakeReadOnly(); credentials.Add(new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest, identifier)); return(credentials); } else if (key.IsSupportedAlgorithm(SecurityAlgorithms.HmacSha256Signature)) { // When using an in-memory symmetric key, no identifier clause can be inferred from the key itself. // To prevent the built-in security token handlers from throwing an exception, a default identifier is added. var identifier = new SecurityKeyIdentifier(new LocalIdKeyIdentifierClause("Default")); // Mark the security key identifier as read-only to // ensure it can't be altered during a request. identifier.MakeReadOnly(); credentials.Add(new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest, identifier)); return(credentials); } throw new InvalidOperationException("A signature algorithm cannot be automatically inferred from the signing key. " + "Consider using 'options.SigningCredentials.Add(SigningCredentials)' instead."); }
/// <summary> /// Adds a specific <see cref="SecurityKey"/> to decrypt /// authorization requests received by the OpenID Connect server. /// </summary> /// <param name="credentials">The options used to configure the OpenID Connect server.</param> /// <param name="key">The key used to sign security tokens issued by the server.</param> /// <returns>The encryption credentials.</returns> public static IList <EncryptingCredentials> AddKey( [NotNull] this IList <EncryptingCredentials> credentials, [NotNull] SecurityKey key) { if (credentials == null) { throw new ArgumentNullException(nameof(credentials)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } if (key.IsSupportedAlgorithm(SecurityAlgorithms.RsaOaepKeyWrap)) { var x509SecurityKey = key as X509SecurityKey; if (x509SecurityKey != null) { return(credentials.AddCertificate(x509SecurityKey.Certificate)); } var x509AsymmetricSecurityKey = key as X509AsymmetricSecurityKey; if (x509AsymmetricSecurityKey != null) { // The X.509 certificate is not directly accessible when using X509AsymmetricSecurityKey. // Reflection is the only way to get the certificate used to create the security key. var field = typeof(X509AsymmetricSecurityKey).GetField( name: "certificate", bindingAttr: BindingFlags.Instance | BindingFlags.NonPublic); Debug.Assert(field != null); return(credentials.AddCertificate((X509Certificate2)field.GetValue(x509AsymmetricSecurityKey))); } // Create an empty security key identifier. var identifier = new SecurityKeyIdentifier(); var rsaSecurityKey = key as RsaSecurityKey; if (rsaSecurityKey != null) { // When using a RSA key, the public part is used to uniquely identify the key. var algorithm = (RSA)rsaSecurityKey.GetAsymmetricAlgorithm( algorithm: SecurityAlgorithms.RsaOaepKeyWrap, requiresPrivateKey: false); Debug.Assert(algorithm != null); // Export the RSA public key to extract a key identifier based on the modulus component. var parameters = algorithm.ExportParameters(includePrivateParameters: false); // Only use the 40 first chars of the base64url-encoded modulus. var kid = Base64UrlEncoder.Encode(parameters.Modulus); kid = kid.Substring(0, Math.Min(kid.Length, 40)).ToUpperInvariant(); identifier.Add(new LocalIdKeyIdentifierClause(kid)); identifier.Add(new RsaKeyIdentifierClause(algorithm)); } credentials.Add(new EncryptingCredentials(key, identifier, SecurityAlgorithms.RsaOaepKeyWrap)); return(credentials); } else if (key.IsSupportedAlgorithm(SecurityAlgorithms.Aes256Encryption)) { // When using an in-memory symmetric key, no identifier clause can be inferred from the key itself. // To prevent the built-in security token handlers from throwing an exception, a default identifier is added. var identifier = new SecurityKeyIdentifier(new LocalIdKeyIdentifierClause("Default")); credentials.Add(new EncryptingCredentials(key, identifier, SecurityAlgorithms.Aes256Encryption)); return(credentials); } throw new InvalidOperationException("The encryption key type is not supported."); }
EncryptedKeyIdentifierClause ReadEncryptedKeyIdentifierClause ( XmlReader reader) { string encNS = EncryptedXml.XmlEncNamespaceUrl; string id = reader.GetAttribute ("Id", Constants.WsuNamespace); reader.Read (); reader.MoveToContent (); string encMethod = reader.GetAttribute ("Algorithm"); bool isEmpty = reader.IsEmptyElement; reader.ReadStartElement ("EncryptionMethod", encNS); string digMethod = null; if (!isEmpty) { reader.MoveToContent (); if (reader.LocalName == "DigestMethod" && reader.NamespaceURI == SignedXml.XmlDsigNamespaceUrl) digMethod = reader.GetAttribute ("Algorithm"); while (reader.NodeType != XmlNodeType.EndElement) { reader.Skip (); reader.MoveToContent (); } reader.ReadEndElement (); } reader.MoveToContent (); SecurityKeyIdentifier ki = null; if (!reader.IsEmptyElement) { reader.ReadStartElement ("KeyInfo", SignedXml.XmlDsigNamespaceUrl); reader.MoveToContent (); SecurityKeyIdentifierClause kic = ReadKeyIdentifierClauseCore (reader); ki = new SecurityKeyIdentifier (); ki.Add (kic); reader.MoveToContent (); reader.ReadEndElement (); // </ds:KeyInfo> reader.MoveToContent (); } byte [] keyValue = null; if (!reader.IsEmptyElement) { reader.ReadStartElement ("CipherData", encNS); reader.MoveToContent (); keyValue = Convert.FromBase64String (reader.ReadElementContentAsString ("CipherValue", encNS)); reader.MoveToContent (); reader.ReadEndElement (); // CipherData } string carriedKeyName = null; if (!reader.IsEmptyElement && reader.LocalName == "CarriedKeyName" && reader.NamespaceURI == encNS) { carriedKeyName = reader.ReadElementContentAsString (); reader.MoveToContent (); } // FIXME: handle derived keys?? return new EncryptedKeyIdentifierClause (keyValue, encMethod, ki, carriedKeyName); }
public static SecurityKeyIdentifier GetKeyIdentifier(this SecurityKey key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } SecurityKeyIdentifier identifier = null; X509Certificate2 certificate = null; var x509SecurityKey = key as X509SecurityKey; if (x509SecurityKey != null) { certificate = x509SecurityKey.Certificate; } var x509AsymmetricSecurityKey = key as X509AsymmetricSecurityKey; if (x509AsymmetricSecurityKey != null) { // The X.509 certificate is not directly accessible when using X509AsymmetricSecurityKey. // Reflection is the only way to get the certificate used to create the security key. var field = typeof(X509AsymmetricSecurityKey).GetField( name: "certificate", bindingAttr: BindingFlags.Instance | BindingFlags.NonPublic); Debug.Assert(field != null, "The 'certificate' field shouldn't be missing."); certificate = (X509Certificate2)field.GetValue(x509AsymmetricSecurityKey); } if (certificate != null) { identifier = new SecurityKeyIdentifier { new X509IssuerSerialKeyIdentifierClause(x509SecurityKey.Certificate), new X509RawDataKeyIdentifierClause(x509SecurityKey.Certificate), new X509ThumbprintKeyIdentifierClause(x509SecurityKey.Certificate), new LocalIdKeyIdentifierClause(x509SecurityKey.Certificate.Thumbprint.ToUpperInvariant()), new NamedKeySecurityKeyIdentifierClause(JwtHeaderParameterNames.X5t, x509SecurityKey.Certificate.Thumbprint.ToUpperInvariant()) }; } if (identifier == null) { // Create an empty security key identifier. identifier = new SecurityKeyIdentifier(); var rsaSecurityKey = key as RsaSecurityKey; if (rsaSecurityKey != null) { // Resolve the underlying algorithm from the security key. var algorithm = (RSA)rsaSecurityKey.GetAsymmetricAlgorithm( algorithm: SecurityAlgorithms.RsaSha256Signature, requiresPrivateKey: false); Debug.Assert(algorithm != null, "SecurityKey.GetAsymmetricAlgorithm() shouldn't return a null algorithm."); // Export the RSA public key to extract a key identifier based on the modulus component. var parameters = algorithm.ExportParameters(includePrivateParameters: false); Debug.Assert(parameters.Modulus != null, "RSA.ExportParameters() shouldn't return a null modulus."); // Only use the 40 first chars of the base64url-encoded modulus. var kid = Base64UrlEncoder.Encode(parameters.Modulus); kid = kid.Substring(0, Math.Min(kid.Length, 40)).ToUpperInvariant(); identifier.Add(new RsaKeyIdentifierClause(algorithm)); identifier.Add(new LocalIdKeyIdentifierClause(kid)); identifier.Add(new NamedKeySecurityKeyIdentifierClause(JwtHeaderParameterNames.Kid, kid)); } } // Mark the security key identifier as read-only to // ensure it can't be altered during a request. identifier.MakeReadOnly(); return(identifier); }
public void ReadOnlyAdd () { SecurityKeyIdentifier ki = new SecurityKeyIdentifier (); ki.MakeReadOnly (); ki.Add (new LocalIdKeyIdentifierClause ("foo")); }