Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何读取和写入加密的XML文件?_C#_Xml_Winforms_Encryption - Fatal编程技术网

C# 如何读取和写入加密的XML文件?

C# 如何读取和写入加密的XML文件?,c#,xml,winforms,encryption,C#,Xml,Winforms,Encryption,如何读取和写入加密的XML文件?我需要一种方法来保存用户最后输入的表单值,但我不希望它们以纯文本或XML的形式可读。我想,您可以只保存用户保存的字符串,然后编写一个带有加密字符串的常规XML文件 这里有一个例子 公共类加密 { 私有静态字节[]_salt=Encoding.ASCII.GetBytes(“o6806642kbM7c5”); /// ///使用AES加密给定字符串。可以使用 ///DecryptStringAES()。sharedSecret参数必须匹配。 /// ///要加密

如何读取和写入加密的XML文件?我需要一种方法来保存用户最后输入的表单值,但我不希望它们以纯文本或XML的形式可读。

我想,您可以只保存用户保存的字符串,然后编写一个带有加密字符串的常规XML文件

这里有一个例子

公共类加密
{
私有静态字节[]_salt=Encoding.ASCII.GetBytes(“o6806642kbM7c5”);
/// 
///使用AES加密给定字符串。可以使用
///DecryptStringAES()。sharedSecret参数必须匹配。
/// 
///要加密的文本。
///用于生成加密密钥的密码。
公共静态字符串EncryptStringAES(字符串明文、字符串共享秘密)
{
if(string.IsNullOrEmpty(纯文本))
抛出新的ArgumentNullException(“明文”);
if(string.IsNullOrEmpty(sharedSecret))
抛出新ArgumentNullException(“sharedSecret”);
string outStr=null;//要返回的加密字符串
RijndaelManaged aesAlg=null;//用于加密数据的RijndaelManaged对象。
尝试
{
//从共享密钥和salt生成密钥
Rfc2898DeriveBytes键=新的Rfc2898DeriveBytes(sharedSecret,_salt);
//创建RijndaelManaged对象
aesAlg=新RijndaelManaged();
aesAlg.Key=Key.GetBytes(aesAlg.KeySize/8);
//创建decrytor以执行流变换。
ICryptoTransform encryptor=aesAlg.CreateEncryptor(aesAlg.Key,aesAlg.IV);
//创建用于加密的流。
使用(MemoryStream msEncrypt=new MemoryStream())
{
//准备静脉注射
msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length),0,sizeof(int));
msEncrypt.Write(aesAlg.IV,0,aesAlg.IV.Length);
使用(CryptoStream csEncrypt=new CryptoStream(msEncrypt,encryptor,CryptoStreamMode.Write))
{
使用(StreamWriter swEncrypt=newstreamwriter(csEncrypt))
{
//将所有数据写入流。
书写(纯文本);
}
}
outStr=Convert.ToBase64String(msEncrypt.ToArray());
}
}
最后
{
//清除RijndaelManaged对象。
如果(aesAlg!=null)
aesAlg.Clear();
}
//从内存流返回加密的字节。
回报率;
}
/// 
///解密给定字符串。假定该字符串是使用
///EncryptStringAES(),使用相同的sharedSecret。
/// 
///要解密的文本。
///用于生成解密密钥的密码。
公共静态字符串解密字符串AES(字符串密文、字符串共享密文)
{
if(string.IsNullOrEmpty(密文))
抛出新的ArgumentNullException(“密文”);
if(string.IsNullOrEmpty(sharedSecret))
抛出新ArgumentNullException(“sharedSecret”);
//声明RijndaelManaged对象
//用于解密数据。
RijndaelManaged aesAlg=null;
//声明用于保存的字符串
//解密的文本。
字符串明文=空;
尝试
{
//从共享密钥和salt生成密钥
Rfc2898DeriveBytes键=新的Rfc2898DeriveBytes(sharedSecret,_salt);
//创建用于解密的流。
byte[]bytes=Convert.FromBase64String(密文);
使用(MemoryStream msDecrypt=新的MemoryStream(字节))
{
//创建RijndaelManaged对象
//使用指定的键和IV。
aesAlg=新RijndaelManaged();
aesAlg.Key=Key.GetBytes(aesAlg.KeySize/8);
//从加密流中获取初始化向量
aesAlg.IV=读写阵列(msDecrypt);
//创建decrytor以执行流变换。
ICryptoTransform decryptor=aesAlg.CreateDecryptor(aesAlg.Key,aesAlg.IV);
使用(CryptoStream csDecrypt=新加密流(msDecrypt、解密程序、CryptoStreamMode.Read))
{
使用(StreamReader srDecrypt=新的StreamReader(csDecrypt))
//从解密流中读取解密的字节
//然后把它们放在一根绳子里。
明文=srDecrypt.ReadToEnd();
}
}
}
最后
{
//清除RijndaelManaged对象。
如果(aesAlg!=null)
aesAlg.Clear();
}
返回纯文本;
}
专用静态字节[]ReadByteArray(流s)
{
字节[]rawLength=新字节[sizeof(int)];
if(s.Read(rawLength,0,rawLength.Length)!=rawLength.Length)
{
抛出新的SystemException(“流未包含格式正确的字节数组”);
}
字节[]缓冲区=新字节[BitConverter.ToInt32(rawLength,0)];
if(s.Read(buffer,0,buffer.Length)!=buffer.Length)
{
抛出新的SystemException(“未正确读取字节数组”);
}
返回缓冲区;
}
}

我想,您可以只保存用户保存的字符串,然后编写一个带有加密字符串的常规XML文件

这里有一个例子

公共类加密
{
私有静态字节[]_salt=Encoding.ASCII.GetBytes(“o6806642kbM7c5”);
/// 
///使用AES加密给定字符串。可以使用
///DecryptStringAES()。sharedSecr
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;
    }
}