在.NET中,有多种方式可以对数据进行加密。以下是一些常见的加密方法和示例:
1. AES (高级加密标准)
AES是一种广泛使用的对称加密算法。
```csharp
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] encrypted;
// Create an Aes object with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
// Create an encryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);