public void KeyInfoName () { KeyInfoName name = new KeyInfoName (); name.Value = "Mono::"; info.AddClause (name); AssertEquals ("name", "<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><KeyName>Mono::</KeyName></KeyInfo>", (info.GetXml ().OuterXml)); AssertEquals ("name count", 1, info.Count); }
public void InvalidValue1 () { string bad = "<Test></Test>"; XmlDocument doc = new XmlDocument (); doc.LoadXml (bad); KeyInfoName name = new KeyInfoName (); name.LoadXml (null); }
public override XmlNode Encrypt(XmlNode node) { XmlDocument xmlDocument; EncryptedXml exml; byte[] rgbOutput; EncryptedData ed; KeyInfoName kin; SymmetricAlgorithm symAlg; EncryptedKey ek; KeyInfoEncryptedKey kek; XmlElement inputElement; RSACryptoServiceProvider rsa = GetCryptoServiceProvider(false, false); // Encrypt the node with the new key xmlDocument = new XmlDocument(); xmlDocument.PreserveWhitespace = true; xmlDocument.LoadXml("<foo>"+ node.OuterXml+ "</foo>"); exml = new EncryptedXml(xmlDocument); inputElement = xmlDocument.DocumentElement; // Create a new 3DES key symAlg = new TripleDESCryptoServiceProvider(); byte[] rgbKey1 = GetRandomKey(); symAlg.Key = rgbKey1; symAlg.Mode = CipherMode.ECB; symAlg.Padding = PaddingMode.PKCS7; rgbOutput = exml.EncryptData(inputElement, symAlg, true); ed = new EncryptedData(); ed.Type = EncryptedXml.XmlEncElementUrl; ed.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl); ed.KeyInfo = new KeyInfo(); ek = new EncryptedKey(); ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); ek.KeyInfo = new KeyInfo(); ek.CipherData = new CipherData(); ek.CipherData.CipherValue = EncryptedXml.EncryptKey(symAlg.Key, rsa, UseOAEP); kin = new KeyInfoName(); kin.Value = _KeyName; ek.KeyInfo.AddClause(kin); kek = new KeyInfoEncryptedKey(ek); ed.KeyInfo.AddClause(kek); ed.CipherData = new CipherData(); ed.CipherData.CipherValue = rgbOutput; EncryptedXml.ReplaceElement(inputElement, ed, true); // Get node from the document foreach (XmlNode node2 in xmlDocument.ChildNodes) if (node2.NodeType == XmlNodeType.Element) foreach (XmlNode node3 in node2.ChildNodes) // node2 is the "foo" node if (node3.NodeType == XmlNodeType.Element) return node3; // node3 is the "EncryptedData" node return null; }
public void ImportKeyValue () { string value = "<KeyName xmlns=\"http://www.w3.org/2000/09/xmldsig#\">Mono::</KeyName>"; XmlDocument doc = new XmlDocument (); doc.LoadXml (value); KeyInfoName name = new KeyInfoName (); name.LoadXml (doc.DocumentElement); AssertEquals ("import.Name", "Mono::", name.Value); AssertEquals ("import.GetXml", value, name.GetXml ().OuterXml); }
public void InvalidValue2 () { string bad = "<Test></Test>"; XmlDocument doc = new XmlDocument (); doc.LoadXml (bad); KeyInfoName name = new KeyInfoName (); name.LoadXml (doc.DocumentElement); AssertEquals ("invalid.Name", "", name.Value); AssertEquals ("invalid.GetXml", "<KeyName xmlns=\"http://www.w3.org/2000/09/xmldsig#\"></KeyName>", (name.GetXml ().OuterXml)); }
public string SignXml(XDocument xml) { using (MemoryStream streamIn = new MemoryStream()) { xml.Save(streamIn); streamIn.Position = 0; // var rsaKey = (RSACryptoServiceProvider)_privateCertificate.PrivateKey; // Create rsa crypto provider from private key contained in certificate, weirdest cast ever!; // string sCertFileLocation = @"C:\plugins\idealtest\bin\Debug\certficate.pfx"; // X509Certificate2 certificate = new X509Certificate2(sCertFileLocation, "D3M@ast3rsR0cks"); RSA rsaKey = (RSACryptoServiceProvider)_privateCertificate.PrivateKey; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.PreserveWhitespace = true; xmlDoc.Load(streamIn); SignedXml signedXml = new SignedXml(xmlDoc); signedXml.SigningKey = rsaKey; Reference reference = new Reference(); reference.Uri = ""; XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); signedXml.AddReference(reference); KeyInfo keyInfo = new KeyInfo(); KeyInfoName kin = new KeyInfoName(); kin.Value = _privateCertificate.Thumbprint; keyInfo.AddClause(kin); signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature(); XmlElement xmlDigitalSignature = signedXml.GetXml(); xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true)); using (MemoryStream sout = new MemoryStream()) { xmlDoc.Save(sout); sout.Position = 0; using (StreamReader reader = new StreamReader(sout)) { string xmlOut = reader.ReadToEnd(); return xmlOut; } } } }
public void NewKeyValue () { string newKeyValue = "Mono::"; KeyInfoName name1 = new KeyInfoName (); name1.Value = newKeyValue; XmlElement xel = name1.GetXml (); KeyInfoName name2 = new KeyInfoName (); name2.LoadXml (xel); AssertEquals ("newKeyValue==value", newKeyValue, name1.Value); AssertEquals ("name1==name2", (name1.GetXml ().OuterXml), (name2.GetXml ().OuterXml)); }
public override XmlNode Encrypt(XmlNode node) { RSACryptoServiceProvider cryptoServiceProvider = this.GetCryptoServiceProvider(false, false); XmlDocument document = new XmlDocument { PreserveWhitespace = true }; document.LoadXml("<foo>" + node.OuterXml + "</foo>"); EncryptedXml xml = new EncryptedXml(document); XmlElement documentElement = document.DocumentElement; SymmetricAlgorithm symmetricAlgorithm = new TripleDESCryptoServiceProvider(); byte[] randomKey = this.GetRandomKey(); symmetricAlgorithm.Key = randomKey; symmetricAlgorithm.Mode = CipherMode.ECB; symmetricAlgorithm.Padding = PaddingMode.PKCS7; byte[] buffer = xml.EncryptData(documentElement, symmetricAlgorithm, true); EncryptedData encryptedData = new EncryptedData { Type = "http://www.w3.org/2001/04/xmlenc#Element", EncryptionMethod = new EncryptionMethod("http://www.w3.org/2001/04/xmlenc#tripledes-cbc"), KeyInfo = new KeyInfo() }; EncryptedKey encryptedKey = new EncryptedKey { EncryptionMethod = new EncryptionMethod("http://www.w3.org/2001/04/xmlenc#rsa-1_5"), KeyInfo = new KeyInfo(), CipherData = new CipherData() }; encryptedKey.CipherData.CipherValue = EncryptedXml.EncryptKey(symmetricAlgorithm.Key, cryptoServiceProvider, this.UseOAEP); KeyInfoName clause = new KeyInfoName { Value = this._KeyName }; encryptedKey.KeyInfo.AddClause(clause); KeyInfoEncryptedKey key2 = new KeyInfoEncryptedKey(encryptedKey); encryptedData.KeyInfo.AddClause(key2); encryptedData.CipherData = new CipherData(); encryptedData.CipherData.CipherValue = buffer; EncryptedXml.ReplaceElement(documentElement, encryptedData, true); foreach (XmlNode node2 in document.ChildNodes) { if (node2.NodeType == XmlNodeType.Element) { foreach (XmlNode node3 in node2.ChildNodes) { if (node3.NodeType == XmlNodeType.Element) { return node3; } } } } return null; }
public override XmlNode Encrypt(XmlNode node) { // Load config section to encrypt into xmlDocument instance XmlDocument doc = new XmlDocument { PreserveWhitespace = true }; doc.LoadXml(node.OuterXml); // Create Rijndael key. RijndaelManaged sessionKey = new RijndaelManaged(); sessionKey.KeySize = 256; EncryptedXml eXml = new EncryptedXml(); XmlElement elementToEncrypt = (XmlElement)node; byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, false); EncryptedData edElement = new EncryptedData(); edElement.Type = EncryptedXml.XmlEncElementUrl; edElement.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url); // Encrypt the session key and add it to an EncryptedKey element. EncryptedKey ek = new EncryptedKey(); byte[] encryptedKey = EncryptedXml.EncryptKey(sessionKey.Key, this.rsaKey, false); ek.CipherData = new CipherData(encryptedKey); ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); // Set the KeyInfo element to specify the name of the RSA key. edElement.KeyInfo = new KeyInfo(); KeyInfoName kin = new KeyInfoName(); kin.Value = this.keyName; // Add the KeyInfoName element to the // EncryptedKey object. ek.KeyInfo.AddClause(kin); edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek)); // Add the encrypted element data to the // EncryptedData object. edElement.CipherData.CipherValue = encryptedElement; // EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false); return edElement.GetXml(); }
public void Complex () { KeyInfoName name = new KeyInfoName (); name.Value = "Mono::"; info.AddClause (name); DSA keyDSA = DSA.Create (); keyDSA.FromXmlString (xmlDSA); DSAKeyValue dsa = new DSAKeyValue (keyDSA); info.AddClause (dsa); RSA keyRSA = RSA.Create (); keyRSA.FromXmlString (xmlRSA); RSAKeyValue rsa = new RSAKeyValue (keyRSA); info.AddClause (rsa); KeyInfoRetrievalMethod retrieval = new KeyInfoRetrievalMethod (); retrieval.Uri = "http://www.go-mono.org/"; info.AddClause (retrieval); X509Certificate x509 = new X509Certificate (cert); KeyInfoX509Data x509data = new KeyInfoX509Data (x509); info.AddClause (x509data); string s = "<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><KeyName>Mono::</KeyName><KeyValue xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><DSAKeyValue><P>rjxsMU368YOCTQejWkiuO9e/vUVwkLtq1jKiU3TtJ53hBJqjFRuTa228vZe+BH2su9RPn/vYFWfQDv6zgBYe3eNdu4Afw+Ny0FatX6dl3E77Ra6Tsd3MmLXBiGSQ1mMNd5G2XQGpbt9zsGlUaexXekeMLxIufgfZLwYp67M+2WM=</P><Q>tf0K9rMyvUrU4cIkwbCrDRhQAJk=</Q><G>S8Z+1pGCed00w6DtVcqZLKjfqlCJ7JsugEFIgSy/Vxtu9YGCMclV4ijGEbPo/jU8YOSMuD7E9M7UaopMRcmKQjoKZzoJjkgVFP48Ohxl1f08lERnButsxanx3+OstFwUGQ8XNaGg3KrIoZt1FUnfxN3RHHTvVhjzNSHxMGULGaU=</G><Y>LnrxxRGLYeV2XLtK3SYz8RQHlHFZYrtznDZyMotuRfO5uC5YODhSFyLXvb1qB3WeGtF4h3Eo4KzHgMgfN2ZMlffxFRhJgTtH3ctbL8lfQoDkjeiPPnYGhspdJxr0tyZmiy0gkjJG3vwHYrLnvZWx9Wm/unqiOlGBPNuxJ+hOeP8=</Y><J>9RhE5TycDtdEIXxS3HfxFyXYgpy81zY5lVjwD6E9JP37MWEi80BlX6ab1YPm6xYSEoqReMPP9RgGiW6DuACpgI7+8vgCr4i/7VhzModJAA56PwvTu6UMt9xxKU/fT672v8ucREkMWoc7lEey</J><Seed>HxW3N4RHWVgqDQKuGg7iJTUTiCs=</Seed><PgenCounter>Asw=</PgenCounter></DSAKeyValue></KeyValue>"; s += "<KeyValue xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><RSAKeyValue><Modulus>9DC4XNdQJwMRnz5pP2a6U51MHCODRilaIoVXqUPhCUb0lJdGroeqVYT84ZyIVrcarzD7Tqs3aEOIa3rKox0N1bxQpZPqayVQeLAkjLLtzJW/ScRJx3uEDJdgT1JnM1FH0GZTinmEdCUXdLc7+Y/c/qqIkTfbwHbRZjW0bBJyExM=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue></KeyValue>"; #if NET_1_0 s += "<RetrievalElement URI=\"http://www.go-mono.org/\" />"; #else s += "<RetrievalMethod URI=\"http://www.go-mono.org/\" />"; #endif s += "<X509Data xmlns=\"http://www.w3.org/2000/09/xmldsig#\">"; s += "<X509Certificate>MIICHTCCAYYCARQwDQYJKoZIhvcNAQEEBQAwWDELMAkGA1UEBhMCQ0ExHzAdBgNVBAMTFktleXdpdG5lc3MgQ2FuYWRhIEluYy4xKDAmBgorBgEEASoCCwIBExhrZXl3aXRuZXNzQGtleXdpdG5lc3MuY2EwHhcNOTYwNTA3MDAwMDAwWhcNOTkwNTA3MDAwMDAwWjBYMQswCQYDVQQGEwJDQTEfMB0GA1UEAxMWS2V5d2l0bmVzcyBDYW5hZGEgSW5jLjEoMCYGCisGAQQBKgILAgETGGtleXdpdG5lc3NAa2V5d2l0bmVzcy5jYTCBnTANBgkqhkiG9w0BAQEFAAOBiwAwgYcCgYEAzSP6KuHtmPTp0JM+13qAAkzMwQKvXLYff/pXQm8w0SDFtSEHQCyphsLzZISuPYUu7YW9VLAYKO9q+BvnCxYfkyVPx/iOw7nKmIQOVdAv73h3xXIoX2C/GSvRcqK32D/glzRaAb0EnMh4Rc2TjRXydhARq7hbLp5S3YE+nGTIKZMCAQMwDQYJKoZIhvcNAQEEBQADgYEAMho1ur9DJ9a01Lh25eObTWzAhsl3NbprFi0TRkqwMlOhW1rpmeIMhogXTg3+gqxOR+/7/zms7jXI+lI3CkmtWa3iiqkcxl8f+G9zfs2gMegMvvVN2bKrihK2MHhoEXwN8UlNo/2y6f8d8JH6VIX/M5Dowb+km6RiRr1hElmYQYk=</X509Certificate></X509Data></KeyInfo>"; AssertCrypto.AssertXmlEquals ("Complex", s, (info.GetXml ().OuterXml)); AssertEquals ("RetrievalMethod count", 5, info.Count); }
public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey) { if (encryptedKey == null) { throw new ArgumentNullException("encryptedKey"); } if (encryptedKey.KeyInfo != null) { IEnumerator enumerator = encryptedKey.KeyInfo.GetEnumerator(); EncryptedKey key2 = null; bool useOAEP = false; while (enumerator.MoveNext()) { KeyInfoName current = enumerator.Current as KeyInfoName; if (current != null) { string str = current.Value; object obj2 = this.m_keyNameMapping[str]; if (obj2 != null) { if (obj2 is SymmetricAlgorithm) { return(DecryptKey(encryptedKey.CipherData.CipherValue, (SymmetricAlgorithm)obj2)); } useOAEP = (encryptedKey.EncryptionMethod != null) && (encryptedKey.EncryptionMethod.KeyAlgorithm == "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"); return(DecryptKey(encryptedKey.CipherData.CipherValue, (RSA)obj2, useOAEP)); } break; } KeyInfoX509Data data = enumerator.Current as KeyInfoX509Data; if (data != null) { X509Certificate2Enumerator enumerator2 = System.Security.Cryptography.Xml.Utils.BuildBagOfCerts(data, CertUsageType.Decryption).GetEnumerator(); while (enumerator2.MoveNext()) { RSA privateKey = enumerator2.Current.PrivateKey as RSA; if (privateKey != null) { useOAEP = (encryptedKey.EncryptionMethod != null) && (encryptedKey.EncryptionMethod.KeyAlgorithm == "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"); return(DecryptKey(encryptedKey.CipherData.CipherValue, privateKey, useOAEP)); } } break; } KeyInfoRetrievalMethod method = enumerator.Current as KeyInfoRetrievalMethod; if (method != null) { string idValue = System.Security.Cryptography.Xml.Utils.ExtractIdFromLocalUri(method.Uri); key2 = new EncryptedKey(); key2.LoadXml(this.GetIdElement(this.m_document, idValue)); return(this.DecryptEncryptedKey(key2)); } KeyInfoEncryptedKey key = enumerator.Current as KeyInfoEncryptedKey; if (key != null) { key2 = key.EncryptedKey; byte[] buffer = this.DecryptEncryptedKey(key2); if (buffer != null) { SymmetricAlgorithm symmetricAlgorithm = (SymmetricAlgorithm)CryptoConfig.CreateFromName(encryptedKey.EncryptionMethod.KeyAlgorithm); symmetricAlgorithm.Key = buffer; return(DecryptKey(encryptedKey.CipherData.CipherValue, symmetricAlgorithm)); } } } } return(null); }
public static void Encrypt(XmlDocument Doc, string ElementToEncrypt, string EncryptionElementID, RSA Alg, string KeyName) { // Check the arguments. if (Doc == null) throw new ArgumentNullException("Doc"); if (ElementToEncrypt == null) throw new ArgumentNullException("ElementToEncrypt"); if (EncryptionElementID == null) throw new ArgumentNullException("EncryptionElementID"); if (Alg == null) throw new ArgumentNullException("Alg"); if (KeyName == null) throw new ArgumentNullException("KeyName"); //////////////////////////////////////////////// // Find the specified element in the XmlDocument // object and create a new XmlElemnt object. //////////////////////////////////////////////// XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementToEncrypt)[0] as XmlElement; // Throw an XmlException if the element was not found. if (elementToEncrypt == null) { throw new XmlException("The specified element was not found"); } RijndaelManaged sessionKey = null; try { ////////////////////////////////////////////////// // Create a new instance of the EncryptedXml class // and use it to encrypt the XmlElement with the // a new random symmetric key. ////////////////////////////////////////////////// // Create a 256 bit Rijndael key. sessionKey = new RijndaelManaged(); sessionKey.KeySize = 256; EncryptedXml eXml = new EncryptedXml(); byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, false); //////////////////////////////////////////////// // Construct an EncryptedData object and populate // it with the desired encryption information. //////////////////////////////////////////////// EncryptedData edElement = new EncryptedData(); edElement.Type = EncryptedXml.XmlEncElementUrl; edElement.Id = EncryptionElementID; // Create an EncryptionMethod element so that the // receiver knows which algorithm to use for decryption. edElement.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url); // Encrypt the session key and add it to an EncryptedKey element. EncryptedKey ek = new EncryptedKey(); byte[] encryptedKey = EncryptedXml.EncryptKey(sessionKey.Key, Alg, false); ek.CipherData = new CipherData(encryptedKey); ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); // Create a new DataReference element // for the KeyInfo element. This optional // element specifies which EncryptedData // uses this key. An XML document can have // multiple EncryptedData elements that use // different keys. DataReference dRef = new DataReference(); // Specify the EncryptedData URI. dRef.Uri = "#" + EncryptionElementID; // Add the DataReference to the EncryptedKey. ek.AddReference(dRef); // Add the encrypted key to the // EncryptedData object. edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek)); // Set the KeyInfo element to specify the // name of the RSA key. // Create a new KeyInfo element. edElement.KeyInfo = new KeyInfo(); // Create a new KeyInfoName element. KeyInfoName kin = new KeyInfoName(); // Specify a name for the key. kin.Value = KeyName; // Add the KeyInfoName element to the // EncryptedKey object. ek.KeyInfo.AddClause(kin); // Add the encrypted element data to the // EncryptedData object. edElement.CipherData.CipherValue = encryptedElement; //////////////////////////////////////////////////// // Replace the element from the original XmlDocument // object with the EncryptedData element. //////////////////////////////////////////////////// EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false); } catch (Exception e) { // re-throw the exception. throw e; } finally { if (sessionKey != null) { sessionKey.Clear(); } } }
public virtual SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, string symmetricAlgorithmUri) { if (encryptedData == null) { throw new ArgumentNullException("encryptedData"); } if (encryptedData.KeyInfo == null) { return(null); } IEnumerator enumerator = encryptedData.KeyInfo.GetEnumerator(); EncryptedKey encryptedKey = null; while (enumerator.MoveNext()) { KeyInfoName current = enumerator.Current as KeyInfoName; if (current != null) { string str = current.Value; if (((SymmetricAlgorithm)this.m_keyNameMapping[str]) != null) { return((SymmetricAlgorithm)this.m_keyNameMapping[str]); } XmlNamespaceManager nsmgr = new XmlNamespaceManager(this.m_document.NameTable); nsmgr.AddNamespace("enc", "http://www.w3.org/2001/04/xmlenc#"); XmlNodeList list = this.m_document.SelectNodes("//enc:EncryptedKey", nsmgr); if (list != null) { foreach (XmlNode node in list) { XmlElement element = node as XmlElement; EncryptedKey key3 = new EncryptedKey(); key3.LoadXml(element); if ((key3.CarriedKeyName == str) && (key3.Recipient == this.Recipient)) { encryptedKey = key3; break; } } } break; } KeyInfoRetrievalMethod method = enumerator.Current as KeyInfoRetrievalMethod; if (method != null) { string idValue = System.Security.Cryptography.Xml.Utils.ExtractIdFromLocalUri(method.Uri); encryptedKey = new EncryptedKey(); encryptedKey.LoadXml(this.GetIdElement(this.m_document, idValue)); break; } KeyInfoEncryptedKey key = enumerator.Current as KeyInfoEncryptedKey; if (key != null) { encryptedKey = key.EncryptedKey; break; } } if (encryptedKey == null) { return(null); } if (symmetricAlgorithmUri == null) { if (encryptedData.EncryptionMethod == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingAlgorithm")); } symmetricAlgorithmUri = encryptedData.EncryptionMethod.KeyAlgorithm; } byte[] buffer = this.DecryptEncryptedKey(encryptedKey); if (buffer == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingDecryptionKey")); } SymmetricAlgorithm algorithm = (SymmetricAlgorithm)CryptoConfig.CreateFromName(symmetricAlgorithmUri); algorithm.Key = buffer; return(algorithm); }
//加密 private void btn2JiaMi_Click(object sender, EventArgs e) { try { //经过咨询微软全球技术服务中心和查阅微软Support站点和Technet站点,得出以下结论:使用EFS加密的文件(夹)一旦密钥丢失以后是不可能恢复的 //*****生产对称密钥.该密钥用来对XML加密 //CspParameters cspParams = new CspParameters(); //cspParams.KeyContainerName = "XML_ENC_RSA_KEY"; //生成一个对称密钥,对密钥进行加密 RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(); rsaKey.FromXmlString(publicK); //加载XML对象,定制加密位置 XmlDocument xmlDoc = new XmlDocument(); xmlDoc.PreserveWhitespace = true; xmlDoc.Load(this.label2.Text); XmlElement elementToEncrypt = xmlDoc.GetElementsByTagName("creditcard")[0] as XmlElement; //*****处理EncrypteData对象 EncryptedData edElement = new EncryptedData(); edElement.Type = EncryptedXml.XmlEncElementUrl; edElement.Id = "encryptedElement1";//EncryptionElementID; //生成会话密钥的加密算法的 URL 标识符 edElement.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url); //用RijindaelManaged加密元素(即用会话密钥加密元素) RijndaelManaged sessionKey = new RijndaelManaged(); sessionKey.KeySize = 256; byte[] encryptedElement = new EncryptedXml().EncryptData(elementToEncrypt, sessionKey, false); //用EncrypteKey对象(对会话密钥进行加密) EncryptedKey ek = new EncryptedKey(); byte[] encrytedKey = EncryptedXml.EncryptKey(sessionKey.Key, rsaKey, false); ek.CipherData = new CipherData(encrytedKey); ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); //将加密的密钥添加到EncrypteData中 edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek)); //`````用KeyInfo指定RSA密钥名称,这将帮助解密方识别正确的非对称密钥 KeyInfoName kin = new KeyInfoName(); kin.Value = keyName; ek.KeyInfo.AddClause(kin); //替换xml Dom 元素 edElement.CipherData.CipherValue = encryptedElement; EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false); //保存 xmlDoc.Save(this.label2.Text); succes(); } catch (Exception ess) { fail(); } }
/// <summary> /// Encrypt. /// </summary> /// <param name="Doc">XML document.</param> /// <param name="ElementToEncrypt">Element to encrypt.</param> /// <param name="Alg">Algoritm.</param> /// <param name="KeyName">Key name.</param> public static void Encrypt(XmlDocument Doc, string ElementToEncrypt, RSA Alg, string KeyName) { // Check the arguments. if (Doc == null) throw new ArgumentNullException("Doc"); if (ElementToEncrypt == null) throw new ArgumentNullException("ElementToEncrypt"); if (Alg == null) throw new ArgumentNullException("Alg"); //////////////////////////////////////////////// // Find the specified element in the XmlDocument // object and create a new XmlElemnt object. //////////////////////////////////////////////// XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementToEncrypt)[0] as XmlElement; // Throw an XmlException if the element was not found. if (elementToEncrypt == null) { throw new XmlException("The specified element was not found"); } ////////////////////////////////////////////////// // Create a new instance of the EncryptedXml class // and use it to encrypt the XmlElement with the // a new random symmetric key. ////////////////////////////////////////////////// // Create a 256 bit Rijndael key. RijndaelManaged sessionKey = new RijndaelManaged(); sessionKey.KeySize = 256; EncryptedXml eXml = new EncryptedXml(); byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, false); //////////////////////////////////////////////// // Construct an EncryptedData object and populate // it with the desired encryption information. //////////////////////////////////////////////// EncryptedData edElement = new EncryptedData(); edElement.Type = EncryptedXml.XmlEncElementUrl; // Create an EncryptionMethod element so that the // receiver knows which algorithm to use for decryption. edElement.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url); // Encrypt the session key and add it to an EncryptedKey element. EncryptedKey ek = new EncryptedKey(); byte[] encryptedKey = EncryptedXml.EncryptKey(sessionKey.Key, Alg, false); ek.CipherData = new CipherData(encryptedKey); ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); // Set the KeyInfo element to specify the // name of the RSA key. // Create a new KeyInfo element. edElement.KeyInfo = new KeyInfo(); // Create a new KeyInfoName element. KeyInfoName kin = new KeyInfoName(); // Specify a name for the key. kin.Value = KeyName; // Add the KeyInfoName element to the // EncryptedKey object. ek.KeyInfo.AddClause(kin); // Add the encrypted key to the // EncryptedData object. edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek)); // Add the encrypted element data to the // EncryptedData object. edElement.CipherData.CipherValue = encryptedElement; //////////////////////////////////////////////////// // Replace the element from the original XmlDocument // object with the EncryptedData element. //////////////////////////////////////////////////// EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false); }
private KeyInfo GenerateKeyInfo(AsymmetricAlgorithm key, X509Certificate2 signer) { // KeyInfo section KeyInfo keyInfo = new KeyInfo(); KeyInfoName keyInfoName = new KeyInfoName(); keyInfoName.Value = signer.Subject; keyInfo.AddClause(keyInfoName); // human readable Principal name // Include the public key information (if we are familiar with the algorithm type) if (key is RSA) keyInfo.AddClause(new RSAKeyValue((RSA)key)); // RSA key parameters else { if (key is DSA) keyInfo.AddClause(new DSAKeyValue((DSA)key)); // DSA else throw new ArgumentException(SR.Get(SRID.CertificateKeyTypeNotSupported), "signer"); } // the actual X509 cert keyInfo.AddClause(new KeyInfoX509Data(signer)); return keyInfo; }
/// <summary> /// Creates a key used to encrypt messages. /// </summary> /// <returns>The encryption key</returns> private EncryptionKey GetEncryptionKey() { // We generated a symmetric key using triple DES and stored the // key in the configuration file for this application. string keyData = ConfigurationSettings.AppSettings["symmetricKey"]; if (keyData == null) { throw new ApplicationException("Symmetric key not found."); } byte[] keyBytes = Convert.FromBase64String(keyData); SymmetricEncryptionKey key = new SymmetricEncryptionKey(TripleDES.Create(), keyBytes); KeyInfoName keyName = new KeyInfoName(); keyName.Value = "WSDK Sample Symmetric Key"; key.KeyInfo.AddClause(keyName); return key; }
public void CheckSignatureEmptySafe () { SignedXml sx; KeyInfoClause kic; KeyInfo ki; // empty keyinfo passes... sx = new SignedXml (); sx.KeyInfo = new KeyInfo (); Assert.IsTrue (!sx.CheckSignature ()); // with empty KeyInfoName kic = new KeyInfoName (); ki = new KeyInfo (); ki.AddClause (kic); sx.KeyInfo = ki; Assert.IsTrue (!sx.CheckSignature ()); }
/// <summary> /// Encrypts the NameID attribute of the AttributeQuery request. /// </summary> /// <param name="certFriendlyName"> /// Friendly Name of the X509Certificate to be retrieved /// from the LocalMachine keystore and used to encrypt generated symmetric key. /// Be sure to have appropriate permissions set on the keystore. /// </param> /// <param name="xmlDoc"> /// XML document to be encrypted. /// </param> /// <param name="symmetricAlgorithmUri"> /// Symmetric algorithm uri used for encryption. /// </param> public static void EncryptAttributeQueryNameID(string certFriendlyName, string symmetricAlgorithmUri, XmlDocument xmlDoc) { if (string.IsNullOrWhiteSpace(certFriendlyName)) { throw new Saml2Exception(Resources.EncryptedXmlInvalidCertFriendlyName); } if (string.IsNullOrWhiteSpace(symmetricAlgorithmUri)) { throw new Saml2Exception(Resources.EncryptedXmlInvalidEncrAlgorithm); } if (xmlDoc == null) { throw new Saml2Exception(Resources.SignedXmlInvalidXml); } X509Certificate2 cert = FedletCertificateFactory.GetCertificateByFriendlyName(certFriendlyName); if (cert == null) { throw new Saml2Exception(Resources.EncryptedXmlCertNotFound); } XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlDoc.NameTable); nsMgr.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); nsMgr.AddNamespace("saml", Saml2Constants.NamespaceSamlAssertion); nsMgr.AddNamespace("samlp", Saml2Constants.NamespaceSamlProtocol); string xpath = "/samlp:AttributeQuery/saml:Subject/saml:NameID"; XmlNode root = xmlDoc.DocumentElement; XmlNode node = root.SelectSingleNode(xpath, nsMgr); XmlNode encryptedID = xmlDoc.CreateNode(XmlNodeType.Element, "EncryptedID", Saml2Constants.NamespaceSamlAssertion); node.ParentNode.PrependChild(encryptedID); XmlElement elementToEncrypt = (XmlElement)encryptedID.AppendChild(node.Clone()); if (elementToEncrypt == null) { throw new Saml2Exception(Resources.EncryptedXmlInvalidXml); } encryptedID.ParentNode.RemoveChild(node); SymmetricAlgorithm alg = Saml2Utils.GetAlgorithm(symmetricAlgorithmUri); if (alg == null) { throw new Saml2Exception(Resources.EncryptedXmlInvalidEncrAlgorithm); } alg.GenerateKey(); string encryptionElementID = Saml2Utils.GenerateId(); string encryptionKeyElementID = Saml2Utils.GenerateId(); EncryptedData encryptedData = new EncryptedData(); encryptedData.Type = EncryptedXml.XmlEncElementUrl; encryptedData.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES128Url); encryptedData.Id = encryptionElementID; EncryptedXml encryptedXml = new EncryptedXml(); byte[] encryptedElement = encryptedXml.EncryptData(elementToEncrypt, alg, false); encryptedData.CipherData.CipherValue = encryptedElement; encryptedData.KeyInfo = new KeyInfo(); EncryptedKey encryptedKey = new EncryptedKey(); encryptedKey.Id = encryptionKeyElementID; RSA publicKeyRSA = cert.PublicKey.Key as RSA; encryptedKey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); encryptedKey.CipherData = new CipherData(EncryptedXml.EncryptKey(alg.Key, publicKeyRSA, false)); encryptedData.KeyInfo.AddClause(new KeyInfoRetrievalMethod("#" + encryptionKeyElementID, "http://www.w3.org/2001/04/xmlenc#EncryptedKey")); KeyInfoName kin = new KeyInfoName(); kin.Value = cert.SubjectName.Name; encryptedKey.KeyInfo.AddClause(kin); EncryptedXml.ReplaceElement(elementToEncrypt, encryptedData, false); XmlNode importKeyNode = xmlDoc.ImportNode(encryptedKey.GetXml(), true); encryptedID.AppendChild(importKeyNode); }