public Stream Decrypt(EncryptionMethod encryptionMethod, KeyInfo keyInfo, Stream toDecrypt) { Assert.NotNull(encryptionMethod); Assert.NotNull(keyInfo); Assert.NotNull(toDecrypt); Assert.True(encryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncAES128Url || encryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncAES192Url || encryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncAES256Url); Assert.Equal(keyInfo.Count, 1); byte[] decryptedKey = null; foreach (KeyInfoClause clause in keyInfo) { if (clause is KeyInfoEncryptedKey) { KeyInfoEncryptedKey encryptedKeyInfo = clause as KeyInfoEncryptedKey; EncryptedKey encryptedKey = encryptedKeyInfo.EncryptedKey; Assert.Equal(encryptedKey.EncryptionMethod.KeyAlgorithm, EncryptedXml.XmlEncRSAOAEPUrl); Assert.Equal(encryptedKey.KeyInfo.Count, 1); Assert.NotEqual(_asymmetricKeys.Count, 0); RSAParameters rsaParams = new RSAParameters(); RSAParameters rsaInputParams = new RSAParameters(); foreach (KeyInfoClause rsa in encryptedKey.KeyInfo) { if (rsa is RSAKeyValue) { rsaParams = (rsa as RSAKeyValue).Key.ExportParameters(false); break; } else { Assert.True(false, "Invalid License - MalformedKeyInfoClause"); } } bool keyMismatch = true; foreach (AsymmetricAlgorithm key in _asymmetricKeys) { RSA rsaKey = key as RSA; Assert.NotNull(rsaKey); rsaInputParams = rsaKey.ExportParameters(false); if (!PublicKeysEqual(rsaParams, rsaInputParams)) { continue; } keyMismatch = false; // Decrypt session key byte[] encryptedKeyValue = encryptedKey.CipherData.CipherValue; if (encryptedKeyValue == null) { throw new CryptographicException("MissingKeyCipher"); } decryptedKey = EncryptedXml.DecryptKey(encryptedKeyValue, rsaKey, true); break; } if (keyMismatch) { throw new Exception("Invalid License - AsymmetricKeyMismatch"); } } else if (clause is KeyInfoName) { Assert.True(false, "This test should not have KeyInfoName clauses"); } else { throw new CryptographicException("MalformedKeyInfoClause"); } break; } if (decryptedKey == null) { throw new CryptographicException("KeyDecryptionFailure"); } using (Aes aes = Aes.Create()) { aes.Key = decryptedKey; aes.Padding = PaddingMode.PKCS7; aes.Mode = CipherMode.CBC; return(DecryptStream(toDecrypt, aes)); } }
/// <summary> /// An example on how to decrypt an encrypted assertion. /// </summary> private static void DecryptAssertion(string file) { XmlDocument doc = new XmlDocument(); doc.Load(file); XmlElement encryptedDataElement = GetElement(dk.nita.saml20.Schema.XEnc.EncryptedData.ELEMENT_NAME, Saml20Constants.XENC, doc); EncryptedData encryptedData = new EncryptedData(); encryptedData.LoadXml(encryptedDataElement); XmlNodeList nodelist = doc.GetElementsByTagName(dk.nita.saml20.Schema.XmlDSig.KeyInfo.ELEMENT_NAME, Saml20Constants.XMLDSIG); Assert.That(nodelist.Count > 0); KeyInfo key = new KeyInfo(); key.LoadXml((XmlElement)nodelist[0]); // Review: Is it possible to figure out which certificate to load based on the Token? /* * Comment: * It would be possible to provide a key/certificate identifier in the EncryptedKey element, which contains the "recipient" attribute. * The implementation (Safewhere.Tokens.Saml20.Saml20EncryptedAssertion) currently just expects an appropriate asymmetric key to be provided, * and is not not concerned about its origin. * If the need arises, we can easily extend the Saml20EncryptedAssertion class with a property that allows extraction key info, eg. the "recipient" * attribute. */ X509Certificate2 cert = new X509Certificate2(@"Saml20\Certificates\sts_dev_certificate.pfx", "test1234"); // ms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.NETDEVFX.v20.en/CPref18/html/T_System_Security_Cryptography_Xml_KeyInfoClause_DerivedTypes.htm // Look through the list of KeyInfo elements to find the encrypted key. SymmetricAlgorithm symmetricKey = null; foreach (KeyInfoClause keyInfoClause in key) { if (keyInfoClause is KeyInfoEncryptedKey) { KeyInfoEncryptedKey keyInfoEncryptedKey = (KeyInfoEncryptedKey)keyInfoClause; EncryptedKey encryptedKey = keyInfoEncryptedKey.EncryptedKey; symmetricKey = new RijndaelManaged(); symmetricKey.Key = EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (RSA)cert.PrivateKey, false); continue; } } // Explode if we didn't manage to find a viable key. Assert.IsNotNull(symmetricKey); EncryptedXml encryptedXml = new EncryptedXml(); byte[] plaintext = encryptedXml.DecryptData(encryptedData, symmetricKey); XmlDocument assertion = new XmlDocument(); assertion.Load(new StringReader(System.Text.Encoding.UTF8.GetString(plaintext))); // A very simple test to ensure that there is indeed an assertion in the plaintext. Assert.AreEqual(Assertion.ELEMENT_NAME, assertion.DocumentElement.LocalName); Assert.AreEqual(Saml20Constants.ASSERTION, assertion.DocumentElement.NamespaceURI); }
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); }
// Зашифрование узла 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); } }
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); }
private byte[] DecryptSessionKey(EncryptedKey encryptedKey) { // Get RSA Key RSA key = (RSA)_keyMappings[encryptedKey.KeyInfo.KeyName]; // Import key CspParameters CSPParam = new CspParameters(); CSPParam.Flags = CspProviderFlags.UseMachineKeyStore; RSACryptoServiceProvider crypto = new RSACryptoServiceProvider(CSPParam); crypto.ImportParameters(key.ExportParameters(true)); // Create session key RijndaelManaged sessionKey = new RijndaelManaged(); sessionKey.KeySize = 256; // Encrypt the symmetric key and IV (session key encryption). byte[] symmetricKey = crypto.Decrypt(Convert.FromBase64String(encryptedKey.CipherData.CipherValue), false); return symmetricKey; }
public PkiArchiveOptions(EncryptedKey encKey) { value = encKey; }
/** * 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 void Encrypt(string ElementToEncrypt) { // Check the arguments. if (xmlDoc == null) { throw new ArgumentNullException("Doc"); } if (ElementToEncrypt == null) { throw new ArgumentNullException("ElementToEncrypt"); } if (rsaKey == null) { throw new ArgumentNullException("Alg"); } 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(); for (int index = 0; xmlDoc.GetElementsByTagName(ElementToEncrypt).Count > 0; index++) { XmlElement elementToEncrypt = xmlDoc.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"); } 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 = "Encrypted" + ElementToEncrypt + index; // 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, rsaKey, 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 = "#" + "Encrypted" + ElementToEncrypt + index; // 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); } // Save the XML document. xmlDoc.Save(string.Format("{0}{1}{2}", path, CryptExtention, fileName)); } catch (Exception e) { // re-throw the exception. throw e; } finally { if (sessionKey != null) { sessionKey.Clear(); } } }
public KeyInfoEncryptedKey(EncryptedKey encryptedKey) {}
/// <summary> /// Creates a new KeyInfoEncryptedKey. /// </summary> /// <param name="encryptedKey"> The encrypted key.</param> public KeyInfoEncryptedKey(EncryptedKey encryptedKey) { _encryptedKey = encryptedKey; }
/// <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))); }
public void Encrypt(string Element, X509Certificate2 certificate, bool includeKey) { // Find the element by name and create a new // XmlElement object. XmlElement inputElement = docValue.GetElementsByTagName(Element)[0] as XmlElement; // If the element was not found, throw an exception. if (inputElement == null) { throw new Exception("The element was not found."); } // Create a new EncryptedXml object. EncryptedXml exml = new EncryptedXml(docValue); // Encrypt the element using the symmetric key. byte[] rgbOutput = exml.EncryptData(inputElement, tripleDES, false); // Create an EncryptedData object and populate it. EncryptedData ed = new EncryptedData(); // Specify the namespace URI for XML encryption elements. ed.Type = EncryptedXml.XmlEncElementUrl; // Specify the namespace URI for the TrippleDES algorithm. ed.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl); // Create a CipherData element. ed.CipherData = new CipherData(); // Set the CipherData element to the value of the encrypted XML element. ed.CipherData.CipherValue = rgbOutput; // Encrypt the session key and add it to an EncryptedKey element. EncryptedKey encryptedKey = new EncryptedKey(); RSACryptoServiceProvider publicKeyProvider = (RSACryptoServiceProvider)certificate.PublicKey.Key; byte[] encryptedKeyBytes = EncryptedXml.EncryptKey(tripleDES.Key, publicKeyProvider, false); encryptedKey.CipherData = new CipherData(encryptedKeyBytes); encryptedKey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); // Create a new KeyInfo element. ed.KeyInfo = new KeyInfo(); if (includeKey) { // Create a new KeyInfoName element. KeyInfoName keyInfoName = new KeyInfoName(kkKey); // Add the KeyInfoName element to the // EncryptedKey object. encryptedKey.KeyInfo.AddClause(keyInfoName); } KeyInfoX509Data keyInfoData = new KeyInfoX509Data(certificate); ed.KeyInfo.AddClause(keyInfoData); ed.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedKey)); // Replace the plaintext XML elemnt with an EncryptedData element. EncryptedXml.ReplaceElement(inputElement, ed, false); }
public void Decrypt(SecureString privatekey, string publickey) { if (!Security.Utils.IsBase64(privatekey)) { throw new ArgumentException($"{nameof(privatekey)} must be Base64-encoded string"); } if (!Security.Utils.IsBase64(publickey)) { throw new ArgumentException($"{nameof(publickey)} must be Base64-encoded string"); } using SecureString key = Security.Boxes.Asymmetric.Decrypt(EncryptedKey.Split(':')[1], privatekey, publickey, EncryptedKey.Split(':')[0]); Plaintext = Security.Boxes.Symmetric.Decrypt(EncryptedMessage, key, Nonce); }
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, 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(); } } }
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); }
/// <summary> /// Encrypts a list of elements. /// </summary> /// <param name="elementToAddEncKeysTo"></param> /// <param name="elementsToEncrypt"></param> /// <param name="certificates"></param> /// <param name="cipherKey"></param> public void Encrypt(XmlElement elementToAddEncKeysTo, IList <XmlElement> elementsToEncrypt, X509Certificate2Collection certificates, byte[] cipherKey) { ArgumentUtils.CheckNotNull(elementToAddEncKeysTo, "elementToAddEncKeysTo"); ArgumentUtils.CheckNotNullNorEmpty(elementsToEncrypt, "elementsToEncrypt"); CertificateUtils.CheckNotNullOrEmpty(certificates, "certificates"); // Check all the elements to encrypt are not the same as the element // to add the keys to and check they belong to the same document. foreach (XmlElement elementToEncrypt in elementsToEncrypt) { if (elementToEncrypt == elementToAddEncKeysTo) { throw new XspException( "Cannot add keys to an element that is being encrypted"); } if (elementToAddEncKeysTo.OwnerDocument != elementToEncrypt.OwnerDocument) { throw new XspException( "Elements to encrypt must belong to the same document as the " + "keys element"); } if (XmlUtils.IsDescendant(elementToEncrypt, elementToAddEncKeysTo)) { throw new XspException( "Element the keys are added to cannot be a child element of an " + "element to encrypt"); } } // Get the container document XmlDocument containerDoc = elementToAddEncKeysTo.OwnerDocument; // Create a random session key RijndaelManaged sessionKey = new RijndaelManaged(); sessionKey.KeySize = 256; if (cipherKey != null) { sessionKey.Key = cipherKey; } IList <string> referenceIdList = new List <string>(); foreach (XmlElement elementToEncrypt in elementsToEncrypt) { // Generate a unique reference identifier string referenceId = "_" + Guid.NewGuid().ToString(); // Add it to the reference list referenceIdList.Add(referenceId); // Create the encrypted data EncryptedData encryptedData = XmlSecurityUtils.Encrypt( sessionKey, elementToEncrypt, referenceId); // Replace the original element with the encrypted data EncryptedXml.ReplaceElement(elementToEncrypt, encryptedData, false); } foreach (X509Certificate2 certificate in certificates) { // Create the encrypted key EncryptedKey encryptedKey = XmlSecurityUtils.CreateEncryptedKey( sessionKey, certificate, referenceIdList); // Import the encrypted key element into the container document XmlNode encryptedKeyElem = containerDoc.ImportNode(encryptedKey.GetXml(), true); elementToAddEncKeysTo.AppendChild(encryptedKeyElem); } }
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); }
/// <summary> /// Decrypts a list of elements. /// </summary> /// <param name="encryptedKeyElems">List of encrypted key elements.</param> /// <param name="encryptedDataElems">List of encrypted data elements.</param> /// <param name="certificate">Certificate to use for key decryption.</param> public void Decrypt(IList <XmlElement> encryptedKeyElems, IList <XmlElement> encryptedDataElems, X509Certificate2 certificate) { ArgumentUtils.CheckNotNullNorEmpty(encryptedKeyElems, "encryptedKeyElems"); ArgumentUtils.CheckNotNullNorEmpty(encryptedDataElems, "encryptedDataElems"); ArgumentUtils.CheckNotNull(certificate, "certificate"); // Check the certificate has a private key if (certificate.PrivateKey == null) { throw new XspException("Certificate with subject '" + certificate.Subject + "' does not contain a private key"); } XmlDocument containerDoc = encryptedKeyElems[0].OwnerDocument; // Check the 'encryptedKeyElems' elements foreach (XmlElement encryptedKeyElem in encryptedKeyElems) { // Check they are all 'xenc:EncryptedKey' elements if (!XmlUtils.CheckElement(encryptedKeyElem, EncryptedKeyTag, EncryptedXml.XmlEncNamespaceUrl)) { throw new XspException("Element within the keys list is not " + "an 'xenc:EncryptedKey'"); } // Check they all belong to the same document if (encryptedKeyElem.OwnerDocument != containerDoc) { throw new XspException("All 'xenc:EncryptedKey' elements " + "must belong to the same document"); } } // Check the 'encryptedDataElems' elements foreach (XmlElement encryptedDataElem in encryptedDataElems) { // Check they are all 'xenc:EncryptedData' elements if (!XmlUtils.CheckElement(encryptedDataElem, EncryptedDataTag, EncryptedXml.XmlEncNamespaceUrl)) { throw new XspException("Element within the encrypted data list is " + "not an 'xenc:EncryptedData' element."); } // Check they all belong to the same document if (encryptedDataElem.OwnerDocument != containerDoc) { throw new XspException("All 'xenc:EncryptedData' elements " + "must belong to the same document"); } } // Attempt to find the matching encrypted key for the certificate EncryptedKey encryptedKey = null; foreach (XmlElement encryptedKeyElem in encryptedKeyElems) { EncryptedKey currentEncryptedKey = new EncryptedKey(); currentEncryptedKey.LoadXml(encryptedKeyElem); // Check if the subject key identifier specified within the // 'KeyInfo' of the encrypted key matches the certificate if (MatchesCertificate(currentEncryptedKey, certificate)) { encryptedKey = currentEncryptedKey; break; } } // Check if a key was found if (encryptedKey == null) { throw new KeyMismatchException( "Could not find a matching encrypted key for certificate '" + certificate.Subject + "'."); } // Decrypt the encrypted key RijndaelManaged sessionKey = new RijndaelManaged(); sessionKey.Key = XmlSecurityUtils.DecryptEncryptedKey( encryptedKey, certificate.PrivateKey); // Decrypt each of the encrypted data elements using the decrypted key foreach (XmlElement encryptedDataElem in encryptedDataElems) { // Decrypt the data byte[] decryptedData = XmlSecurityUtils.Decrypt( encryptedDataElem, sessionKey); // Replace the encrypted data with the decrypted data within the container EncryptedXml encryptedXml = new EncryptedXml(containerDoc); encryptedXml.ReplaceData(encryptedDataElem, decryptedData); } }
/// <summary> /// Decrypts an encrypted key. /// </summary> /// <param name="encryptedKey">Encrypted key to decrypt. Cannot be null. /// </param> /// <param name="privateKey">Private key that will be used to decrypt /// the encrypted key. Cannot be null.</param> /// <returns>Decrypted key.</returns> public static byte[] DecryptEncryptedKey(EncryptedKey encryptedKey, AsymmetricAlgorithm privateKey) { return(EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (RSA)privateKey, false)); }
/// <summary> /// Encrypts the NameID attribute of the AttributeQuery request. /// </summary> /// <param name="certValue"> /// Encoded X509 certificate retrieved from the identity provider's metadata /// and used to encrypt generated symmetric key. /// </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 certValue, string symmetricAlgorithmUri, XmlDocument xmlDoc) { if (string.IsNullOrWhiteSpace(certValue)) { throw new Saml2Exception(Resources.EncryptedXmlCertNotFound); } if (string.IsNullOrWhiteSpace(symmetricAlgorithmUri)) { throw new Saml2Exception(Resources.EncryptedXmlInvalidEncrAlgorithm); } if (xmlDoc == null) { throw new Saml2Exception(Resources.SignedXmlInvalidXml); } byte[] byteArray = Encoding.UTF8.GetBytes(certValue); X509Certificate2 cert = new X509Certificate2(byteArray); 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 virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey) {}
/// <summary> /// Creates an AS4EncryptedKey instance for the given <paramref name="encryptedKey"/> /// </summary> /// <remarks>This method should only be used for testing purposes.</remarks> /// <param name="encryptedKey"></param> /// <returns></returns> internal static AS4EncryptedKey FromEncryptedKey(EncryptedKey encryptedKey) { return(new AS4EncryptedKey(encryptedKey, null, EncryptionStrategy.XmlEncSHA1Url, null)); }
WrappedKeySecurityToken ReadWrappedKeySecurityTokenCore ( XmlReader reader, SecurityTokenResolver tokenResolver) { if (tokenResolver == null) throw new ArgumentNullException ("tokenResolver"); EncryptedKey ek = new EncryptedKey (); ek.LoadXml (new XmlDocument ().ReadNode (reader) as XmlElement); SecurityKeyIdentifier ki = new SecurityKeyIdentifier (); foreach (KeyInfoClause kic in ek.KeyInfo) ki.Add (ReadKeyIdentifierClause (new XmlNodeReader (kic.GetXml ()))); SecurityToken token = tokenResolver.ResolveToken (ki); string alg = ek.EncryptionMethod.KeyAlgorithm; foreach (SecurityKey skey in token.SecurityKeys) if (skey.IsSupportedAlgorithm (alg)) { byte [] key = skey.DecryptKey (alg, ek.CipherData.CipherValue); WrappedKeySecurityToken wk = new WrappedKeySecurityToken (ek.Id, key, alg, token, ki); // FIXME: This should not be required. wk.SetWrappedKey (ek.CipherData.CipherValue); wk.ReferenceList = ek.ReferenceList; return wk; } throw new InvalidOperationException (String.Format ("Cannot resolve security key with the resolved SecurityToken specified by the key identifier in the EncryptedKey XML. The key identifier is: {0}", ki)); }
public KeyInfoEncryptedKey(EncryptedKey encryptedKey) { }
public static void Encrypt(XmlDocument Doc, string ElementToEncrypt, string EncryptionElementID, RSA Alg, string KeyName) { // Check the arguments. if (Doc == null) { throw new ArgumentNullException("Doc"); } if (ElementToEncrypt == null) { throw new ArgumentNullException("ElementToEncrypt"); } if (EncryptionElementID == null) { throw new ArgumentNullException("EncryptionElementID"); } if (Alg == null) { throw new ArgumentNullException("Alg"); } if (KeyName == null) { throw new ArgumentNullException("KeyName"); } //////////////////////////////////////////////// // Find the specified element in the XmlDocument // object and create a new XmlElemnt object. //////////////////////////////////////////////// XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementToEncrypt)[0] as XmlElement; // Throw an XmlException if the element was not found. if (elementToEncrypt == null) { throw new XmlException("The specified element was not found"); } ////////////////////////////////////////////////// // 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; 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(); ek.Id = "keyID"; 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); // Create a new KeyReference object. // Use the uri of the encrypted key. KeyReference kryRef = new KeyReference("#keyID"); ek.AddReference(kryRef); // 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)); // 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 virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey) { }
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 ReadWrappedKeySecurityTokenImplCheck () { SecurityTokenResolver tokenResolver = GetResolver (new X509SecurityToken (cert)); XmlReader reader = XmlReader.Create (new StringReader (wrapped_key1)); WSSecurityTokenSerializer serializer = WSSecurityTokenSerializer.DefaultInstance; EncryptedKey ek = new EncryptedKey (); ek.LoadXml (new XmlDocument ().ReadNode (reader) as XmlElement); SecurityKeyIdentifier ki = new SecurityKeyIdentifier (); foreach (KeyInfoClause kic in ek.KeyInfo) ki.Add (serializer.ReadKeyIdentifierClause (new XmlNodeReader (kic.GetXml ()))); SecurityToken token = tokenResolver.ResolveToken (ki); string alg = ek.EncryptionMethod.KeyAlgorithm; SecurityKey skey = token.SecurityKeys [0]; Assert.IsTrue (skey is X509AsymmetricSecurityKey, "#1"); Assert.IsTrue (skey.IsSupportedAlgorithm (alg), "#2"); Assert.AreEqual ( EncryptedXml.DecryptKey (ek.CipherData.CipherValue, cert.PrivateKey as RSA, true), skey.DecryptKey (alg, ek.CipherData.CipherValue), "#3"); byte [] key = skey.DecryptKey (alg, ek.CipherData.CipherValue); WrappedKeySecurityToken wk = new WrappedKeySecurityToken (ek.Id, key, alg, token, ki); Assert.AreEqual ( EncryptedXml.DecryptKey (ek.CipherData.CipherValue, cert.PrivateKey as RSA, true), skey.DecryptKey (alg, wk.GetWrappedKey ()), "#4"); }
public Stream Decrypt(EncryptionMethod encryptionMethod, KeyInfo keyInfo, Stream toDecrypt) { Assert.NotNull(encryptionMethod); Assert.NotNull(keyInfo); Assert.NotNull(toDecrypt); Assert.True(encryptionMethod.KeyAlgorithm == NS.XmlEncAES128Url || encryptionMethod.KeyAlgorithm == NS.XmlEncAES192Url || encryptionMethod.KeyAlgorithm == NS.XmlEncAES256Url); Assert.Equal(keyInfo.Count, 1); byte[] decryptedKey = null; foreach (KeyInfoClause clause in keyInfo) { if (clause is KeyInfoEncryptedKey) { KeyInfoEncryptedKey encryptedKeyInfo = clause as KeyInfoEncryptedKey; EncryptedKey encryptedKey = encryptedKeyInfo.GetEncryptedKey(); Assert.Equal(encryptedKey.EncryptionMethod.KeyAlgorithm, NS.XmlEncRSAOAEPUrl); Assert.Equal(encryptedKey.KeyInfo.Count, 1); Assert.NotEqual(_asymmetricKeys.Count, 0); RsaKeyParameters rsaParams = null; RsaKeyParameters rsaInputParams = null; foreach (KeyInfoClause rsa in encryptedKey.KeyInfo) { if (rsa is RsaKeyValue) { rsaParams = (rsa as RsaKeyValue).GetKey(); break; } else { Assert.True(false, "Invalid License - MalformedKeyInfoClause"); } } bool keyMismatch = true; foreach (AsymmetricCipherKeyPair key in _asymmetricKeys) { RsaKeyParameters rsaKey = key.Private as RsaKeyParameters; Assert.NotNull(rsaKey); rsaInputParams = key.Public as RsaKeyParameters; Assert.NotNull(rsaInputParams); if (!PublicKeysEqual(rsaParams, rsaInputParams)) { continue; } keyMismatch = false; byte[] encryptedKeyValue = encryptedKey.CipherData.CipherValue; if (encryptedKeyValue == null) { throw new System.Security.Cryptography.CryptographicException("MissingKeyCipher"); } decryptedKey = XmlDecryption.DecryptKey(encryptedKeyValue, rsaKey, true); break; } if (keyMismatch) { throw new Exception("Invalid License - AsymmetricKeyMismatch"); } } else if (clause is KeyInfoName) { Assert.True(false, "This test should not have KeyInfoName clauses"); } else { throw new System.Security.Cryptography.CryptographicException("MalformedKeyInfoClause"); } break; } if (decryptedKey == null) { throw new System.Security.Cryptography.CryptographicException("KeyDecryptionFailure"); } return(DecryptStream(toDecrypt, new KeyParameter(decryptedKey), "AES/CBC/PKCS7")); }
internal static ICollection <SamlAttributesEncryptionKey> DecryptXml(RSA asymmetricAlgorithm, XmlDocument xmlDoc, string[] xmlElementsXPaths) { if (asymmetricAlgorithm == null) { throw new ArgumentNullException("asymmetricAlgorithm"); } if (xmlDoc == null) { throw new ArgumentNullException("xmlDoc"); } if (xmlElementsXPaths == null) { throw new ArgumentNullException("xmlElementsXPaths"); } // create the symmetric algorithm which was used for encryption var symmetricAlgorithm = new AesManaged(); symmetricAlgorithm.Padding = PaddingMode.ISO10126; ICollection <SamlAttributesEncryptionKey> attributesEncryptionKeys = new Collection <SamlAttributesEncryptionKey>(); foreach (var xPath in xmlElementsXPaths) { // select all encrypted attribute elements var encryptedElements = xmlDoc.SelectNodes(xPath); Debug.Assert(encryptedElements != null, "encryptedElements != null"); foreach (XmlNode encryptedElement in encryptedElements) { // load the encrypted data element var encryptedDataElement = encryptedElement.SelectSingleNode("//*[local-name() = 'EncryptedData']") as XmlElement; var encryptedData = new EncryptedData(); Debug.Assert(encryptedDataElement != null, "encryptedDataElement != null"); encryptedData.LoadXml(encryptedDataElement); // load the encrypted key element var encryptedKeyElement = encryptedDataElement.SelectSingleNode("//*[local-name() = 'EncryptedKey']") as XmlElement; var encryptedKey = new EncryptedKey(); Debug.Assert(encryptedKeyElement != null, "encryptedKeyElement != null"); encryptedKey.LoadXml(encryptedKeyElement); // decrypt the key using the specifief asymmetric algorithm var symetricKey = asymmetricAlgorithm.Decrypt(encryptedKey.CipherData.CipherValue, RSAEncryptionPadding.OaepSHA1); // use the asymmetric decrypted key to decrypt the encrypted data using the specified symmetric algorithm symmetricAlgorithm.Key = symetricKey; var output = new EncryptedXml { Mode = CipherMode.CBC, Padding = PaddingMode.ISO10126 }; var data = output.DecryptData(encryptedData, symmetricAlgorithm); var previousSibling = (XmlElement)encryptedElement.PreviousSibling; var nextSibling = (XmlElement)encryptedElement.NextSibling; var parentElement = (XmlElement)encryptedElement.ParentNode; // replace the encrypted element with its decrypted form output.ReplaceData((XmlElement)encryptedElement, data); var currentNode = previousSibling?.NextSibling ?? nextSibling?.PreviousSibling ?? parentElement?.FirstChild; if (currentNode == null) { continue; } var attributesEncryptionKey = GetAttributesEncryptionKey(currentNode, symetricKey); if (attributesEncryptionKey != null) { attributesEncryptionKeys.Add(attributesEncryptionKey); } } } return(attributesEncryptionKeys); }
/// <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 override byte[] DecryptEncryptedKey(EncryptedKey encryptedKey) { return(EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, DecryptionPrivateKey, (encryptedKey.EncryptionMethod != null) && (encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl))); }
/// <summary> /// Decrypts the encrypted key using a specified password. /// </summary> /// <param name="password">The password.</param> /// <returns>System.String.</returns> public string Decrypt(Password password) { return(CryptoUtils.PasswordToPrivateKey(password.Value, EncryptedKey.FromHex(), Iv.FromHex(), "pass:bip32")); }
/// <summary> /// Encryps the XML element. /// </summary> /// <param name="element"> The element to encrypt.</param> /// <param name="keyName"> The key name.</param> /// <returns> A EncryptedData type.</returns> public EncryptedData Encrypt(XmlElement element, string keyName) { // Get Key from key mappings RSA key = (RSA)_keyMappings[keyName]; // Import key RSACryptoServiceProvider crypto = new RSACryptoServiceProvider(); RSAParameters param = new RSAParameters(); crypto.ImportParameters(key.ExportParameters(false)); // Create session key RijndaelManaged sessionKey = new RijndaelManaged(); sessionKey.KeySize = 256; // Encrypt the symmetric key and IV (session key encryption). byte[] encryptedSymmetricKey = crypto.Encrypt(sessionKey.Key, false); //byte[] encryptedSymmetricIV = crypto.Encrypt(sessionKey.IV, false); // Create a new EncryptedKey EncryptedKey ek = new EncryptedKey(); ek.CipherData = new CipherData(encryptedSymmetricKey); ek.EncryptionMethod = new EncryptionMethod(EncryptXml.XmlEncRSA1_5Url); // set up a key info clause for the key that was used to encrypt the session key // KeyInfoName keyName = new KeyInfoName(); // keyName.Value = keyName; // TODO: KeyInfo.AddClause. ek.KeyInfo = new KeyInfo(keyName); byte[] encryptedData = EncryptData(element, sessionKey); // create the encrypted data EncryptedData ed = new EncryptedData(); ed.CipherData = new CipherData(encryptedData); //ed.Type = EncryptedXml.XmlEncElementUrl; ed.EncryptionMethod = new EncryptionMethod(EncryptXml.XmlEncAES256Url); ed.AddKeyInfoClause(new KeyInfoEncryptedKey(ek)); return ed; }