private static void SerializeCachedToken(Stream stream, Uri target, Uri issuer, GenericXmlSecurityToken token) { XmlTextWriter xmlTextWriter = new XmlTextWriter(stream, Encoding.UTF8); xmlTextWriter.WriteStartElement("Entry"); xmlTextWriter.WriteElementString("Target", target.AbsoluteUri); xmlTextWriter.WriteElementString("Issuer", (issuer == null) ? "" : issuer.AbsoluteUri); xmlTextWriter.WriteStartElement("Token"); xmlTextWriter.WriteStartElement("XML"); token.TokenXml.WriteTo(xmlTextWriter); xmlTextWriter.WriteEndElement(); SymmetricSecurityKey symmetricSecurityKey = (SymmetricSecurityKey)token.SecurityKeys[0]; xmlTextWriter.WriteElementString("Key", Convert.ToBase64String(symmetricSecurityKey.GetSymmetricKey())); xmlTextWriter.WriteElementString("Id", token.Id); xmlTextWriter.WriteElementString("ValidFrom", Convert.ToString(token.ValidFrom)); xmlTextWriter.WriteElementString("ValidTo", Convert.ToString(token.ValidTo)); WSSecurityTokenSerializer wssecurityTokenSerializer = new WSSecurityTokenSerializer(); xmlTextWriter.WriteStartElement("InternalTokenReference"); wssecurityTokenSerializer.WriteKeyIdentifierClause(xmlTextWriter, token.InternalTokenReference); xmlTextWriter.WriteEndElement(); xmlTextWriter.WriteStartElement("ExternalTokenReference"); wssecurityTokenSerializer.WriteKeyIdentifierClause(xmlTextWriter, token.ExternalTokenReference); xmlTextWriter.WriteEndElement(); xmlTextWriter.WriteEndElement(); xmlTextWriter.WriteEndElement(); xmlTextWriter.Flush(); stream.Flush(); }
public override byte[] GetSymmetricKey() { if (SymmetricSecurityKey == null) { return(null); } return(SymmetricSecurityKey.GetSymmetricKey()); }
byte [] GetEncryptionKeyForData(EncryptedData ed2, EncryptedXml encXml, byte [] dummyEncKey) { // Since ReferenceList could be embedded directly in wss_header without // key indication, it must iterate all the derived keys to find out // appropriate one. foreach (DerivedKeySecurityToken dk in header.FindAll <DerivedKeySecurityToken> ()) { if (dk.ReferenceList == null) { continue; } foreach (DataReference dr in dk.ReferenceList) { if (StripUri(dr.Uri) == ed2.Id) { return(((SymmetricSecurityKey)dk.SecurityKeys [0]).GetSymmetricKey()); } } } foreach (WrappedKeySecurityToken wk in header.FindAll <WrappedKeySecurityToken> ()) { if (wk.ReferenceList == null) { continue; } foreach (DataReference dr in wk.ReferenceList) { if (StripUri(dr.Uri) == ed2.Id) { return(((SymmetricSecurityKey)wk.SecurityKeys [0]).GetSymmetricKey()); } } } if (ed2.KeyInfo == null) { return(null); } foreach (KeyInfoClause kic in ed2.KeyInfo) { SecurityKeyIdentifierClause skic = serializer.ReadKeyIdentifierClause(new XmlNodeReader(kic.GetXml())); SecurityKey skey = null; if (!resolver.TryResolveSecurityKey(skic, out skey)) { throw new MessageSecurityException(String.Format("The signing key could not be resolved from {0}", skic)); } SymmetricSecurityKey ssk = skey as SymmetricSecurityKey; if (ssk != null) { return(ssk.GetSymmetricKey()); } } return(null); // no applicable key info clause. }
/// <summary> /// Initializes a new instance of the <see cref="SymmetricSignatureProvider"/> class that uses an <see cref="SymmetricSecurityKey"/> to create and / or verify signatures over a array of bytes. /// </summary> /// <param name="key">The <see cref="SymmetricSecurityKey"/> used for signing.</param> /// <param name="algorithm">The signature algorithm to use.</param> /// <exception cref="ArgumentNullException">'key' is null.</exception> /// <exception cref="ArgumentNullException">'algorithm' is null.</exception> /// <exception cref="ArgumentException">'algorithm' contains only whitespace.</exception> /// <exception cref="ArgumentOutOfRangeException">'<see cref="SymmetricSecurityKey"/>.KeySize' is smaller than <see cref="SignatureProviderFactory.MinimumSymmetricKeySizeInBits"/>.</exception> /// <exception cref="InvalidOperationException"><see cref="SymmetricSecurityKey.GetKeyedHashAlgorithm"/> throws.</exception> /// <exception cref="InvalidOperationException"><see cref="SymmetricSecurityKey.GetKeyedHashAlgorithm"/> returns null.</exception> /// <exception cref="InvalidOperationException"><see cref="SymmetricSecurityKey.GetSymmetricKey"/> throws.</exception> public SymmetricSignatureProvider(SymmetricSecurityKey key, string algorithm) { if (key == null) { throw new ArgumentNullException("key"); } if (null == algorithm) { throw new ArgumentNullException(algorithm); } if (string.IsNullOrWhiteSpace(algorithm)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10002, "algorithm")); } if (key.KeySize < SignatureProviderFactory.MinimumSymmetricKeySizeInBits) { throw new ArgumentOutOfRangeException("key.KeySize", key.KeySize, string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10603, key.GetType(), SignatureProviderFactory.MinimumSymmetricKeySizeInBits)); } try { this.keyedHash = key.GetKeyedHashAlgorithm(algorithm); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10632, algorithm, key, ex), ex); } if (this.keyedHash == null) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10633, algorithm, key)); } try { this.keyedHash.Key = key.GetSymmetricKey(); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10634, algorithm, key, ex), ex); } }
public bool IsSourceKeyEqual(SecurityToken token) { if (token.SecurityKeys.Count != 1) { return(false); } SymmetricSecurityKey key = token.SecurityKeys[0] as SymmetricSecurityKey; if (key == null) { return(false); } return(CryptoHelper.IsEqual(this.keyToDerive, key.GetSymmetricKey())); }
static public SecurityContextSecurityToken ConvertSessionTokenToSecurityContextSecurityToken(SessionSecurityToken token) { if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token"); } List <IAuthorizationPolicy> policies = new List <IAuthorizationPolicy>(); if (token.SctAuthorizationPolicy != null) { policies.Add(token.SctAuthorizationPolicy); } if (token.ClaimsPrincipal != null && token.ClaimsPrincipal.Identities != null) { policies.Add(new AuthorizationPolicy(token.ClaimsPrincipal.Identities)); } byte[] key = null; SymmetricSecurityKey symmetricKey = token.SecurityKeys[0] as SymmetricSecurityKey; if (symmetricKey != null) { key = symmetricKey.GetSymmetricKey(); } SecurityContextSecurityToken sct = new SecurityContextSecurityToken( token.ContextId, token.Id, key, token.ValidFrom, token.ValidTo, token.KeyGeneration, token.KeyEffectiveTime, token.KeyExpirationTime, policies.AsReadOnly()); return(sct); }
void ExtractSecurity() { if (security.MessageProtectionOrder == MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature && wss_header.Find <SignedXml> () != null) { throw new MessageSecurityException("The security binding element expects that the message signature is encrypted, while it isn't."); } WrappedKeySecurityToken wk = wss_header.Find <WrappedKeySecurityToken> (); DerivedKeySecurityToken dk = wss_header.Find <DerivedKeySecurityToken> (); if (wk != null) { if (Parameters.RequireDerivedKeys && dk == null) { throw new MessageSecurityException("DerivedKeyToken is required in this contract, but was not found in the message"); } } else { // FIXME: this is kind of hack for symmetric reply processing. wk = RequestSecurity.ProtectionToken != null ? RequestSecurity.ProtectionToken.SecurityToken as WrappedKeySecurityToken : null; } SymmetricSecurityKey wkkey = wk != null ? wk.SecurityKeys [0] as SymmetricSecurityKey : null; wss_header_reader.DecryptSecurity(this, wkkey, RequestSecurity != null ? RequestSecurity.EncryptionKey : null); // signature confirmation WSSignedXml sxml = wss_header.Find <WSSignedXml> (); if (sxml == null) { throw new MessageSecurityException("The the message signature is expected but not found."); } bool confirmed = false; SecurityKeyIdentifierClause sigClause = null; foreach (KeyInfoClause kic in sxml.KeyInfo) { SecurityTokenReferenceKeyInfo r = kic as SecurityTokenReferenceKeyInfo; if (r != null) { sigClause = r.Clause; } } if (sigClause == null) { throw new MessageSecurityException("SecurityTokenReference was not found in dsig:Signature KeyInfo."); } SecurityToken signToken; SecurityKey signKey; signToken = TokenResolver.ResolveToken(sigClause); signKey = signToken.ResolveKeyIdentifierClause(sigClause); SymmetricSecurityKey symkey = signKey as SymmetricSecurityKey; if (symkey != null) { confirmed = sxml.CheckSignature(new HMACSHA1(symkey.GetSymmetricKey())); if (wk != null) { // FIXME: authenticate token sec_prop.ProtectionToken = new SecurityTokenSpecification(wk, null); } } else { AsymmetricAlgorithm alg = ((AsymmetricSecurityKey)signKey).GetAsymmetricAlgorithm(security.DefaultSignatureAlgorithm, false); confirmed = sxml.CheckSignature(alg); sec_prop.InitiatorToken = new SecurityTokenSpecification( signToken, security.TokenAuthenticator.ValidateToken(signToken)); } if (!confirmed) { throw new MessageSecurityException("Message signature is invalid."); } // token authentication // FIXME: it might not be limited to recipient if (Direction == MessageDirection.Input) { ProcessSupportingTokens(sxml); } sec_prop.EncryptionKey = ((SymmetricSecurityKey)wk.SecurityKeys [0]).GetSymmetricKey(); sec_prop.ConfirmedSignatures.Add(Convert.ToBase64String(sxml.SignatureValue)); }
private static bool AreSecurityKeysEqual(SecurityKey securityKey1, SecurityKey securityKey2, CompareContext context) { if (context.IgnoreType && (securityKey1.GetType() != securityKey2.GetType())) { return(false); } // Check X509SecurityKey first so we don't have to use reflection to get cert. X509SecurityKey x509Key1 = securityKey1 as X509SecurityKey; if (x509Key1 != null) { X509SecurityKey x509Key2 = securityKey2 as X509SecurityKey; if (x509Key1.Certificate.Thumbprint == x509Key2.Certificate.Thumbprint) { return(true); } return(false); } X509AsymmetricSecurityKey x509AsymmKey1 = securityKey1 as X509AsymmetricSecurityKey; if (x509AsymmKey1 != null) { X509AsymmetricSecurityKey x509AsymmKey2 = securityKey2 as X509AsymmetricSecurityKey; X509Certificate2 x509Cert1 = TestUtilities.GetField(x509AsymmKey1, "certificate") as X509Certificate2; X509Certificate2 x509Cert2 = TestUtilities.GetField(x509AsymmKey2, "certificate") as X509Certificate2; if (x509Cert1 == null && x509Cert2 == null) { return(true); } if (x509Cert1 == null || x509Cert2 == null) { return(false); } if (x509Cert1.Thumbprint != x509Cert2.Thumbprint) { return(false); } } SymmetricSecurityKey symKey1 = securityKey1 as SymmetricSecurityKey; if (symKey1 != null) { SymmetricSecurityKey symKey2 = securityKey2 as SymmetricSecurityKey; if (!AreBytesEqual(symKey1.GetSymmetricKey(), symKey2.GetSymmetricKey())) { return(false); } } RsaSecurityKey rsaKey = securityKey1 as RsaSecurityKey; if (rsaKey != null) { RSA rsa1 = (rsaKey.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, false)) as RSA; RSA rsa2 = ((securityKey2 as RsaSecurityKey).GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, false)) as RSA; if (!string.Equals(rsa1.ToXmlString(false), rsa2.ToXmlString(false), StringComparison.Ordinal)) { return(false); } } return(true); }
// returns the protection token public void DecryptSecurity(SecureMessageDecryptor decryptor, SymmetricSecurityKey sym, byte [] dummyEncKey) { WSEncryptedXml encXml = new WSEncryptedXml(doc); // default, unless overriden by the default DerivedKeyToken. Rijndael aes = RijndaelManaged.Create(); // it is reused with every key aes.Mode = CipherMode.CBC; if (sym == null) { throw new MessageSecurityException("Cannot find the encryption key in this message and context"); } // decrypt the body with the decrypted key Collection <string> references = new Collection <string> (); foreach (ReferenceList rlist in header.FindAll <ReferenceList> ()) { foreach (EncryptedReference encref in rlist) { references.Add(StripUri(encref.Uri)); } } foreach (WrappedKeySecurityToken wk in header.FindAll <WrappedKeySecurityToken> ()) { foreach (EncryptedReference er in wk.ReferenceList) { references.Add(StripUri(er.Uri)); } } Collection <XmlElement> list = new Collection <XmlElement> (); foreach (string uri in references) { XmlElement el = encXml.GetIdElement(doc, uri); if (el != null) { list.Add(el); } else { throw new MessageSecurityException(String.Format("On decryption, EncryptedData with Id '{0}', referenced by ReferenceData, was not found.", uri)); } } foreach (XmlElement el in list) { EncryptedData ed2 = CreateEncryptedData(el); byte [] key = GetEncryptionKeyForData(ed2, encXml, dummyEncKey); aes.Key = key != null ? key : sym.GetSymmetricKey(); byte [] decrypted = DecryptData(encXml, ed2, aes); encXml.ReplaceData(el, decrypted); EncryptedData existing; // if it was a header content, replace // corresponding one. if (encryptedDataList.TryGetValue(ed2.Id, out existing)) { // FIXME: it is kind of extraneous and could be replaced by XmlNodeReader //Console.WriteLine ("DECRYPTED EncryptedData:"); //Console.WriteLine (Encoding.UTF8.GetString (decrypted)); object o = ReadContent(XmlReader.Create(new MemoryStream(decrypted))); header.Contents.Remove(existing); header.Contents.Add(o); } } /* * Console.WriteLine ("======== Decrypted Document ========"); * doc.PreserveWhitespace = false; * doc.Save (Console.Out); * doc.PreserveWhitespace = true; */ }