public void Decrypt(X509Certificate2 certificate, bool useFakeKeyName) { if (useFakeKeyName) { KeyInfoName keyInfoName = new KeyInfoName(kkKey); XmlNodeList encryptedKeyNodes = docValue.GetElementsByTagName("EncryptedKey"); XmlNode encryptedKeyNode = encryptedKeyNodes.Item(0); XmlNode referenceNode = encryptedKeyNode.FirstChild; XmlElement infoElement = docValue.CreateElement(null, "KeyInfo", "http://www.w3.org/2000/09/xmldsig#"); XmlElement keyNameElement = docValue.CreateElement(null, "KeyName", "http://www.w3.org/2000/09/xmldsig#"); keyNameElement.InnerText = kkKey; infoElement.AppendChild(keyNameElement); encryptedKeyNode.InsertAfter(infoElement, referenceNode); encryptedKeyNode.ParentNode.AppendChild(encryptedKeyNode); } EncryptedXml exml = new EncryptedXml(docValue); RSACryptoServiceProvider privateKeyProvider = (RSACryptoServiceProvider)certificate.PrivateKey; exml.AddKeyNameMapping(kkKey, privateKeyProvider); exml.DecryptDocument(); }
public void KeyInfoName() { KeyInfoName name = new KeyInfoName(); name.Value = "Mono::"; info.AddClause(name); Assert.AreEqual("<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><KeyName>Mono::</KeyName></KeyInfo>", (info.GetXml().OuterXml), "name"); Assert.AreEqual(1, info.Count, "name count"); }
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 void InvalidValue1() { string bad = "<Test></Test>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(bad); KeyInfoName name = new KeyInfoName(); name.LoadXml(null); }
public void InvalidValue1() { string bad = "<Test></Test>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(bad); KeyInfoName name = new KeyInfoName(); Assert.Throws <ArgumentNullException>(() => name.LoadXml(null)); }
public void InvalidValue2() { string bad = "<Test></Test>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(bad); KeyInfoName name = new KeyInfoName(); name.LoadXml(doc.DocumentElement); Assert.Equal("", name.Value); Assert.Equal("<KeyName xmlns=\"http://www.w3.org/2000/09/xmldsig#\"></KeyName>", (name.GetXml().OuterXml)); }
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); Assert.Equal("Mono::", name.Value); Assert.Equal(value, 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); } } } }
/// <summary> /// Verschlüsseung eines XML Dokumentes /// </summary> /// <param name="doc">zu verschlüsselndes XML Dokument</param> /// <param name="xmlElementToEncrypt">Knoten im XML Dokument der für die Verschlüsselung betrachtet werden soll</param> /// <param name="nurknotenInhaltVerschluesseln">Soll nur der Inhalt (true) oder auch der Knoten selbst verschlüsselt werden (false)</param> /// <param name="aesAlgo">Algorithmus für die AES Verschlüsselung</param> /// <param name="useOAEP">Verwendung vom optimalen asymmetrischen Verschlüsselungs Padding</param> /// <param name="rsaAlgo">Algorithmus für die RSA Verschlüsselung</param> /// <param name="keyStore">KeyStore der für die Verschlüsselung herangezogen werden soll</param> /// <param name="keyStorePasswort">Passwort zum KeyStore</param> private static void EncryptXML(XmlDocument doc, string xmlElementToEncrypt, bool nurknotenInhaltVerschluesseln, string aesAlgo, bool useOAEP, string rsaAlgo, X509Certificate certEncryptInfo) { //Heranziehen des öffentlichen Schlüssels: RSACryptoServiceProvider publicKeyProvider = KeyHelper.ConvertAsymmetricKeyParameterToRSACryptoServiceProvider(certEncryptInfo.GetPublicKey()); SymmetricAlgorithm aesAlgorithmus = SymmetricAlgorithm.Create(aesAlgo); //Definition des symmetrischen Verschlüsselungsverfahren: XmlElement elementToEncrypt = doc.GetElementsByTagName(xmlElementToEncrypt)[0] as XmlElement; RijndaelManaged sessionKey = new RijndaelManaged(); sessionKey.KeySize = aesAlgorithmus.KeySize; //Asymmetrische Verschlüsselung des symmetrischen Schlüssels und der Daten: EncryptedXml eXml = new EncryptedXml(); byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, nurknotenInhaltVerschluesseln); //byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, symalgorithmus, nurknotenInhaltVerschluesseln); //byte[] encryptedKey = EncryptedXml.EncryptKey(sessionKey.Key, publicKeyProvider, useOAEP); //TODO: useOAEP aus Algorithmus entnehmen!!!!! byte[] encryptedKey = EncryptedXml.EncryptKey(sessionKey.Key, publicKeyProvider, useOAEP); //Aufbereitung des verschlüsselten XMLs: EncryptedData edElement = new EncryptedData(); edElement.Type = EncryptedXml.XmlEncNamespaceUrl; edElement.EncryptionMethod = new EncryptionMethod(/*GetEncryptionAlgorithmusValue(*/ aesAlgo /*)*/); EncryptedKey ek = new EncryptedKey(); ek.CipherData = new CipherData(encryptedKey); ek.EncryptionMethod = new EncryptionMethod(/*GetEncryptionAlgorithmusValue(*/ rsaAlgo /*)*/); edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek)); //Zur Java Kompatibilität: KeyInfoName kin = new KeyInfoName(); kin.Value = "rsaKeyName"; ek.KeyInfo.AddClause(kin); edElement.CipherData.CipherValue = encryptedElement; EncryptedXml.ReplaceElement(elementToEncrypt, edElement, nurknotenInhaltVerschluesseln); }
private EncryptedData EncryptBody(X509Certificate2 cert, XmlElement elementToEncrypt) { Algorithm keyEncryptionAlgorithm = _soapEnvelopeConfiguration.ApplyElement(Direction.Outgoing, Usage.KeyEncryption).Algorithm; Algorithm contentEncryptionAlgorithm = _soapEnvelopeConfiguration.ApplyElement(Direction.Outgoing, Usage.ContentEncryption).Algorithm; if (keyEncryptionAlgorithm != Algorithm.XmlEncRSA15Url && keyEncryptionAlgorithm != Algorithm.XmlEncRSAOAEPUrl) { throw new InvalidOperationException(string.Format("Key encryption: \"{0}\" not supported, at this time only \"XmlEncRSA15Url\" and \"XmlEncRSAOAEPUrl\" are supported", keyEncryptionAlgorithm)); } if (contentEncryptionAlgorithm != Algorithm.XmlEncTripleDESUrl) { throw new InvalidOperationException(string.Format("Content encryption: \"{0}\" not supported, at this time only \"XmlEncTripleDESUrl\" is supported", contentEncryptionAlgorithm)); } var publicKeyProvider = (RSACryptoServiceProvider)cert.PublicKey.Key; var sessionKey = TripleDES.Create(); EncryptedXml eXml = new EncryptedXml(); byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, false); EncryptedData edElement = new EncryptedData(); edElement.Type = EncryptedXml.XmlEncElementContentUrl; edElement.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl); // Calculate encrypted key EncryptedKey ek = new EncryptedKey(); bool useOaep; ek.EncryptionMethod = CalculateEncryptedKey(keyEncryptionAlgorithm, out useOaep); byte[] encryptedKey = EncryptedXml.EncryptKey(sessionKey.Key, publicKeyProvider, useOaep); ek.CipherData = new CipherData(encryptedKey); // Create a new KeyInfo element. edElement.KeyInfo = new KeyInfo(); edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek)); edElement.KeyInfo.AddClause(new KeyInfoX509Data(cert)); // Add the encrypted element data to the // EncryptedData object. edElement.CipherData.CipherValue = encryptedElement; KeyInfoName kin = new KeyInfoName(); ek.KeyInfo.AddClause(kin); return(edElement); }
public void Complex() { KeyInfoName name = new KeyInfoName(); name.Value = "CoreFx::"; info.AddClause(name); using (DSA keyDSA = DSA.Create()) { keyDSA.ImportParameters(new DSAParameters { P = Convert.FromBase64String(dsaP), Q = Convert.FromBase64String(dsaQ), G = Convert.FromBase64String(dsaG), Y = Convert.FromBase64String(dsaY), }); DSAKeyValue dsa = new DSAKeyValue(keyDSA); info.AddClause(dsa); using (RSA keyRSA = RSA.Create()) { keyRSA.ImportParameters(new RSAParameters() { Modulus = Convert.FromBase64String(rsaModulus), Exponent = Convert.FromBase64String(rsaExponent) }); RSAKeyValue rsa = new RSAKeyValue(keyRSA); info.AddClause(rsa); KeyInfoRetrievalMethod retrieval = new KeyInfoRetrievalMethod(); retrieval.Uri = "https://github.com/dotnet/corefx"; info.AddClause(retrieval); using (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>CoreFx::</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></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>"; s += "<RetrievalMethod URI=\"https://github.com/dotnet/corefx\" />"; 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)); Assert.Equal(5, info.Count); } } } }
public static bool EncryptXmlNode( XmlElement elementToEncrypt, bool bContent, RSA rsaKey, String keyName, SymmetricAlgorithm sessionKey) { if (null == elementToEncrypt || null == rsaKey) { return(false); } try { EncryptedXml eXml = new EncryptedXml(); byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, bContent); EncryptedData edElement = new EncryptedData(); edElement.Type = EncryptedXml.XmlEncElementUrl; edElement.EncryptionMethod = CreateEncryptionMethod(sessionKey, false, false); EncryptedKey ek = new EncryptedKey(); byte[] encryptedKey = EncryptedXml.EncryptKey(sessionKey.Key, rsaKey, false); ek.CipherData = new CipherData(encryptedKey); ek.EncryptionMethod = CreateEncryptionMethod(rsaKey, false, false); if (null != keyName && !keyName.Equals(String.Empty)) { edElement.KeyInfo = new KeyInfo(); KeyInfoName kin = new KeyInfoName(); kin.Value = keyName; ek.KeyInfo.AddClause(kin); } edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek)); edElement.CipherData.CipherValue = encryptedElement; EncryptedXml.ReplaceElement(elementToEncrypt, edElement, bContent); return(true); } catch (System.Exception ex) { } return(false); }
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()); }
//加密 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(); } }
public void NewKeyValue() { string newKeyValue = "Mono::"; KeyInfoName name1 = new KeyInfoName(); name1.Value = newKeyValue; XmlElement xel = name1.GetXml(); KeyInfoName name2 = new KeyInfoName(); name2.LoadXml(xel); Assert.Equal(newKeyValue, name1.Value); Assert.Equal((name1.GetXml().OuterXml), (name2.GetXml().OuterXml)); }
/// <summary> /// Encrypts the specified x document. /// </summary> /// <param name="xDoc">The x document.</param> /// <param name="elementToEncrypt">The element to encrypt.</param> /// <param name="method">The method.</param> /// <param name="algo">The algo.</param> /// <param name="keyName">Name of the key.</param> /// <returns></returns> public static XmlDocument Encrypt(ref XmlDocument xDoc, XmlElement elementToEncrypt, string method, RSA algo, string keyName) { var sessionKey = new RijndaelManaged() { KeySize = 256 }; try { var docCopy = (XmlDocument)xDoc.Clone(); docCopy.PreserveWhitespace = xDoc.PreserveWhitespace; var eXml = new EncryptedXml(); var encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, false); var ek = new EncryptedKey(); var encryptedKey = EncryptedXml.EncryptKey(sessionKey.Key, algo, false); ek.CipherData = new CipherData(encryptedKey); ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); var edElement = new EncryptedData() { Type = EncryptedXml.XmlEncElementUrl, EncryptionMethod = new EncryptionMethod(method), KeyInfo = new KeyInfo() }; var kin = new KeyInfoName(keyName); ek.KeyInfo.AddClause(kin); edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek)); 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); } finally { sessionKey.Clear(); } }
private EncryptedData EncryptElement(X509Certificate2 cert, XmlElement elementToEncrypt) { /* * This constructs a symmetric key with which the data is encrypted * This encryption key is then encrypted itself under the public key of the recipient * The encrypted symmetric key is then attached to the document */ // Create a new 3des instance (This automaticly creates a non-weak 3des key) var tripleDesAlgo = TripleDES.Create(); EncryptedXml xmlCryptoUtil = new EncryptedXml(); // Create a new EncryptedData element for the xml document EncryptedData edElement = new EncryptedData(); // Set type and crypto method (So recipient will know how to decrypt it) edElement.Type = EncryptedXml.XmlEncElementContentUrl; edElement.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl); // Encrypt the element byte[] encryptedElement = xmlCryptoUtil.EncryptData(elementToEncrypt, tripleDesAlgo, false); // Add the encrypted element data to the // EncryptedData object. edElement.CipherData.CipherValue = encryptedElement; #region Encryption of symmetric key EncryptedKey ek = new EncryptedKey(); // Specify key encryption method and encrypt under recipient public key ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); byte[] encryptedKey = EncryptedXml.EncryptKey(tripleDesAlgo.Key, (RSACryptoServiceProvider)cert.PublicKey.Key, false); ek.CipherData = new CipherData(encryptedKey); KeyInfoName kin = new KeyInfoName(); ek.KeyInfo.AddClause(kin); // Add a new KeyInfo element to the encrypted data element. edElement.KeyInfo = new KeyInfo(); edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek)); edElement.KeyInfo.AddClause(new KeyInfoX509Data(cert)); #endregion return(edElement); }
public static void Encrypt(XmlDocument Doc, string ElementToEncrypt, string EncryptionElementID, RSA Alg, string KeyName) { XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementToEncrypt)[0] as XmlElement; if (elementToEncrypt == null) { throw new XmlException("The specified element was not found"); } RijndaelManaged sessionKey = null; try { 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; 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) { throw e; } finally { if (sessionKey != null) { sessionKey.Clear(); } } }
public static void SaveAsXmlEncrypted(T data, TextWriter outStream, RSA rsaKey) { XmlDocument xmlDoc = GetXmlDocumentClearText(data); XmlElement elementToEncrypt = xmlDoc.DocumentElement; Rijndael sessionKey = null; // Create a 256 bit Rijndael key. 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; edElement.Id = elementToEncrypt.Name; edElement.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url); EncryptedKey ek = new EncryptedKey(); byte[] encryptedKey = EncryptedXml.EncryptKey(sessionKey.Key, rsaKey, false); ek.CipherData = new CipherData(encryptedKey); ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek)); KeyInfoName kin = new KeyInfoName(); kin.Value = "rsaKey"; ek.KeyInfo.AddClause(kin); edElement.CipherData.CipherValue = encryptedElement; EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false); xmlDoc.Save(outStream); }
static void DumpKeyInfoClause(KeyInfoClause kic) { KeyInfoName kn = kic as KeyInfoName; if (kn != null) { Console.WriteLine("*** KeyInfoName ***"); Console.WriteLine("Value: " + kn.Value); return; } KeyInfoX509Data k509 = kic as KeyInfoX509Data; if (k509 != null) { Console.WriteLine("*** KeyInfoX509Data ***"); Console.WriteLine("Certificates : " + k509.Certificates); Console.WriteLine("CRL : " + k509.CRL); Console.WriteLine("IssuerSerials : " + k509.IssuerSerials); Console.WriteLine("SubjectKeyIds : " + k509.SubjectKeyIds); Console.WriteLine("SubjectNames : " + k509.SubjectNames); return; } }
/// <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); }
/// <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); }
/// <summary> /// Método para criptografia /// </summary> /// <param name="doc">XML documento</param> /// <param name="tagToEncrypt">Tag para criptografia</param> /// <param name="encryptionElementId">Tag de identificação da criptografia</param> /// <param name="alg">RSA</param> /// <param name="keyName">chave para criptografia</param> public static void Encrypt(XmlDocument doc, string tagToEncrypt, string encryptionElementId, RSA alg, string keyName) { if (doc == null) { throw new ArgumentNullException("doc"); } if (tagToEncrypt == 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(tagToEncrypt)[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) { // re-throw the exception. throw e; } finally { if (sessionKey != null) { sessionKey.Clear(); } } }
// Зашифрование узла 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); } }
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); }
public static XmlElement GetSignature(XmlDocument document, X509Certificate2 cert, string elementToSignId) { SignedXml signedXml = new SignedXml(document) { SigningKey = cert.PrivateKey }; signedXml.SigningKey = cert.PrivateKey; // Create a reference to be signed. Reference reference = new Reference() { Uri = elementToSignId }; // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(true); reference.AddTransform(env); //canonicalize XmlDsigC14NTransform c14t = new XmlDsigC14NTransform(); reference.AddTransform(c14t); //Key Info KeyInfoName kin = new KeyInfoName() { Value = cert.Subject }; //RSA Key Provider // RSACryptoServiceProvider rsaprovider = (RSACryptoServiceProvider)cert.PublicKey.Key; // RSAKeyValue rkv = new RSAKeyValue(rsaprovider); //System.Security.Cryptography..X509IssuerSerial xserial; //xserial.IssuerName = cert.IssuerName.Name; //xserial.SerialNumber = cert.SerialNumber; KeyInfo keyInfo = new KeyInfo(); KeyInfoX509Data keyInfoData = new KeyInfoX509Data(cert); //keyInfo.AddClause(new KeyInfoX509Data(cert)); keyInfoData.AddIssuerSerial(cert.IssuerName.Name, cert.SerialNumber); keyInfo.AddClause(keyInfoData); keyInfo.AddClause(kin); //keyInfo.AddClause(rkv); // Add the KeyInfo object to the SignedXml object. keyInfo.AddClause(new RSAKeyValue((RSA)cert.PrivateKey)); signedXml.KeyInfo = keyInfo; // Add the reference to the SignedXml object. signedXml.AddReference(reference); // Compute the signature. signedXml.ComputeSignature(); // Get the XML representation of the signature and save it to an XmlElement object. XmlElement xmlDigitalSignature = signedXml.GetXml(); return(xmlDigitalSignature); }
//tutorial - https://www.asptricks.net/2015/09/sign-xmldocument-with-x509certificate2.html internal static XmlDocument GetSignedXMLDocument(XmlDocument xmlDocument, X509Certificate2 certificate, long procedureSerial = -1, string reason = "") { //Before signing, should check if current document sign is valid or not, if current document is invalid, then new sign should not be added - not implemented yet, but should be if (CheckIfDocumentPreviouslySigned(xmlDocument)) { bool?isLastSignVerified = VerifyLastSign(xmlDocument); if (isLastSignVerified == false) { MessageBox.Show("The file was TEMPERED after last sign !!"); return(null); //Last Sign Not Verified } } //Then sign the xml try { //MessageBox.Show(certificate.Subject); SignedXml signedXml = new SignedXml(xmlDocument); signedXml.SigningKey = certificate.PrivateKey; // Create a reference to be signed Reference reference = new Reference(); ///////////////////// reference.Uri = ""; //"#" + procedureSerial; //reference.Type = reason; //reference.Id = DateTime.UtcNow.Ticks.ToString(); Tsa tsa = new Tsa(); string signedTsaString = tsa.GetSignedHashFromTsa(xmlDocument); DateTime?tsaTime = Tsa.GetTsaTimeFromSignedHash(signedTsaString); //reference.Id = Base64EncodedCurrentTime(tsaTime); reference.Id = signedTsaString; //bool status = Tsa.ValidateTimestamp(xmlDocument, reference.Id); //reference.TransformChain = ; ///////////////////// // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(true); reference.AddTransform(env); // Add the reference to the SignedXml object. signedXml.AddReference(reference); //canonicalize XmlDsigC14NTransform c14t = new XmlDsigC14NTransform(); reference.AddTransform(c14t); KeyInfo keyInfo = new KeyInfo(); KeyInfoX509Data keyInfoData = new KeyInfoX509Data(certificate); KeyInfoName kin = new KeyInfoName(); //kin.Value = "Public key of certificate"; kin.Value = certificate.FriendlyName; RSA rsa = (RSA)certificate.PublicKey.Key; RSAKeyValue rkv = new RSAKeyValue(rsa); keyInfo.AddClause(rkv); keyInfo.AddClause(kin); keyInfo.AddClause(keyInfoData); signedXml.KeyInfo = keyInfo; //////////////////////////////////////////Add Other Data as we need//// // Add the data object to the signature. //CreateMetaDataObject("Name", GetNetworkTime()); signedXml.AddObject(CreateMetaDataObject(procedureSerial, reason)); /////////////////////////////////////////////////////////////////////// // Compute the signature. signedXml.ComputeSignature(); // Get the XML representation of the signature and save // it to an XmlElement object. XmlElement xmlDigitalSignature = signedXml.GetXml(); xmlDocument.DocumentElement.AppendChild( xmlDocument.ImportNode(xmlDigitalSignature, true) ); ///////////////////// } catch (Exception exception) { MessageBox.Show("Internal System Error during sign"); throw exception; } return(xmlDocument); }
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); }
public string Encrypt(string xmlDocument, RSA rsaKey) { var xml = new XmlDocument { PreserveWhitespace = true }; xml.LoadXml(xmlDocument); var elementToEncrypt = (XmlElement)xml.GetElementsByTagName(xml.DocumentElement.Name)[0]; SymmetricAlgorithm sessionKey = null; try { sessionKey = new RijndaelManaged { KeySize = 256 }; // sessionKey = new TripleDESCryptoServiceProvider(); // Create a new instance of the EncryptedXml class and use it to encrypt the XmlElement with the a new random symmetric key. var encryptedXml = new EncryptedXml(); var encryptedElement = encryptedXml.EncryptData(elementToEncrypt, sessionKey, false); // Construct an EncryptedData object and populate it with the desired encryption information. var encryptedData = new EncryptedData { Type = EncryptedXml.XmlEncElementUrl, //EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl), EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url) }; // Create an EncryptionMethod element so that the receiver knows which algorithm to use for decryption. // Encrypt the session key and add it to an EncryptedKey element. var encryptedKey = new EncryptedKey(); var keyEncrypted = EncryptedXml.EncryptKey(sessionKey.Key, rsaKey, false); encryptedKey.CipherData = new CipherData(keyEncrypted); encryptedKey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); encryptedKey.Recipient = $"name:{KeyName}"; // Add the encrypted key to the EncryptedData object. encryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedKey)); // Set the KeyInfo element to specify the name of the RSA key. var keyInfoName = new KeyInfoName { Value = KeyName }; encryptedKey.KeyInfo.AddClause(keyInfoName); // Add the encrypted element data to the EncryptedData object. encryptedData.CipherData.CipherValue = encryptedElement; // Replace the element from the original XmlDocument object with the EncryptedData element. EncryptedXml.ReplaceElement(elementToEncrypt, encryptedData, false); //var prefixXmlnsXenc = "xenc"; //var xmlnsXenc = "http://www.w3.org/2001/04/xmlenc#"; //var xmlWithPrefix = new XmlDocument { PreserveWhitespace = true }; //var xElement = XElement.Parse(xml.OuterXml); //var xmlElement = xmlWithPrefix.CreateElement(prefixXmlnsXenc, xElement.Name.LocalName, xmlnsXenc); //AddAttributesToElement(xmlElement, xElement); //ProcessElement(xmlWithPrefix, xElement.Elements(), xmlElement); //xmlWithPrefix.AppendChild(xmlElement); //return xmlWithPrefix.OuterXml; return(xml.OuterXml); } catch (Exception e) { throw e; } finally { sessionKey?.Clear(); } }
/// <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); }