/// -------------- Two Utility Methods (not used but may be useful) ----------- /// Generates an encryption key. public static byte[] GenerateEncryptionKey() { //Generate a Key. RijndaelManaged rm = new RijndaelManaged(); rm.GenerateKey(); return rm.Key; }
public static string EncodeEx(string data, out string hexKey) { RijndaelManaged aes = new RijndaelManaged(); aes.KeySize = 256; aes.BlockSize = 128; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.GenerateKey(); aes.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; var encrypt = aes.CreateEncryptor(aes.Key, aes.IV); byte[] xBuff = null; using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write)) { byte[] xXml = Encoding.UTF8.GetBytes(data); cs.Write(xXml, 0, xXml.Length); } xBuff = ms.ToArray(); } hexKey = BitConverter.ToString(aes.Key).Replace("-", ""); string result = Convert.ToBase64String(xBuff); return result; }
public static byte[] RandomKey(int length) { var alg = new RijndaelManaged(); alg.KeySize = length * 8; alg.GenerateKey(); return alg.Key; }
/// <summary> /// Create an AES key that is encrypted using a RSA certificate, this is the parsed version for increased efficiancy /// /// To create the parsed cert <see cref="Kalix.ApiCrypto.RSA.RSACertificateParser.ParsePublicCertificate"/> /// </summary> /// <param name="keySize">Required AES key size</param> /// <param name="rsaCert">RSA parsed public certificate used to sign</param> /// <returns>data that can be stored</returns> public static byte[] CreateBlob(AESKeySize keySize, RSAServiceProvider rsaCert) { int intKeySize; switch (keySize) { case AESKeySize.AES128: intKeySize = 128; break; case AESKeySize.AES192: intKeySize = 192; break; case AESKeySize.AES256: intKeySize = 256; break; default: throw new ArgumentOutOfRangeException("keySize", "Unknown key size"); } var aesProvider = new RijndaelManaged(); aesProvider.KeySize = intKeySize; aesProvider.GenerateKey(); // Encrypt using the RSA cert and return return rsaCert.EncryptValue(aesProvider.Key); }
public static byte[] GenerateKey() { RijndaelManaged provider = new RijndaelManaged(); provider.GenerateKey(); return provider.Key; }
public void CreateSymmetricKey() { symmetricAlgo = (RijndaelManaged)RijndaelManaged.Create(); symmetricAlgo.GenerateKey(); encryptedKey = ProtectedData.Protect(symmetricAlgo.Key, null, DataProtectionScope.CurrentUser); stream = new MemoryStream(); }
public static byte[] Encrypt(string unencryptedString) { using (var myRijndael = new RijndaelManaged()) { myRijndael.GenerateKey(); myRijndael.GenerateIV(); return EncryptStringToBytes(unencryptedString, myRijndael.Key, myRijndael.IV); } }
public Base64EncodedRijndaelKeyVectorPair() { RijndaelManaged rm = new RijndaelManaged(); rm.GenerateKey(); rm.GenerateIV(); this.Key = Convert.ToBase64String(rm.Key); this.IV = Convert.ToBase64String(rm.IV); }
static void Main(string[] args) { RijndaelManaged rm = new RijndaelManaged(); rm.GenerateKey(); rm.GenerateIV(); string key = Convert.ToBase64String(rm.Key); string iv = Convert.ToBase64String(rm.IV); }
/// <summary> /// Genera un segreto compatibile per la trasmissione in URL che deve essere protetto e condiviso dalle parti che vogliono scambiare i messaggi in maniera cifrata. /// </summary> /// <returns>Segreto</returns> public string GeneraSegreto() { using (var myRijndael = new RijndaelManaged()) { myRijndael.GenerateKey(); return HttpServerUtility.UrlTokenEncode(myRijndael.Key); } }
private System.Security.Cryptography.RijndaelManaged GetCryptographer() { System.Security.Cryptography.RijndaelManaged rijndaelManaged = new System.Security.Cryptography.RijndaelManaged(); rijndaelManaged.KeySize = 128; rijndaelManaged.GenerateIV(); rijndaelManaged.GenerateKey(); return(rijndaelManaged); }
public static string Decrypt(byte[] encryptedString) { using (var myRijndael = new RijndaelManaged()) { myRijndael.GenerateKey(); myRijndael.GenerateIV(); return DecryptStringFromBytes(encryptedString, myRijndael.Key, myRijndael.IV); } }
string GenerateNewKey() { using (var rijndael = new RijndaelManaged()) { rijndael.GenerateKey(); return Convert.ToBase64String(rijndael.Key); } }
public override void Process(Command command) { var options = this.LoadOptions<CommandOptions>((TextCommand)command); if (options.Modulus != null && options.Exponent != null && options.Algorithm != null) { var symmetric = new RijndaelManaged(); symmetric.GenerateKey(); var modulus = TextConversion.FromBase64String(options.Modulus); var exponent = TextConversion.FromBase64String(options.Exponent); var rsaparameters = new RSAParameters(); rsaparameters.Modulus = modulus; rsaparameters.Exponent = exponent; var rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(rsaparameters); var myrsa = new RSACryptoServiceProvider(); rsaparameters = myrsa.ExportParameters(false); Connection.WriteOk ( "Modulus", TextConversion.ToBase64String(rsaparameters.Modulus), "Exponent", TextConversion.ToBase64String(rsaparameters.Exponent), "IV", TextConversion.ToBase64String(new RSAPKCS1KeyExchangeFormatter(rsa).CreateKeyExchange(symmetric.IV)), "KeyExchange", TextConversion.ToBase64String(new RSAPKCS1KeyExchangeFormatter(rsa).CreateKeyExchange(symmetric.Key)) ); Connection.Flush(); if (options.WaitForReady) { Connection.ReadReady(); } } else if (options.Compress) { Connection.WriteOk(); Connection.Flush(); this.Connection.ReadStream = new InteractiveInflaterInputStream(this.Connection.RawReadStream, new Inflater(true)); this.Connection.WriteStream = new InteractiveDeflaterOutputStream(this.Connection.RawWriteStream, new Deflater(Deflater.DEFAULT_COMPRESSION, true), 512); if (options.WaitForReady) { Connection.ReadReady(); } } }
// no error??? public void GetSymmetricAlgorithmWrongSize2() { AES aes = new AES(); aes.KeySize = 192; aes.GenerateKey(); Key key = new Key(aes.Key); Assert.IsNotNull(key.GetSymmetricAlgorithm(SecurityAlgorithms.Aes256Encryption)); }
/// store a key into a text file static public bool CreateSecretKey(string ASecretKeyFile) { Rijndael alg = new RijndaelManaged(); alg.GenerateKey(); StreamWriter sw = new StreamWriter(ASecretKeyFile); sw.Write(Convert.ToBase64String(alg.Key)); sw.Close(); return true; }
public static SymmetricAlgorithm CreateAes() { var alg = new RijndaelManaged(); alg.GenerateKey(); alg.BlockSize = 128; alg.KeySize = 128; alg.Mode = CipherMode.ECB; alg.Padding = PaddingMode.None; return alg; }
public AESKeyAndIVGenerator () { rijndaelManaged = new RijndaelManaged(); rijndaelManaged.KeySize = 256; rijndaelManaged.GenerateKey (); rijndaelManaged.GenerateIV (); aesKey = rijndaelManaged.Key; aesIV = rijndaelManaged.IV; }
public static String generateKey() { System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged { KeySize = 128, Mode = System.Security.Cryptography.CipherMode.ECB, Padding = System.Security.Cryptography.PaddingMode.PKCS7 }; rm.GenerateKey(); return(Convert.ToBase64String(rm.Key)); }
/// <summary> /// Generates a new key /// </summary> public static string GenerateNewKey() { var rijndael = new RijndaelManaged { Mode = CipherMode.CBC, KeySize = 256, }; rijndael.GenerateKey(); return Convert.ToBase64String(rijndael.Key); }
//[MenuItem("Hugula AES/GenerateKey", false, 12)] public static void GenerateKey() { using (System.Security.Cryptography.RijndaelManaged myRijndael = new System.Security.Cryptography.RijndaelManaged()) { myRijndael.GenerateKey(); byte[] Key = myRijndael.Key; KeyVData KeyScri = ScriptableObject.CreateInstance <KeyVData>(); KeyScri.KEY = Key; AssetDatabase.CreateAsset(KeyScri, "Assets/Config/I81.asset"); Debug.Log("key Generate " + Key.Length); } }
/// <summary> /// 共通キーと初期化ベクトルを返す /// </summary> /// <param name="key">作成された共通キー</param> /// <param name="IV">作成された初期化ベクトル</param> public static void CreateKeys(out byte[] key, out byte[] IV) { using (RijndaelManaged aes = new RijndaelManaged()) { aes.KeySize = 256; aes.GenerateKey(); aes.GenerateIV(); key = aes.Key; IV = aes.IV; } }
//[MenuItem("Hugula AES/GenerateKey", false, 12)] public static void GenerateKey() { using (System.Security.Cryptography.RijndaelManaged myRijndael = new System.Security.Cryptography.RijndaelManaged()) { myRijndael.GenerateKey (); byte[] Key=myRijndael.Key; KeyVData KeyScri=ScriptableObject.CreateInstance<KeyVData>(); KeyScri.KEY=Key; AssetDatabase.CreateAsset(KeyScri,"Assets/Config/I81.asset"); Debug.Log("key Generate "+Key.Length); } }
private static byte[] GetKey(RijndaelManaged MyRijndael) { string sTemp = "LpdJ%H*1U7njd$jdj&HsFkd!kdF8348kz93kd(jdlk#00Dwz87aWdd0(Fkm9cGo5"; MyRijndael.GenerateKey(); byte[] bytTemp = MyRijndael.Key; int KeyLength = bytTemp.Length; if (sTemp.Length > KeyLength) { sTemp = sTemp.Substring(0, KeyLength); } else if (sTemp.Length < KeyLength) { sTemp = sTemp.PadRight(KeyLength, ' '); } return UTF8Encoding.UTF8.GetBytes(sTemp); }
public String generateKey() { /* AesManaged Legal min key size = 128 Legal max key size = 256 Legal min block size = 128 Legal max block size = 128*/ using (RijndaelManaged rijAlg = new RijndaelManaged()) { rijAlg.KeySize = 256; rijAlg.BlockSize = 256; rijAlg.GenerateKey(); rijAlg.GenerateIV(); return rijAlg.KeySize + " " + rijAlg.BlockSize + " " + Convert.ToBase64String(rijAlg.IV, Base64FormattingOptions.None) + " " + Convert.ToBase64String(rijAlg.Key, Base64FormattingOptions.None); } }
public static void GenerateKey() { CheckDirectory(Path.Combine(Application.dataPath, "Config")); using (System.Security.Cryptography.RijndaelManaged myRijndael = new System.Security.Cryptography.RijndaelManaged()) { myRijndael.GenerateKey(); byte[] key = myRijndael.Key; byte[] IV = myRijndael.IV; KeyVData keyScri = ScriptableObject.CreateInstance <KeyVData>(); keyScri.KEY = key; keyScri.IV = IV; AssetDatabase.CreateAsset(keyScri, "Assets/Resources/des.asset"); Debug.Log("key Generate " + key.Length); } }
public void GenerateEncryptedAssertion_01() { XmlDocument assertion = AssertionUtil.GetTestAssertion_01(); // Create an EncryptedData instance to hold the results of the encryption.o EncryptedData encryptedData = new EncryptedData(); encryptedData.Type = EncryptedXml.XmlEncElementUrl; encryptedData.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url); // Create a symmetric key. RijndaelManaged aes = new RijndaelManaged(); aes.KeySize = 256; aes.GenerateKey(); // Encrypt the assertion and add it to the encryptedData instance. EncryptedXml encryptedXml = new EncryptedXml(); byte[] encryptedElement = encryptedXml.EncryptData(assertion.DocumentElement, aes, false); encryptedData.CipherData.CipherValue = encryptedElement; // Add an encrypted version of the key used. encryptedData.KeyInfo = new KeyInfo(); EncryptedKey encryptedKey = new EncryptedKey(); // Use this certificate to encrypt the key. X509Certificate2 cert = new X509Certificate2(@"Saml20\Certificates\sts_dev_certificate.pfx", "test1234"); RSA publicKeyRSA = cert.PublicKey.Key as RSA; Assert.IsNotNull(publicKeyRSA, "Public key of certificate was not an RSA key. Modify test."); encryptedKey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); encryptedKey.CipherData = new CipherData(EncryptedXml.EncryptKey(aes.Key, publicKeyRSA, false)); encryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedKey)); // Create the resulting Xml-document to hook into. EncryptedAssertion encryptedAssertion = new EncryptedAssertion(); encryptedAssertion.encryptedData = new saml20.Schema.XEnc.EncryptedData(); encryptedAssertion.encryptedKey = new saml20.Schema.XEnc.EncryptedKey[1]; encryptedAssertion.encryptedKey[0] = new saml20.Schema.XEnc.EncryptedKey(); XmlDocument result; result = Serialization.Serialize(encryptedAssertion); XmlElement encryptedDataElement = GetElement(dk.nita.saml20.Schema.XEnc.EncryptedData.ELEMENT_NAME, Saml20Constants.XENC, result); EncryptedXml.ReplaceElement(encryptedDataElement, encryptedData, false); }
/// <summary> /// Generates a new EncryptionKey /// </summary> /// <returns> /// The key. /// </returns> public static EncryptKey GenerateKey() { //Create key EncryptKey key = new EncryptKey(); //create encryption algoritm to make the keys using(RijndaelManaged rj = new RijndaelManaged()) { //Generate key data rj.GenerateKey(); rj.GenerateIV(); key.data = rj.Key; key.dataIV = rj.IV; //dispose encryptor } //Return key return key; }
public void When_key_is_different_deserializing_key_will_fail() { var container = CreateContainer(); var serializer = container.Resolve<IMessageSerializer>(); var convertor = (WireEcryptedStringConvertor)container.Resolve<IValueConvertor<WireEcryptedString>>(); var managed = new RijndaelManaged(); managed.GenerateKey(); convertor.EncryptionService.Key = managed.Key; var memoryStream = new MemoryStream(); var writer = new StreamWriter(memoryStream); writer.Write(encryptedMessage); writer.Flush(); memoryStream.Position = 0; Assert.Throws<CryptographicException>( () => serializer.Deserialize(memoryStream) ); }
public static byte [] Encrypt(byte[] input, CipherMode cipherMode) { using (RijndaelManaged myRijndael = new RijndaelManaged { Mode = cipherMode }) { myRijndael.GenerateKey(); myRijndael.GenerateIV(); ICryptoTransform encryptor = myRijndael.CreateEncryptor(myRijndael.Key, myRijndael.IV); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { csEncrypt.Write(input, 0, input.Length); csEncrypt.FlushFinalBlock(); return msEncrypt.ToArray(); } } } }
static RijndaelManaged GetAlgorithm(string filePath) { string iv = DatabaseHelper.Instance.GetIVForFilePath (filePath); if (string.IsNullOrEmpty (iv)) { var rijndael = new RijndaelManaged (); rijndael.KeySize = 256; rijndael.BlockSize = 128; rijndael.GenerateIV (); iv = Convert.ToBase64String (rijndael.IV); DatabaseHelper.Instance.AddFilePathIV (new FilePathIV { FilePath = filePath, IV = iv}); } string key; Setting keyObject = DatabaseHelper.Instance.GetSetting (StorageConstants.EncryptionKey); if (keyObject == null) { var rijndael = new RijndaelManaged (); rijndael.KeySize = 256; rijndael.BlockSize = 128; rijndael.GenerateKey (); key = Convert.ToBase64String (rijndael.Key); DatabaseHelper.Instance.AddSetting (new Setting { Key = StorageConstants.EncryptionKey, Value = key }); } else { key = keyObject.Value; } var algorithm = new RijndaelManaged (); algorithm.KeySize = 256; algorithm.BlockSize = 128; algorithm.IV = Convert.FromBase64String(iv); algorithm.Key = Convert.FromBase64String(key); return algorithm; }
static void Main(string[] args) { string inFileName = @"C:\Users\Donal\Documents\win.ini"; string outFileName = @"C:\Users\Donal\Documents\win.ini.enc"; SymmetricAlgorithm myAlg = new RijndaelManaged(); myAlg.GenerateKey(); Console.WriteLine(Encoding.ASCII.GetString(myAlg.Key)); using (FileStream inFile = new FileStream(inFileName, FileMode.Open, FileAccess.Read)) using (FileStream outFile = new FileStream(outFileName, FileMode.Create, FileAccess.Write)) { byte[] fileData = new byte[inFile.Length]; inFile.Read(fileData, 0, (int)inFile.Length); ICryptoTransform encryptor = myAlg.CreateEncryptor(); using (CryptoStream encryptStream = new CryptoStream(outFile, encryptor, CryptoStreamMode.Write)) { encryptStream.Write(fileData, 0, fileData.Length); } } using (FileStream readFile = new FileStream(outFileName, FileMode.Open, FileAccess.Read)) { byte[] fileData = new byte[readFile.Length]; readFile.Read(fileData, 0, (int)readFile.Length); ICryptoTransform decryptor = myAlg.CreateDecryptor(); using (CryptoStream decryptStream = new CryptoStream(outFileName, decryptor, CryptoStreamMode.Read)) { decryptStream.Read( } } }
public CryptoManager() { m_RSA_Exch_Def = new RSAPKCS1KeyExchangeDeformatter(); m_RSA_Exch_For = new RSAPKCS1KeyExchangeFormatter(); m_RSA = new RSACryptoServiceProvider(); m_RSA.KeySize = m_KeySize; //m_RSA.PersistKeyInCsp = true; m_SHA = new SHA256Managed(); m_RIJ = new RijndaelManaged(); m_RIJ.Padding = PaddingMode.PKCS7; m_RIJ.Mode = CipherMode.CBC; m_RIJ.IV = new byte[16]; m_RIJ.BlockSize = 128; m_RIJ.KeySize = 256; m_RIJ.GenerateKey(); //m_PublicKey = m_RSA.ExportCspBlob(false); //m_PrivateKey = m_RSA.ExportCspBlob(true); m_PublicKey = Encoding.UTF8.GetBytes(m_RSA.ToXmlString(false)); m_PrivateKey = Encoding.UTF8.GetBytes(m_RSA.ToXmlString(true)); m_KeyPair = m_RSA.ExportParameters(true); }
public static byte[] GenerateEncryptionKey() { RijndaelManaged managed = new RijndaelManaged(); managed.GenerateKey(); return managed.Key; }
public override void GenerateKey() { m_rijndael.GenerateKey(); }
public Message SecureMessage () { secprop = Message.Properties.Security ?? new SecurityMessageProperty (); SecurityToken encToken = secprop.InitiatorToken != null ? secprop.InitiatorToken.SecurityToken : security.EncryptionToken; // FIXME: it might be still incorrect. SecurityToken signToken = Parameters == CounterParameters ? null : security.SigningToken; MessageProtectionOrder protectionOrder = security.MessageProtectionOrder; SecurityTokenSerializer serializer = security.TokenSerializer; SecurityBindingElement element = security.Element; SecurityAlgorithmSuite suite = element.DefaultAlgorithmSuite; // FIXME: remove this hack if (!ShouldOutputEncryptedKey) encToken = new BinarySecretSecurityToken (secprop.EncryptionKey); string messageId = "uuid-" + Guid.NewGuid (); int identForMessageId = 1; XmlDocument doc = new XmlDocument (); doc.PreserveWhitespace = true; UniqueId relatesTo = RelatesTo; if (relatesTo != null) msg.Headers.RelatesTo = relatesTo; else // FIXME: probably it is always added when it is stateful ? msg.Headers.MessageId = new UniqueId ("urn:" + messageId); // FIXME: get correct ReplyTo value if (Direction == MessageDirection.Input) msg.Headers.ReplyTo = new EndpointAddress (Constants.WsaAnonymousUri); if (MessageTo != null) msg.Headers.To = MessageTo.Uri; // wss:Security WSSecurityMessageHeader header = new WSSecurityMessageHeader (serializer); msg.Headers.Add (header); // 1. [Timestamp] if (element.IncludeTimestamp) { WsuTimestamp timestamp = new WsuTimestamp (); timestamp.Id = messageId + "-" + identForMessageId++; timestamp.Created = DateTime.Now; // FIXME: on service side, use element.LocalServiceSettings.TimestampValidityDuration timestamp.Expires = timestamp.Created.Add (element.LocalClientSettings.TimestampValidityDuration); header.AddContent (timestamp); } XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable); nsmgr.AddNamespace ("s", msg.Version.Envelope.Namespace); nsmgr.AddNamespace ("o", Constants.WssNamespace); nsmgr.AddNamespace ("u", Constants.WsuNamespace); nsmgr.AddNamespace ("o11", Constants.Wss11Namespace); /*WrappedKey*/SecurityToken primaryToken = null; DerivedKeySecurityToken dkeyToken = null; SecurityToken actualToken = null; SecurityKeyIdentifierClause actualClause = null; Signature sig = null; List<DerivedKeySecurityToken> derivedKeys = new List<DerivedKeySecurityToken> (); SymmetricAlgorithm masterKey = new RijndaelManaged (); masterKey.KeySize = suite.DefaultSymmetricKeyLength; masterKey.Mode = CipherMode.CBC; masterKey.Padding = PaddingMode.ISO10126; SymmetricAlgorithm actualKey = masterKey; // 2. [Encryption Token] // SecurityTokenInclusionMode // - Initiator or Recipient // - done or notyet. FIXME: not implemented yet // It also affects on key reference output bool includeEncToken = // /* FIXME: remove this hack */Parameters is SslSecurityTokenParameters ? false : ShouldIncludeToken ( Security.RecipientParameters.InclusionMode, false); bool includeSigToken = // /* FIXME: remove this hack */ Parameters is SslSecurityTokenParameters ? false : ShouldIncludeToken ( Security.InitiatorParameters.InclusionMode, false); SecurityKeyIdentifierClause encClause = ShouldOutputEncryptedKey ? CounterParameters.CallCreateKeyIdentifierClause (encToken, !ShouldOutputEncryptedKey ? SecurityTokenReferenceStyle.Internal : includeEncToken ? Parameters.ReferenceStyle : SecurityTokenReferenceStyle.External) : null; MessagePartSpecification sigSpec = SignaturePart; MessagePartSpecification encSpec = EncryptionPart; // encryption key (possibly also used for signing) // FIXME: get correct SymmetricAlgorithm according to the algorithm suite if (secprop.EncryptionKey != null) actualKey.Key = secprop.EncryptionKey; // FIXME: remove thid hack if (!ShouldOutputEncryptedKey) primaryToken = RequestContext.RequestMessage.Properties.Security.ProtectionToken.SecurityToken as WrappedKeySecurityToken; else primaryToken = // FIXME: remove this hack? encToken is SecurityContextSecurityToken ? encToken : new WrappedKeySecurityToken (messageId + "-" + identForMessageId++, actualKey.Key, // security.DefaultKeyWrapAlgorithm, Parameters.InternalHasAsymmetricKey ? suite.DefaultAsymmetricKeyWrapAlgorithm : suite.DefaultSymmetricKeyWrapAlgorithm, encToken, encClause != null ? new SecurityKeyIdentifier (encClause) : null); // If it reuses request's encryption key, do not output. if (ShouldOutputEncryptedKey) header.AddContent (primaryToken); actualToken = primaryToken; // FIXME: I doubt it is correct... WrappedKeySecurityToken requestEncKey = ShouldOutputEncryptedKey ? null : primaryToken as WrappedKeySecurityToken; actualClause = requestEncKey == null ? (SecurityKeyIdentifierClause) new LocalIdKeyIdentifierClause (actualToken.Id, typeof (WrappedKeySecurityToken)) : new InternalEncryptedKeyIdentifierClause (SHA1.Create ().ComputeHash (requestEncKey.GetWrappedKey ())); // generate derived key if needed if (CounterParameters.RequireDerivedKeys) { RijndaelManaged deriv = new RijndaelManaged (); deriv.KeySize = suite.DefaultEncryptionKeyDerivationLength; deriv.Mode = CipherMode.CBC; deriv.Padding = PaddingMode.ISO10126; deriv.GenerateKey (); dkeyToken = new DerivedKeySecurityToken ( GenerateId (doc), null, // algorithm actualClause, new InMemorySymmetricSecurityKey (actualKey.Key), null, // name null, // generation null, // offset deriv.Key.Length, null, // label deriv.Key); derivedKeys.Add (dkeyToken); actualToken = dkeyToken; actualKey.Key = ((SymmetricSecurityKey) dkeyToken.SecurityKeys [0]).GetSymmetricKey (); actualClause = new LocalIdKeyIdentifierClause (dkeyToken.Id); header.AddContent (dkeyToken); } ReferenceList refList = new ReferenceList (); // When encrypted with DerivedKeyToken, put references // immediately after the derived token (not inside the // primary token). // Similarly, when we do not output EncryptedKey, // output ReferenceList in the same way. if (CounterParameters.RequireDerivedKeys || !ShouldOutputEncryptedKey) header.AddContent (refList); else ((WrappedKeySecurityToken) primaryToken).ReferenceList = refList; // [Signature Confirmation] if (security.RequireSignatureConfirmation && secprop.ConfirmedSignatures.Count > 0) foreach (string value in secprop.ConfirmedSignatures) header.AddContent (new Wss11SignatureConfirmation (GenerateId (doc), value)); SupportingTokenInfoCollection tokenInfos = Direction == MessageDirection.Input ? security.CollectSupportingTokens (GetAction ()) : new SupportingTokenInfoCollection (); // empty foreach (SupportingTokenInfo tinfo in tokenInfos) header.AddContent (tinfo.Token); // populate DOM to sign. XPathNavigator nav = doc.CreateNavigator (); using (XmlWriter w = nav.AppendChild ()) { msg.WriteMessage (w); } XmlElement body = doc.SelectSingleNode ("/s:Envelope/s:Body/*", nsmgr) as XmlElement; string bodyId = null; XmlElement secElem = null; Collection<WSSignedXml> endorsedSignatures = new Collection<WSSignedXml> (); bool signatureProtection = (protectionOrder == MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature); // Below are o:Security contents that are not signed... if (includeSigToken && signToken != null) header.AddContent (signToken); switch (protectionOrder) { case MessageProtectionOrder.EncryptBeforeSign: // FIXME: implement throw new NotImplementedException (); case MessageProtectionOrder.SignBeforeEncrypt: case MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature: // sign // see clause 8 of WS-SecurityPolicy C.2.2 WSSignedXml sxml = new WSSignedXml (doc); SecurityTokenReferenceKeyInfo sigKeyInfo; sig = sxml.Signature; sig.SignedInfo.CanonicalizationMethod = suite.DefaultCanonicalizationAlgorithm; foreach (XmlElement elem in doc.SelectNodes ("/s:Envelope/s:Header/o:Security/u:Timestamp", nsmgr)) CreateReference (sig, elem, elem.GetAttribute ("Id", Constants.WsuNamespace)); foreach (XmlElement elem in doc.SelectNodes ("/s:Envelope/s:Header/o:Security/o11:SignatureConfirmation", nsmgr)) CreateReference (sig, elem, elem.GetAttribute ("Id", Constants.WsuNamespace)); foreach (SupportingTokenInfo tinfo in tokenInfos) if (tinfo.Mode != SecurityTokenAttachmentMode.Endorsing) { XmlElement el = sxml.GetIdElement (doc, tinfo.Token.Id); CreateReference (sig, el, el.GetAttribute ("Id", Constants.WsuNamespace)); } XmlNodeList nodes = doc.SelectNodes ("/s:Envelope/s:Header/*", nsmgr); for (int i = 0; i < msg.Headers.Count; i++) { MessageHeaderInfo h = msg.Headers [i]; if (h.Name == "Security" && h.Namespace == Constants.WssNamespace) secElem = nodes [i] as XmlElement; else if (sigSpec.HeaderTypes.Count == 0 || sigSpec.HeaderTypes.Contains (new XmlQualifiedName (h.Name, h.Namespace))) { string id = GenerateId (doc); h.Id = id; CreateReference (sig, nodes [i] as XmlElement, id); } } if (sigSpec.IsBodyIncluded) { bodyId = GenerateId (doc); CreateReference (sig, body.ParentNode as XmlElement, bodyId); } if (security.DefaultSignatureAlgorithm == SignedXml.XmlDsigHMACSHA1Url) { // FIXME: use appropriate hash algorithm sxml.ComputeSignature (new HMACSHA1 (actualKey.Key)); sigKeyInfo = new SecurityTokenReferenceKeyInfo (actualClause, serializer, doc); } else { SecurityKeyIdentifierClause signClause = CounterParameters.CallCreateKeyIdentifierClause (signToken, includeSigToken ? CounterParameters.ReferenceStyle : SecurityTokenReferenceStyle.External); AsymmetricSecurityKey signKey = (AsymmetricSecurityKey) signToken.ResolveKeyIdentifierClause (signClause); sxml.SigningKey = signKey.GetAsymmetricAlgorithm (security.DefaultSignatureAlgorithm, true); sxml.ComputeSignature (); sigKeyInfo = new SecurityTokenReferenceKeyInfo (signClause, serializer, doc); } sxml.KeyInfo = new KeyInfo (); sxml.KeyInfo.AddClause (sigKeyInfo); if (!signatureProtection) header.AddContent (sig); // endorse the signature with (signed)endorsing // supporting tokens. foreach (SupportingTokenInfo tinfo in tokenInfos) { switch (tinfo.Mode) { case SecurityTokenAttachmentMode.Endorsing: case SecurityTokenAttachmentMode.SignedEndorsing: if (sxml.Signature.Id == null) { sig.Id = GenerateId (doc); secElem.AppendChild (sxml.GetXml ()); } WSSignedXml ssxml = new WSSignedXml (doc); ssxml.Signature.SignedInfo.CanonicalizationMethod = suite.DefaultCanonicalizationAlgorithm; CreateReference (ssxml.Signature, doc, sig.Id); SecurityToken sst = tinfo.Token; SecurityKey ssk = sst.SecurityKeys [0]; // FIXME: could be different? SecurityKeyIdentifierClause tclause = new LocalIdKeyIdentifierClause (sst.Id); // FIXME: could be different? if (ssk is SymmetricSecurityKey) { SymmetricSecurityKey signKey = (SymmetricSecurityKey) ssk; ssxml.ComputeSignature (signKey.GetKeyedHashAlgorithm (suite.DefaultSymmetricSignatureAlgorithm)); } else { AsymmetricSecurityKey signKey = (AsymmetricSecurityKey) ssk; ssxml.SigningKey = signKey.GetAsymmetricAlgorithm (suite.DefaultAsymmetricSignatureAlgorithm, true); ssxml.ComputeSignature (); } ssxml.KeyInfo.AddClause (new SecurityTokenReferenceKeyInfo (tclause, serializer, doc)); if (!signatureProtection) header.AddContent (ssxml.Signature); endorsedSignatures.Add (ssxml); break; } } // encrypt WSEncryptedXml exml = new WSEncryptedXml (doc); EncryptedData edata = Encrypt (body, actualKey, actualToken.Id, refList, actualClause, exml, doc); EncryptedXml.ReplaceElement (body, edata, false); // encrypt signature if (signatureProtection) { XmlElement sigxml = sig.GetXml (); edata = Encrypt (sigxml, actualKey, actualToken.Id, refList, actualClause, exml, doc); header.AddContent (edata); foreach (WSSignedXml ssxml in endorsedSignatures) { sigxml = ssxml.GetXml (); edata = Encrypt (sigxml, actualKey, actualToken.Id, refList, actualClause, exml, doc); header.AddContent (edata); } if (security.RequireSignatureConfirmation) { Collection<Wss11SignatureConfirmation> confs = header.FindAll<Wss11SignatureConfirmation> (); int count = 0; foreach (XmlElement elem in doc.SelectNodes ("/s:Envelope/s:Header/o:Security/o11:SignatureConfirmation", nsmgr)) { edata = Encrypt (elem, actualKey, confs [count].Id, refList, actualClause, exml, doc); EncryptedXml.ReplaceElement (elem, edata, false); header.Contents.Insert (header.Contents.IndexOf (confs [count]), edata); header.Contents.Remove (confs [count++]); } } } // encrypt Encrypted supporting tokens foreach (SupportingTokenInfo tinfo in tokenInfos) { if (tinfo.Mode == SecurityTokenAttachmentMode.SignedEncrypted) { XmlElement el = exml.GetIdElement (doc, tinfo.Token.Id); tinfo.Encrypted = Encrypt (el, actualKey, actualToken.Id, refList, actualClause, exml, doc); EncryptedXml.ReplaceElement (el, tinfo.Encrypted, false); header.Contents.Insert (header.Contents.IndexOf (tinfo.Token), tinfo.Encrypted); header.Contents.Remove (tinfo.Token); } } break; } Message ret = new WSSecurityMessage (Message.CreateMessage (msg.Version, msg.Headers.Action, new XmlNodeReader (doc.SelectSingleNode ("/s:Envelope/s:Body/*", nsmgr) as XmlElement)), bodyId); ret.Properties.Security = (SecurityMessageProperty) secprop.CreateCopy (); ret.Properties.Security.EncryptionKey = masterKey.Key; // FIXME: can we support TransportToken here? if (element is AsymmetricSecurityBindingElement) { ret.Properties.Security.InitiatorToken = new SecurityTokenSpecification (encToken, null); // FIXME: second argument ret.Properties.Security.InitiatorToken = new SecurityTokenSpecification (signToken, null); // FIXME: second argument } else ret.Properties.Security.ProtectionToken = new SecurityTokenSpecification (primaryToken, null); ret.Headers.Clear (); ret.Headers.CopyHeadersFrom (msg); // Header contents are: // - Timestamp // - SignatureConfirmation if required // - EncryptionToken if included // - derived key token for EncryptionToken // - ReferenceList for encrypted items // - signed supporting tokens // - signed endorsing supporting tokens // (i.e. Signed/SignedEncrypted/SignedEndorsing) // - Signature Token if different from enc token. // - derived key token for sig token if different // - Signature for: // - Timestamp // - supporting tokens (regardless of // its inclusion) // - message parts in SignedParts // - SignatureToken if TokenProtection // (regardless of its inclusion) // - Signatures for the main signature (above), // for every endorsing token and signed // endorsing token. // //MessageBuffer zzz = ret.CreateBufferedCopy (100000); //ret = zzz.CreateMessage (); //Console.WriteLine (zzz.CreateMessage ()); return ret; }