在C#中对XML文件进行加密可以使用对称加密算法或非对称加密算法。下面分别介绍两种方式:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Xml;
public class XmlEncryption
{
public static void EncryptXmlFile(string inputFile, string outputFile, string key)
{
using (Aes aes = Aes.Create())
{
aes.Key = Convert.FromBase64String(key);
aes.IV = new byte[16];
using (FileStream fsInput = new FileStream(inputFile, FileMode.Open))
using (FileStream fsOutput = new FileStream(outputFile, FileMode.Create))
using (CryptoStream cs = new CryptoStream(fsOutput, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
fsInput.CopyTo(cs);
}
}
}
public static void DecryptXmlFile(string inputFile, string outputFile, string key)
{
using (Aes aes = Aes.Create())
{
aes.Key = Convert.FromBase64String(key);
aes.IV = new byte[16];
using (FileStream fsInput = new FileStream(inputFile, FileMode.Open))
using (FileStream fsOutput = new FileStream(outputFile, FileMode.Create))
using (CryptoStream cs = new CryptoStream(fsInput, aes.CreateDecryptor(), CryptoStreamMode.Read))
{
cs.CopyTo(fsOutput);
}
}
}
}
using System;
using System.IO;
using System.Security.Cryptography;
using System.Xml;
public class XmlEncryption
{
public static void EncryptXmlFile(string inputFile, string outputFile, string publicKey)
{
using (RSA rsa = RSA.Create())
{
rsa.FromXmlString(publicKey);
using (FileStream fsInput = new FileStream(inputFile, FileMode.Open))
using (FileStream fsOutput = new FileStream(outputFile, FileMode.Create))
{
byte[] inputBytes = new byte[fsInput.Length];
fsInput.Read(inputBytes, 0, inputBytes.Length);
byte[] encryptedBytes = rsa.Encrypt(inputBytes, RSAEncryptionPadding.Pkcs1);
fsOutput.Write(encryptedBytes, 0, encryptedBytes.Length);
}
}
}
public static void DecryptXmlFile(string inputFile, string outputFile, string privateKey)
{
using (RSA rsa = RSA.Create())
{
rsa.FromXmlString(privateKey);
using (FileStream fsInput = new FileStream(inputFile, FileMode.Open))
using (FileStream fsOutput = new FileStream(outputFile, FileMode.Create))
{
byte[] inputBytes = new byte[fsInput.Length];
fsInput.Read(inputBytes, 0, inputBytes.Length);
byte[] decryptedBytes = rsa.Decrypt(inputBytes, RSAEncryptionPadding.Pkcs1);
fsOutput.Write(decryptedBytes, 0, decryptedBytes.Length);
}
}
}
}
以上示例代码只是演示了如何使用对称加密算法和非对称加密算法对XML文件进行加密和解密,实际应用中需要根据具体需求进行调整和完善。