Как я мог бы читать и писать зашифрованные XML-файлы? Мне нужен способ сохранить последние введенные значения пользователя для формы, но я не хочу, чтобы они читались как обычный текст или XML.Как читать и писать зашифрованные XML-файлы?
0
A
ответ
6
Существует всеобъемлющий набор классов, доступных в вашем одноразовом для защиты данных XML в System.Security.Cryptography.Xml Namespace
.
Потратьте некоторое время, чтобы прочитать следующие статьи MSDN статьи:
- How to: Encrypt XML Elements with Symmetric Keys
- How to: Decrypt XML Elements with Symmetric Keys
- How to: Sign XML Documents with Digital Signatures
Если вы посетите корневой узел в навигационном меню на любой из статей, вы можете просмотреть другие статьи по безопасности XML.
+0
Спасибо, это очень полезно! – Jack
0
Я думаю, вы могли бы просто сохранить сохраненные строки пользователей, а затем написать обычный XML-файл с зашифрованными строками?
Вот пример из here
public class Crypto
{
private static byte[] _salt = Encoding.ASCII.GetBytes("o6806642kbM7c5");
/// <summary>
/// Encrypt the given string using AES. The string can be decrypted using
/// DecryptStringAES(). The sharedSecret parameters must match.
/// </summary>
/// <param name="plainText">The text to encrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for encryption.</param>
public static string EncryptStringAES(string plainText, string sharedSecret)
{
if (string.IsNullOrEmpty(plainText))
throw new ArgumentNullException("plainText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
string outStr = null; // Encrypted string to return
RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data.
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create a RijndaelManaged object
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize/8);
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
// prepend the IV
msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
}
outStr = Convert.ToBase64String(msEncrypt.ToArray());
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
// Return the encrypted bytes from the memory stream.
return outStr;
}
/// <summary>
/// Decrypt the given string. Assumes the string was encrypted using
/// EncryptStringAES(), using an identical sharedSecret.
/// </summary>
/// <param name="cipherText">The text to decrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for decryption.</param>
public static string DecryptStringAES(string cipherText, string sharedSecret)
{
if (string.IsNullOrEmpty(cipherText))
throw new ArgumentNullException("cipherText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret");
// Declare the RijndaelManaged object
// used to decrypt the data.
RijndaelManaged aesAlg = null;
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create the streams used for decryption.
byte[] bytes = Convert.FromBase64String(cipherText);
using (MemoryStream msDecrypt = new MemoryStream(bytes))
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize/8);
// Get the initialization vector from the encrypted stream
aesAlg.IV = ReadByteArray(msDecrypt);
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
}
return plaintext;
}
private static byte[] ReadByteArray(Stream s)
{
byte[] rawLength = new byte[sizeof(int)];
if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
{
throw new SystemException("Stream did not contain properly formatted byte array");
}
byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
{
throw new SystemException("Did not read byte array properly");
}
return buffer;
}
}
Смежные вопросы
- 1. Как читать и писать файл
- 2. Как читать и писать shared_ptr?
- 3. Как писать, читать и добавлять?
- 4. QProcess читать и писать
- 5. писать и читать peewee
- 6. Как писать зашифрованные данные приложения и дешифровать его
- 7. Как читать зашифрованные zip-файлы в Python
- 8. Учимся читать и писать рекурсивно
- 9. Kryo читать и писать вообще
- 10. PHP-файл читать и писать
- 11. Valgrind - недействительный читать и писать
- 12. PNG метаданные читать и писать
- 13. C# - NetworkStream читать и писать
- 14. PIC16F84 - eeprom читать и писать
- 15. файл Python читать и писать
- 16. Как читать и писать XML с Perl?
- 17. ReactJS: Как читать и писать в файл
- 18. Как читать и писать в TCPStream одновременно?
- 19. C# - Как читать и писать двоичный файл?
- 20. Как читать и писать файл в Phonegap?
- 21. Как читать и писать HashMap в файл?
- 22. Как читать и писать текст в файл
- 23. Как читать и писать одновременно с Excel?
- 24. VB - Как читать и писать двоичный файл?
- 25. Как читать и писать NSString с UTF8N?
- 26. Как читать и писать несколько файлов?
- 27. Как читать JSON и писать в Консоль
- 28. Как читать и писать существующие листы Excel?
- 29. Как читать и писать DataFrame из Spark
- 30. как писать и читать печатные ascii?
То же, что шифрование любого другого потока байтов. –
Не используйте для этого xml. – AntoineLev
Что я буду использовать для этого? – Jack