在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文件進行加密和解密,實際應用中需要根據具體需求進行調整和完善。