//Part - II /// <summary> /// Encripts an XmlDocument by RSA algorithm /// </summary> /// <param name="doc"></param> /// <param name="elementToEnc"></param> /// <param name="encryptionElementID"></param> /// <param name="alg"></param> /// <param name="keyName"></param> public static void Encrypt(this XmlDocument doc, string elementToEnc, string encryptionElementID, RSA alg, string keyName) { // Check the arguments. if (doc == null) { throw new ArgumentNullException("Doc"); } if (elementToEnc == 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(elementToEnc)[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 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) { throw e; } finally { if (sessionKey != null) { sessionKey.Clear(); } } }
public static void Encrypt(XmlDocument Doc, string ElementName, SymmetricAlgorithm Key) { // 요소를 체크해라 if (Doc == null) { throw new ArgumentNullException("Doc"); } if (ElementName == null) { throw new ArgumentNullException("ElementToEncrypt"); } if (Key == null) { throw new ArgumentNullException("Alg"); } // 찾아라 / 특별한 요소를 / Xml문서 객체 안에서/ 그리고 창조해라/ 새로운 Xml요소 객체를. XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementName)[0] as XmlElement; // 요소가 없다면 Xml예외를 던져라. if (elementToEncrypt == null) { throw new XmlException("The specified element was not found"); } //암호화된Xml 클래스의 새 인스턴스를 만들고 이를 사용하여 대칭 키로 XmlElement를 암호화하십시오. EncryptedXml eXml = new EncryptedXml(); byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, Key, 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. // Determine what kind of algorithm is being used and supply the appropriate URL to the EncryptionMethod element. // 수신기가 암호 해독에 사용할 알고리즘을 알 수 있도록 EncryptionMethod 요소를 생성하십시오. // 사용 중인 알고리즘의 종류를 결정하고 적절한 URL을 EncryptionMethod 요소에 제공하십시오. string encryptionMethod = null; if (Key is Aes) { encryptionMethod = EncryptedXml.XmlEncAES256Url; } else { // AES로 변환이 안되면 예외처리 하라. throw new CryptographicException("The specified algorithm is not supported or not recommended for XML Encryption."); } edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod); // EncryptedData 객체에 암호화된 요소 데이터를 추가해라. edElement.CipherData.CipherValue = encryptedElement; // Replace the element from the original XmlDocument object with the EncryptedData element. // 원래 XmlDocument 개체의 요소를 암호화된 데이터 요소로 교체하십시오. EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false); }
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); // Save some more information about the key using // the EncryptionProperty element. In this example, // we will save the value "LibVersion1". You can save // anything you want here. // Create a new "EncryptionProperty" XmlElement object. XmlElement element = new XmlDocument().CreateElement("EncryptionProperty", EncryptedXml.XmlEncNamespaceUrl); // Set the value of the EncryptionProperty" XmlElement object. element.InnerText = "LibVersion1"; // Create the EncryptionProperty object using the XmlElement object. EncryptionProperty encProp = new EncryptionProperty(element); // Add the EncryptionProperty object to the EncryptedData object. edElement.AddProperty(encProp); // 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); }
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 Aes key. Aes sessionKey = Aes.Create(); 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); }
public void EncryptData_XmlElementNull() { EncryptedXml ex = new EncryptedXml(); ex.EncryptData(null, Rijndael.Create(), true); }
public void RoundtripSample1() { using (StringWriter sw = new StringWriter()) { // Encryption { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml("<root> <child>sample</child> </root>"); XmlElement body = doc.DocumentElement; using (Aes aes = Aes.Create()) { aes.Mode = CipherMode.CBC; aes.KeySize = 256; aes.IV = Convert.FromBase64String("pBUM5P03rZ6AE4ZK5EyBrw=="); aes.Key = Convert.FromBase64String("o/ilseZu+keLBBWGGPlUHweqxIPc4gzZEFWr2nBt640="); aes.Padding = PaddingMode.Zeros; EncryptedXml exml = new EncryptedXml(); byte[] encrypted = exml.EncryptData(body, aes, false); EncryptedData edata = new EncryptedData(); edata.Type = EncryptedXml.XmlEncElementUrl; edata.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url); EncryptedKey ekey = new EncryptedKey(); // omit key encryption, here for testing byte[] encKeyBytes = aes.Key; ekey.CipherData = new CipherData(encKeyBytes); ekey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); DataReference dr = new DataReference(); dr.Uri = "_0"; ekey.AddReference(dr); edata.KeyInfo.AddClause(new KeyInfoEncryptedKey(ekey)); ekey.KeyInfo.AddClause(new RSAKeyValue(RSA.Create())); edata.CipherData.CipherValue = encrypted; EncryptedXml.ReplaceElement(doc.DocumentElement, edata, false); doc.Save(new XmlTextWriter(sw)); } } // Decryption { using (Aes aes = Aes.Create()) { aes.Mode = CipherMode.CBC; aes.KeySize = 256; aes.Key = Convert.FromBase64String( "o/ilseZu+keLBBWGGPlUHweqxIPc4gzZEFWr2nBt640="); aes.Padding = PaddingMode.Zeros; XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(sw.ToString()); EncryptedXml encxml = new EncryptedXml(doc); EncryptedData edata = new EncryptedData(); edata.LoadXml(doc.DocumentElement); encxml.ReplaceData(doc.DocumentElement, encxml.DecryptData(edata, aes)); } } } }
public void EncryptData_DataNull() { EncryptedXml ex = new EncryptedXml(); Assert.Throws <ArgumentNullException>(() => ex.EncryptData(null, Aes.Create())); }
public void EncryptData_DataNull() { EncryptedXml ex = new EncryptedXml(); ex.EncryptData(null, Rijndael.Create()); }
/** * Doc = documentul xml * ElementToEncrypt = numele elementului de criptat * EncryptionElementID = id-ul elementului ce va fi criptat * RSA = algoritmul de criptare (algoritm asimetric) * KeyNane = numele cheii de criptare */ public static void Encrypt(XmlDocument Doc, string ElementToEncrypt, string EncryptionElementID, RSA Alg, string KeyName) { // Verificarea argumentelor 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"); } //////////////////////////////////////////////// // Identificarea elementului de criptat //////////////////////////////////////////////// XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementToEncrypt)[0] as XmlElement; // Daca nu este gasit se arunca o exceptie if (elementToEncrypt == null) { throw new XmlException("The specified element was not found"); } RijndaelManaged sessionKey = null; try { ////////////////////////////////////////////////// // Se creeaza o noua instanta a clasei EncryptedXml // si se foloseste pentru criptarea elementului xml // cu o noua cheie simetrica generata random. ////////////////////////////////////////////////// // Se creaza o cheie de sesiune SIMETRICA Rijndael de 256 de biti sessionKey = new RijndaelManaged(); sessionKey.KeySize = 256; EncryptedXml eXml = new EncryptedXml(); byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, false); //////////////////////////////////////////////// // Se creeaza un obiect EncryptedData si se populeaza // cu informatia criptata. //////////////////////////////////////////////// EncryptedData edElement = new EncryptedData(); edElement.Type = EncryptedXml.XmlEncElementUrl; edElement.Id = EncryptionElementID; // Se creeaza un element de tip EncryptionMethod astfel incat // destinatarul sa stie ce algoritm va folosi pentru decriptare. edElement.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url); // Cripteaza cheia de sesiune si se adauga intr-un element de tip EncryptedKey. EncryptedKey ek = new EncryptedKey(); byte[] encryptedKey = EncryptedXml.EncryptKey(sessionKey.Key, Alg, false); ek.CipherData = new CipherData(encryptedKey); ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); // Din cauza faptului ca un document xml poate avea // mai multe elemente EncrypredData criptate cu mai multe chei // este nevoie de specificarea unui element de tip DataReference // care sa indice elementul criptat cu aceasta cheie DataReference dRef = new DataReference(); // Se specifica URI-ul dRef.Uri = "#" + EncryptionElementID; // Se adauga DataReference la EncryptedKey. ek.AddReference(dRef); // Se adauga cheia criptata la obiectul EncryptedData // EncryptedData object. edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek)); // Se seteaza numele cheii RSA KeyInfoName kin = new KeyInfoName(); kin.Value = KeyName; // Adauga obiectul kin la cheia criptata ek.KeyInfo.AddClause(kin); // Se adauga elementul criptat edElement.CipherData.CipherValue = encryptedElement; //////////////////////////////////////////////////// // Se inlocuieste elementul original cu elementul criptat //////////////////////////////////////////////////// EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false); } catch (Exception e) { // re-throw the exception. throw e; } finally { if (sessionKey != null) { sessionKey.Clear(); } } }
public static void Encrypt(XmlDocument Doc, string ElementToEncrypt, string EncryptionElementID, RSA Alg, string KeyName) { 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"); } XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementToEncrypt)[0] as XmlElement; if (elementToEncrypt == null) { throw new XmlException("The specified element was not found"); } Aes sessionKey = null; try { sessionKey = Aes.Create(); EncryptedXml eXml = new EncryptedXml(); byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, false); EncryptedData edElement = new EncryptedData(); edElement.Type = EncryptedXml.XmlEncElementUrl; edElement.Id = EncryptionElementID; edElement.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url); EncryptedKey ek = new EncryptedKey(); byte[] encryptedKey = EncryptedXml.EncryptKey(sessionKey.Key, Alg, false); ek.CipherData = new CipherData(encryptedKey); ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); DataReference dRef = new DataReference(); dRef.Uri = "#" + EncryptionElementID; ek.AddReference(dRef); edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek)); KeyInfoName kin = new KeyInfoName(); kin.Value = KeyName; ek.KeyInfo.AddClause(kin); edElement.CipherData.CipherValue = encryptedElement; EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false); } catch (Exception e) { // re-throw the exception. throw e; } finally { if (sessionKey != null) { sessionKey.Clear(); } } }
/// <summary> /// Encrypts the specified XML element. /// </summary> /// <param name="plaintextElement">The plaintext to encrypt.</param> /// <returns> /// An <see cref="EncryptedXmlInfo" /> that contains the encrypted value of /// <paramref name="plaintextElement" /> along with information about how to /// decrypt it. /// </returns> /// <exception cref="System.ArgumentNullException"> /// Thrown if <paramref name="plaintextElement" /> is <see langword="null" />. /// </exception> /// <exception cref="ObjectDisposedException"> /// Thrown if this method is called after <see cref="Dispose()"/> is called. /// </exception> public EncryptedXmlInfo Encrypt(XElement plaintextElement) { if (plaintextElement == null) { throw new ArgumentNullException(nameof(plaintextElement)); } if (this._disposed) { throw new ObjectDisposedException("Unable to encrypt after the object has been disposed."); } this.Logger.LogDebug("Encrypting XML with certificate {0}.", this._keyName); // Create a faux XML document from the XElement so we can use EncryptedXml. var xmlDocument = plaintextElement.ToXmlDocumentWithRootNode(); var elementToEncrypt = xmlDocument.ElementToProcess(); // Do the actual encryption. Algorithm based on MSDN docs: // https://msdn.microsoft.com/en-us/library/ms229746(v=vs.110).aspx var encryptedXml = new EncryptedXml(); var encryptedElement = encryptedXml.EncryptData(elementToEncrypt, this._sessionKey, false); // Build the wrapper elements that provide information about // the algorithms used, the name of the key used, and so on. var encryptedData = new EncryptedData { Type = EncryptedXml.XmlEncElementUrl, Id = EncryptedElementId, EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url), }; var encryptedKey = new EncryptedKey { CipherData = new CipherData(EncryptedXml.EncryptKey(this._sessionKey.Key, this._keyProvider, false)), EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url), }; // "Connect" the encrypted data and encrypted key with // element references. var encryptedElementDataReference = new DataReference { Uri = "#" + EncryptedElementId, }; encryptedKey.AddReference(encryptedElementDataReference); encryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedKey)); var keyName = new KeyInfoName { Value = this._keyName, }; encryptedKey.KeyInfo.AddClause(keyName); encryptedData.CipherData.CipherValue = encryptedElement; // Swap the plaintext element for the encrypted element. EncryptedXml.ReplaceElement(elementToEncrypt, encryptedData, false); return(new EncryptedXmlInfo(xmlDocument.ElementToProcess().ToXElement(), typeof(CertificateXmlDecryptor))); }
//加密 private void btnJiaMi_Click(object sender, EventArgs e) { if (label1.Text == "") { return; } try { //生产对称密钥.该密钥用来对XML加密 RijndaelManaged key = new RijndaelManaged(); keyIv = key.IV; keyKey = key.Key; //加载XML对象,定制加密位置 XmlDocument xmlDoc = new XmlDocument(); xmlDoc.PreserveWhitespace = true; xmlDoc.Load(this.label1.Text); XmlElement elementToEncrypt = xmlDoc.GetElementsByTagName("creditcard")[0] as XmlElement; //生产EncrypteData类 EncryptedData edElement = new EncryptedData(); edElement.Type = EncryptedXml.XmlEncElementUrl;//填充Url标识符 string encryptionMethod = null; if (key is TripleDES) { encryptionMethod = EncryptedXml.XmlEncTripleDESUrl; } else if (key is DES) { encryptionMethod = EncryptedXml.XmlEncDESUrl; } if (key is Rijndael) { switch (key.KeySize) { case 128: encryptionMethod = EncryptedXml.XmlEncAES128Url; break; case 192: encryptionMethod = EncryptedXml.XmlEncAES192Url; break; case 256: encryptionMethod = EncryptedXml.XmlEncAES256Url; break; } } else { throw new CryptographicException("没有为XML加密的指定算法!"); } edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod);//生成具有加密算法的Url标识符 //用EncryptedXml加密xml EncryptedXml eXml = new EncryptedXml(); byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, key, false); //把加密的元素添加到EncryptedData中 edElement.CipherData.CipherValue = encryptedElement; //最后将xml中原始数据和EncrytedXml替换 EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false); xmlDoc.Save(this.label1.Text); succes(); } catch (Exception ex) { fail(); } }
/// <summary> /// Encrypt the element within the xml document. /// </summary> /// <param name="document">The xml document containing the element to encrypt.</param> /// <param name="elementToEncrypt">The element to encrypt in the xml document.</param> /// <param name="algorithm">The symmetric alogorithm used to encrypt the element.</param> /// <param name="keyName">The name to map to keyObject.</param> public void Encrypt(XmlDocument document, string elementToEncrypt, SymmetricAlgorithm algorithm, string keyName) { // Check the arguments. if (document == null) { throw new ArgumentNullException("document"); } if (string.IsNullOrEmpty(elementToEncrypt)) { throw new ArgumentNullException("elementToEncrypt"); } if (string.IsNullOrEmpty(keyName)) { throw new ArgumentNullException("keyName"); } if (document == null) { throw new ArgumentNullException("algorithm"); } // Find the specified element in the XmlDocument // object and create a new XmlElemnt object. XmlElement element = document.GetElementsByTagName(elementToEncrypt)[0] as XmlElement; // Throw an XmlException if the element was not found. if (element == 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 // symmetric key. EncryptedXml eXml = new EncryptedXml(); byte[] encryptedElement = eXml.EncryptData(element, algorithm, 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. // Determine what kind of algorithm is being used and // supply the appropriate URL to the EncryptionMethod element. string encryptionMethod = null; if (algorithm is TripleDES) { encryptionMethod = EncryptedXml.XmlEncTripleDESUrl; } else if (algorithm is DES) { encryptionMethod = EncryptedXml.XmlEncDESUrl; } else if (algorithm is Rijndael) { switch (algorithm.KeySize) { case 128: encryptionMethod = EncryptedXml.XmlEncAES128Url; break; case 192: encryptionMethod = EncryptedXml.XmlEncAES192Url; break; case 256: encryptionMethod = EncryptedXml.XmlEncAES256Url; break; } } else { // Throw an exception if the transform is not in the previous categories throw new CryptographicException("The specified algorithm is not supported for XML Encryption."); } // Set the encryption method. edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod); // Set the KeyInfo element to specify the // name of a 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. edElement.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(element, edElement, false); }
public static void Encrypt(XmlDocument doc) { SymmetricAlgorithm symAlgo = new RijndaelManaged(); byte[] salt = Encoding.ASCII.GetBytes("This is my salt"); Rfc2898DeriveBytes theKey = new Rfc2898DeriveBytes("myclass", salt); symAlgo.Key = theKey.GetBytes(symAlgo.KeySize / 8); symAlgo.IV = theKey.GetBytes(symAlgo.BlockSize / 8); if (doc == null) { throw new ArgumentNullException("Doc"); } if (symAlgo == null) { throw new ArgumentNullException("Alg"); } XmlElement elementToEncrypt = doc.DocumentElement; if (elementToEncrypt == null) { throw new XmlException("The specified element was not found"); } EncryptedXml eXml = new EncryptedXml(); byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, symAlgo, false); EncryptedData edElement = new EncryptedData(); edElement.Type = EncryptedXml.XmlEncElementUrl; string encryptionMethod = null; if (symAlgo is TripleDES) { encryptionMethod = EncryptedXml.XmlEncTripleDESUrl; } else if (symAlgo is DES) { encryptionMethod = EncryptedXml.XmlEncDESUrl; } if (symAlgo is Rijndael) { switch (symAlgo.KeySize) { case 128: encryptionMethod = EncryptedXml.XmlEncAES128Url; break; case 192: encryptionMethod = EncryptedXml.XmlEncAES192Url; break; case 256: encryptionMethod = EncryptedXml.XmlEncAES256Url; break; default: // do the defalut action break; } } else { throw new CryptographicException("The specified algorithm is not supported for XML Encryption."); } edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod); edElement.CipherData.CipherValue = encryptedElement; EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false); }
public static void Encrypt(XmlDocument Doc, String ElementName, SymmetricAlgorithm Key) { //Check the arguments provided if (Doc == null) { throw new ArgumentNullException("Doc"); } else if (ElementName == null) { throw new ArgumentNullException("ElementToEncrypt"); } else if (Key == null) { throw new ArgumentNullException("Algorithm"); } //Find the specified xmlElement object, encrypt it then create a new xmlElement object XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementName)[0] as XmlElement; //Throw an XmlException if the element isn't found if (elementToEncrypt == null) { throw new XmlException("The specified element could not be found"); } EncryptedXml eXml = new EncryptedXml(); byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, Key, false); //Create an EncryptedData object and populate it with the desired encrypted information EncryptedData edElement = new EncryptedData(); edElement.Type = EncryptedXml.XmlEncElementUrl; //The EncryptionMethod so that the receiver knows which algorithm to use for decryption string encryptionMethod = null; if (Key is TripleDES) { encryptionMethod = EncryptedXml.XmlEncTripleDESUrl; } else if (Key is DES) { encryptionMethod = EncryptedXml.XmlEncDESUrl; } if (Key is Rijndael) { switch (Key.KeySize) { case 128: encryptionMethod = EncryptedXml.XmlEncAES128Url; break; case 192: encryptionMethod = EncryptedXml.XmlEncAES192Url; break; case 256: encryptionMethod = EncryptedXml.XmlEncAES256Url; break; } } else { //Throw an exception if the transform is not in the previous categories throw new CryptographicException("The specified algorithm is not supported for XML"); } edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod); //Add the encrypted element data to the original XMlDocument object with the EncryptedData element edElement.CipherData.CipherValue = encryptedElement; //Replace the element from the original XmlDocument object with the Encrypted Data element EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false); }
internal static void Encrypt(this XmlElement elementToEncrypt, EncryptingCredentials encryptingCredentials) { if (elementToEncrypt == null) { throw new ArgumentNullException(nameof(elementToEncrypt)); } if (encryptingCredentials == null) { throw new ArgumentNullException(nameof(encryptingCredentials)); } string enc; int keySize; switch (encryptingCredentials.Enc) { case SecurityAlgorithms.Aes128CbcHmacSha256: enc = EncryptedXml.XmlEncAES128Url; keySize = 128; break; case SecurityAlgorithms.Aes192CbcHmacSha384: enc = EncryptedXml.XmlEncAES192Url; keySize = 192; break; case SecurityAlgorithms.Aes256CbcHmacSha512: enc = EncryptedXml.XmlEncAES256Url; keySize = 256; break; default: throw new CryptographicException( $"Unsupported cryptographic algorithm {encryptingCredentials.Enc}"); } var encryptedData = new EncryptedData { Type = EncryptedXml.XmlEncElementUrl, EncryptionMethod = new EncryptionMethod(enc) }; string alg; switch (encryptingCredentials.Alg) { case SecurityAlgorithms.RsaOAEP: alg = EncryptedXml.XmlEncRSAOAEPUrl; break; case SecurityAlgorithms.RsaPKCS1: alg = EncryptedXml.XmlEncRSA15Url; break; default: throw new CryptographicException( $"Unsupported cryptographic algorithm {encryptingCredentials.Alg}"); } var encryptedKey = new EncryptedKey { EncryptionMethod = new EncryptionMethod(alg), }; var encryptedXml = new EncryptedXml(); byte[] encryptedElement; using (var symmetricAlgorithm = new RijndaelManaged()) { X509SecurityKey x509SecurityKey = encryptingCredentials.Key as X509SecurityKey; if (x509SecurityKey == null) { throw new CryptographicException( "The encrypting credentials have an unknown key of type {encryptingCredentials.Key.GetType()}"); } symmetricAlgorithm.KeySize = keySize; encryptedKey.CipherData = new CipherData(EncryptedXml.EncryptKey(symmetricAlgorithm.Key, (RSA)x509SecurityKey.PublicKey, alg == EncryptedXml.XmlEncRSAOAEPUrl)); encryptedElement = encryptedXml.EncryptData(elementToEncrypt, symmetricAlgorithm, false); } encryptedData.CipherData.CipherValue = encryptedElement; encryptedData.KeyInfo = new KeyInfo(); encryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedKey)); EncryptedXml.ReplaceElement(elementToEncrypt, encryptedData, false); }
public static String EncryptXML(String xml, SymmetricAlgorithm key = null) { if (String.IsNullOrEmpty(xml)) { throw new ArgumentNullException("xml"); } if (key == null) { key = DefaultCryptographyKey; } var xmlDoc = default(XmlDocument); var element = default(XmlElement); var eXml = default(EncryptedXml); var encryptedElement = default(Byte[]); var edElement = default(EncryptedData); var encryptionMethod = string.Empty; xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xml); element = xmlDoc.DocumentElement; eXml = new EncryptedXml(); Contract.Assert(element != null, "element != null"); encryptedElement = eXml.EncryptData(element, key, false); edElement = new EncryptedData { Type = EncryptedXml.XmlEncElementUrl }; if (key is TripleDES) { encryptionMethod = EncryptedXml.XmlEncTripleDESUrl; } else if (key is DES) { encryptionMethod = EncryptedXml.XmlEncDESUrl; } if (key is Rijndael) { switch (key.KeySize) { case 128: encryptionMethod = EncryptedXml.XmlEncAES128Url; break; case 192: encryptionMethod = EncryptedXml.XmlEncAES192Url; break; case 256: encryptionMethod = EncryptedXml.XmlEncAES256Url; break; } } else { // Throw an exception if the transform is not in the previous categories throw new CryptographicException("The specified algorithm is not supported for XML Encryption."); } edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod); // Add the encrypted element data to the // EncryptedData object. edElement.CipherData.CipherValue = encryptedElement; EncryptedXml.ReplaceElement(element, edElement, false); return(xmlDoc.OuterXml); }
public void EncryptData_SymmetricAlgorithmNull() { EncryptedXml ex = new EncryptedXml(); ex.EncryptData(new byte[16], null); }
/// <summary> /// XML数据加密 /// </summary> /// <param name="xmlDocument">XML 文档的实例</param> /// <param name="nodeName">需要加密的 XML 节点名字</param> /// <param name="key">密钥</param> public void Encrypt(XmlDocument xmlDocument, string nodeName) { // 检查参数 if (xmlDocument == null) { throw new ArgumentNullException("xmlDocument"); } if (nodeName == null || nodeName.Length == 0) { throw new ArgumentNullException("nodeName"); } if (mKey == null) { throw new ArgumentNullException("mKey"); } //////////////////////////////////////////////// // 在XmlDocument找到指定的元素对象,并创建一个新的XmlElemnt对象。 //////////////////////////////////////////////// XmlElement elementToEncrypt = xmlDocument.GetElementsByTagName(nodeName)[0] as XmlElement; // 如果元素不能被发现,抛出一个XmlException。 if (elementToEncrypt == null) { throw new XmlException("指定的元素不能被发现"); } ////////////////////////////////////////////////// // 创建一个新的实例的EncryptedXml类和使用它来加密XmlElement和对称密钥 ////////////////////////////////////////////////// EncryptedXml eXml = new EncryptedXml(); byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, mKey, false); //////////////////////////////////////////////// // 构造一个EncryptedData对象并填充所需的加密信息。 //////////////////////////////////////////////// EncryptedData edElement = new EncryptedData(); edElement.Type = EncryptedXml.XmlEncElementUrl; // 创建一个EncryptionMethod元素,以便接收方知道这算法用于解密。 // 确定什么样的算法被使用和供应适当的URL到EncryptionMethod元素。 string encryptionMethod = null; if (mKey is Rijndael) { switch (mKey.KeySize) { case 128: encryptionMethod = EncryptedXml.XmlEncAES128Url; break; case 192: encryptionMethod = EncryptedXml.XmlEncAES192Url; break; case 256: encryptionMethod = EncryptedXml.XmlEncAES256Url; break; default: throw new CryptographicException("此算法只支持16位, 24位, 32位的密钥"); } } else { // 如果变换不是在前面的类别,抛出一个异常 throw new CryptographicException("指定的算法不支持XML加密"); } edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod); // 添加加密元素数据到EncryptedData对象。 edElement.CipherData.CipherValue = encryptedElement; //////////////////////////////////////////////////// // 从原始XmlDocument对象与EncryptedData元素替换元素。 //////////////////////////////////////////////////// EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false); }
public override XmlNode Encrypt(XmlNode node) { XmlDocument xmlDocument; EncryptedXml exml; byte[] rgbOutput; EncryptedData ed; KeyInfoName kin; 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; using (SymmetricAlgorithm symAlg = GetSymAlgorithmProvider()) { rgbOutput = exml.EncryptData(inputElement, symAlg, true); ed = new EncryptedData(); ed.Type = EncryptedXml.XmlEncElementUrl; ed.EncryptionMethod = GetSymEncryptionMethod(); 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); rsa.Clear(); // 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); }
/// <summary> /// Retrieves a certificate from the Personal Certificate Store in Windows. /// </summary> /// <param name="sujetoCertificado"></param> /// <returns></returns> static void Encriptar(ref XmlDocument document, string elementoParaEncriptar, X509Certificate2 certificadopublico, ref XmlElement securityNode) { RSACryptoServiceProvider rsaAlgorithm = (RSACryptoServiceProvider)certificadopublico.PublicKey.Key; //llave publica usada para encriptar. //Ahora creamos un BinarySecurityToken que será el certificado x509 de la clave pública //se usa para que el receptor sepa qué certificado se usó para encriptar. XmlElement binarySecurityTokenNode = document.CreateElement("wsse", "BinarySecurityToken", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); //El atributo EncodingType dice cómo el Token está codificado, en este caso, Base64Binary. binarySecurityTokenNode.SetAttribute("EncodingType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"); //El atributo ValueType indica qué es el BinarySecurityToken, en este caso un Certificado X509v3. binarySecurityTokenNode.SetAttribute("ValueType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"); binarySecurityTokenNode.SetAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", XmlElementsIds.PublicKeyBinarySecurityTokenUri); XmlAttribute attribute = binarySecurityTokenNode.GetAttributeNode("Id"); attribute.Prefix = "wsu"; binarySecurityTokenNode.InnerText = Convert.ToBase64String(certificadopublico.GetRawCertData()); //Creamos una llave simétrica la cuál servirá para codificar la información. //AES-128-CBC AesManaged algoritmosimetrico = new AesManaged() { Padding = PaddingMode.ISO10126, KeySize = 128, Mode = CipherMode.CBC, }; System.Security.Cryptography.Xml.EncryptedKey encryptedKey = new System.Security.Cryptography.Xml.EncryptedKey(); encryptedKey.EncryptionMethod = new System.Security.Cryptography.Xml.EncryptionMethod(EncryptedXml.XmlEncRSAOAEPUrl); encryptedKey.AddReference(new DataReference("#ED-31")); SecurityTokenReference securityTokenReference = new SecurityTokenReference(); securityTokenReference.Reference = XmlElementsIds.PublicKeyBinarySecurityTokenUri; securityTokenReference.ValueType = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"; KeyInfo ekkeyInfo = new KeyInfo(); ekkeyInfo.AddClause(new KeyInfoNode(securityTokenReference.GetXml())); encryptedKey.KeyInfo = ekkeyInfo; encryptedKey.CipherData = new CipherData(EncryptedXml.EncryptKey(algoritmosimetrico.Key, rsaAlgorithm, true)); securityNode.PrependChild(document.ImportNode(encryptedKey.GetXml(), true)); securityNode.PrependChild(binarySecurityTokenNode); //Crear un XmlElement a través del nombre del Tag que se encuentra en el documento Xml especificado. XmlElement elementoParaEncriptarXML = document.GetElementsByTagName(elementoParaEncriptar)[0] as XmlElement; //Creamos una instancia de la clase EncryptedXml y usarla para encriptar //el XmlElement: elementoParaEncriptarXML; usando la llave simétrica que acabamos de //crear. EncryptedXml xmlEncriptado = new EncryptedXml(); //Encriptamos el Body (elementoParaEncriptarXML) usando el algoritmo simétrico AES-128-CBC y lo dejamos ahí. byte[] elementoEncriptado = xmlEncriptado.EncryptData(elementoParaEncriptarXML, algoritmosimetrico, false); //Ahora creamos una instancia de la clase EncryptedData que representa //un elemento <EncryptedData> en el documento XML. System.Security.Cryptography.Xml.EncryptedData encryptedData = new System.Security.Cryptography.Xml.EncryptedData() { Type = EncryptedXml.XmlEncElementContentUrl, Id = "ED-31", //Le asignamos otra propiedad a este elemento <EncryptedData> que es un EncryptionMethod //para que el receptor sepa que algoritmo usar para descifrar EncryptionMethod = new System.Security.Cryptography.Xml.EncryptionMethod(EncryptedXml.XmlEncAES128Url) //Aes-128-cbc o Rjindael. }; encryptedData.CipherData = new CipherData(elementoEncriptado); /* Para descencriptar: Funciona, es para testear si puedo desencriptar los datos. * var lmao= xmlEncriptado.DecryptData(encryptedData, algoritmosimetrico); * var decrypted = Encoding.UTF8.GetString(lmao); */ //Reemplazamos el elemento quotationCarGenericRq sin encriptar del documento XML con el elemento <EncryptedData> (que contiene el Body y sus contenidos encriptados) básicamente. //totalmente lleno. EncryptedXml.ReplaceElement(elementoParaEncriptarXML, encryptedData, false); }
public void EncryptData_SymmetricAlgorithmNull() { EncryptedXml ex = new EncryptedXml(); Assert.Throws <ArgumentNullException>(() => ex.EncryptData(new byte[16], null)); }
/// <summary> /// Encrypts the specified x document. /// </summary> /// <param name="xDoc">The x document.</param> /// <param name="elementToEncrypt">The element to encrypt.</param> /// <param name="algo">The algo.</param> /// <param name="keyName">Name of the key.</param> /// <returns></returns> /// <exception cref="System.Security.Cryptography.CryptographicException"> /// The specified algorithm is not supported for XML Encryption. /// </exception> public static XmlDocument Encrypt(ref XmlDocument xDoc, XmlElement elementToEncrypt, SymmetricAlgorithm algo, string keyName) { var docCopy = (XmlDocument)xDoc.Clone(); docCopy.PreserveWhitespace = xDoc.PreserveWhitespace; var eXml = new EncryptedXml(); var encryptedElement = eXml.EncryptData(elementToEncrypt, algo, false); var edElement = new EncryptedData() { Type = EncryptedXml.XmlEncElementUrl }; string encryptionMethod = null; if (algo is TripleDES) { encryptionMethod = EncryptedXml.XmlEncTripleDESUrl; } else { if (algo is DES) { encryptionMethod = EncryptedXml.XmlEncDESUrl; } else { if (algo is Rijndael) { switch (algo.KeySize) { case 128: encryptionMethod = EncryptedXml.XmlEncAES128Url; break; case 192: encryptionMethod = EncryptedXml.XmlEncAES192Url; break; case 256: encryptionMethod = EncryptedXml.XmlEncAES256Url; break; default: throw new CryptographicException(string.Format("Unsupported key size: {0}", algo.KeySize)); } } else { throw new CryptographicException("The specified algorithm is not supported for XML Encryption."); } } } edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod); edElement.KeyInfo = new KeyInfo(); edElement.KeyInfo.AddClause(new KeyInfoName(keyName)); edElement.CipherData.CipherValue = encryptedElement; EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false); if (xDoc.FirstChild is XmlDeclaration) { xDoc.RemoveChild(xDoc.FirstChild); } var rDoc = xDoc; xDoc = docCopy; return(rDoc); }
/// <summary> /// Encrypts the XML node passed to it. /// </summary> /// <param name="node">The XmlNode to encrypt.</param> /// <returns></returns> public override XmlNode Encrypt(XmlNode node) { // Get the RSA public key to encrypt the node. This key will encrypt // a symmetric key, which will then be encryped in the XML document. RSACryptoServiceProvider cryptoServiceProvider = this.GetCryptoServiceProvider(true); // Create an XML document and load the node to be encrypted in it. XmlDocument document = new XmlDocument(); document.PreserveWhitespace = true; document.LoadXml("<Data>" + node.OuterXml + "</Data>"); // Create a new instance of the EncryptedXml class // and use it to encrypt the XmlElement with the // a new random symmetric key. EncryptedXml xml = new EncryptedXml(document); XmlElement documentElement = document.DocumentElement; SymmetricAlgorithm symmetricAlgorithm = new RijndaelManaged(); // Create a 192 bit random key. symmetricAlgorithm.Key = this.GetRandomKey(); symmetricAlgorithm.GenerateIV(); symmetricAlgorithm.Padding = PaddingMode.PKCS7; byte[] buffer = xml.EncryptData(documentElement, symmetricAlgorithm, true); // Construct an EncryptedData object and populate // it with the encryption information. EncryptedData encryptedData = new EncryptedData(); encryptedData.Type = EncryptedXml.XmlEncElementUrl; // Create an EncryptionMethod element so that the // receiver knows which algorithm to use for decryption. encryptedData.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES192Url); encryptedData.KeyInfo = new KeyInfo(); // Encrypt the session key and add it to an EncryptedKey element. EncryptedKey encryptedKey = new EncryptedKey(); encryptedKey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); encryptedKey.KeyInfo = new KeyInfo(); encryptedKey.CipherData = new CipherData(); encryptedKey.CipherData.CipherValue = EncryptedXml.EncryptKey(symmetricAlgorithm.Key, cryptoServiceProvider, false); KeyInfoName clause = new KeyInfoName(); clause.Value = "rsaKey"; // Add the encrypted key to the EncryptedData object. encryptedKey.KeyInfo.AddClause(clause); KeyInfoEncryptedKey key2 = new KeyInfoEncryptedKey(encryptedKey); encryptedData.KeyInfo.AddClause(key2); encryptedData.CipherData = new CipherData(); encryptedData.CipherData.CipherValue = buffer; // Replace the element from the original XmlDocument // object with the EncryptedData element. 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 static XmlDocument Encrypt(XmlDocument Doc, string ElementToEncrypt, string KeyName) { CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = "XML_ENC_RSA_KEY"; RSA Alg = new RSACryptoServiceProvider(cspParams); // Check the arguments. if (Doc == null) { throw new ArgumentNullException("Doc"); } if (ElementToEncrypt == null) { throw new ArgumentNullException("ElementToEncrypt"); } 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 = new RijndaelManaged(); sessionKey.KeySize = 256; EncryptedXml eXml = new EncryptedXml(); byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, false); 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; EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false); return(Doc); }
public static void Encrypt(XmlDocument Doc, string ElementName, SymmetricAlgorithm Key) { // Check the arguments. if (Doc == null) { throw new ArgumentNullException("Doc"); } if (ElementName == null) { throw new ArgumentNullException("ElementToEncrypt"); } if (Key == null) { throw new ArgumentNullException("Alg"); } //////////////////////////////////////////////// // Find the specified element in the XmlDocument // object and create a new XmlElemnt object. //////////////////////////////////////////////// XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementName)[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 // symmetric key. ////////////////////////////////////////////////// EncryptedXml eXml = new EncryptedXml(); byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, Key, 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. // Determine what kind of algorithm is being used and // supply the appropriate URL to the EncryptionMethod element. string encryptionMethod = null; if (Key is TripleDES) { encryptionMethod = EncryptedXml.XmlEncTripleDESUrl; } else if (Key is DES) { encryptionMethod = EncryptedXml.XmlEncDESUrl; } if (Key is Rijndael) { switch (Key.KeySize) { case 128: encryptionMethod = EncryptedXml.XmlEncAES128Url; break; case 192: encryptionMethod = EncryptedXml.XmlEncAES192Url; break; case 256: encryptionMethod = EncryptedXml.XmlEncAES256Url; break; } } else { // Throw an exception if the transform is not in the previous categories throw new CryptographicException("The specified algorithm is not supported for XML Encryption."); } edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod); // 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); }
// Зашифрование узла XML документа на ассиметричном ключе private static void Encrypt(string srcName, string destName, string xpath, string EncryptionElementID, AsymmetricAlgorithm alg, string KeyName) { // Создаем новый объект xml документа. XmlDocument xmlDoc = new XmlDocument(); // Пробельные символы участвуют в вычислении подписи и должны быть сохранены для совместимости с другими реализациями xmlDoc.PreserveWhitespace = true; // Загружаем в объект созданный XML документ. xmlDoc.Load(srcName); // Ищем заданный элемент для заширования. XmlElement elementToEncrypt = xmlDoc.SelectSingleNode(xpath) as XmlElement; if (elementToEncrypt == null) { throw new XmlException("Узел не найден"); } // Создаем случайный симметричный ключ. // В целях безопасности удаляем ключ из памяти после использования. using (Gost28147CryptoServiceProvider sessionKey = new Gost28147CryptoServiceProvider()) { // Создаем объект класса EncryptedXml и используем // его для зашифрования узла на случайной симметричном ключе. EncryptedXml eXml = new EncryptedXml(); // Зашифровываем элемент на сессионном ключе. byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, false); // Создаем объект EncryptedData и заполняем его // необходимой информацией. EncryptedData edElement = new EncryptedData(); // Тип элемента зашифрованный узел edElement.Type = EncryptedXml.XmlEncElementUrl; // Созданный элемент помечаем EncryptionElementID edElement.Id = EncryptionElementID; // Заполняем алгоритм зашифрования данных. // Он будет использован при расшифровании. edElement.EncryptionMethod = new EncryptionMethod( EncryptedXml.XmlEncGost28147Url); // Зашифровываем сессионный ключ и добавляем эти зашифрованные данные // к узлу EncryptedKey. EncryptedKey ek = new EncryptedKey(); byte[] encryptedKey; if (alg is Gost3410 gost3410) { encryptedKey = EncryptedXml.EncryptKey(sessionKey, gost3410); } else if (alg is Gost3410_2012_256 gost3410_2012_256) { encryptedKey = EncryptedXml.EncryptKey(sessionKey, gost3410_2012_256); } else if (alg is Gost3410_2012_512 gost3410_2012_512) { encryptedKey = EncryptedXml.EncryptKey(sessionKey, gost3410_2012_512); } else { throw new NotSupportedException(); } ek.CipherData = new CipherData(encryptedKey); ek.EncryptionMethod = new EncryptionMethod( EncryptedXml.XmlEncGostKeyTransportUrl); // Создаем элемент DataReference для KeyInfo. // Эта необязательная операция позволяет указать // какие данные используют данный ключ. // XML документ может содержвать несколько // элементов EncryptedData с различными ключами. DataReference dRef = new DataReference(); // Указываем URI EncryptedData. // Для этого используем ранее проставленную ссылку // EncryptionElementID dRef.Uri = "#" + EncryptionElementID; // Добавляем к EncryptedKey ссылку на зашифрованные // данные. ek.AddReference(dRef); // Создаем новую ссылку на ключ. edElement.KeyInfo = new KeyInfo(); // Добавляем ссылку на зашифрованный ключ к // зашифрованным данным. edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek)); // Указываем имя ассиметричного ключа. // Создаем новый элемент KeyInfoName KeyInfoName kin = new KeyInfoName(); // Указываем имя ассиметричного ключа. kin.Value = KeyName; // Добавляем элемент KeyInfoName к // объекту EncryptedKey. ek.KeyInfo.AddClause(kin); // Добавляем зашифрованные данные // к объекту EncryptedData. edElement.CipherData.CipherValue = encryptedElement; // Заменяем исходный узел на зашифрованный. EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false); // Сохраняем зашифрованный документ. xmlDoc.Save(destName); } }
/// <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); }
public void EncryptData_XmlElementNull() { EncryptedXml ex = new EncryptedXml(); Assert.Throws <ArgumentNullException>(() => ex.EncryptData(null, Rijndael.Create(), true)); }
public void Encrypt(string xmlFileName) { TripleDESCryptoServiceProvider encryptionKey = new TripleDESCryptoServiceProvider(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(xmlFileName); encryptionKey.Key = UTF8Encoding.UTF8.GetBytes(""); // your salt value XmlElement orderElem = xmlDoc.SelectSingleNode("Settings") as XmlElement; EncryptedXml encXml = new EncryptedXml(xmlDoc); byte[] encryptedOrder = encXml.EncryptData(orderElem, encryptionKey, false); EncryptedData encryptedData = new EncryptedData(); encryptedData.Type = EncryptedXml.XmlEncElementUrl; encryptedData.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl); encryptedData.CipherData = new CipherData(); encryptedData.CipherData.CipherValue = encryptedOrder; EncryptedXml.ReplaceElement(orderElem, encryptedData, false); xmlDoc.Save(xmlFileName); }
// The elementName is the tag name for the element. // The elementIndex is the occurrence of the tag (minus 1). private static void doEncryptXml(XmlDocument xmlDoc, string elementName, int elementIndex) { // Check the arguments. if (xmlDoc == null) { throw new ArgumentNullException("xmlDoc"); } if (elementName == null) { throw new ArgumentNullException("elementName"); } //////////////////////////////////////////////// // Find the specified element in the XmlDocument // object and create a new XmlElement object. //////////////////////////////////////////////// XmlElement elementToEncrypt = xmlDoc.GetElementsByTagName(elementName)[elementIndex] as XmlElement; // Throw an XmlException if the element was not found. if (elementToEncrypt == null) { throw new XmlException("The specified element was not found"); } //////////////////////////////////////////////// // Set up the algorithm //////////////////////////////////////////////// string key = m_key; byte[] keyArray; keyArray = UTF8Encoding.UTF8.GetBytes(key); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); //set the secret key for the tripleDES algorithm tdes.Key = keyArray; //mode of operation. there are other 4 modes. //We choose ECB(Electronic code Book) tdes.Mode = CipherMode.ECB; //padding mode(if any extra byte added) tdes.Padding = PaddingMode.PKCS7; ////////////////////////////////////////////////// // Create a new instance of the EncryptedXml class // and use it to encrypt the XmlElement with the // symmetric key. // The false argument means encrypt the entire // element; true means to encrypt just the content. ////////////////////////////////////////////////// EncryptedXml eXml = new EncryptedXml(); byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, tdes, 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. // Determine what kind of algorithm is being used and // supply the appropriate URL to the EncryptionMethod element. // NLT modified the original code to just use Triple DES. string encryptionMethod = EncryptedXml.XmlEncTripleDESUrl; edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod); // 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); }