C# 以加密形式打开数据
时间: 2023-06-30 07:16:04 浏览: 50
要以加密形式打开数据,首先需要对数据进行加密处理。在 C# 中,可以使用加密算法(如 AES、RSA 等)对数据进行加密。以下是一个使用 AES 加密算法对数据进行加密的示例代码:
```csharp
using System;
using System.IO;
using System.Security.Cryptography;
class Program
{
static void Main(string[] args)
{
// 加密密钥和向量
byte[] key = new byte[32] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20 };
byte[] iv = new byte[16] { 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30 };
// 加密文本
string plainText = "Hello, world!";
byte[] plainBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
// 加密器
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.Key = key;
aes.IV = iv;
// 加密流
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(plainBytes, 0, plainBytes.Length);
cs.FlushFinalBlock();
// 加密后的文本
byte[] encryptedBytes = ms.ToArray();
string encryptedText = Convert.ToBase64String(encryptedBytes);
// 输出加密后的文本
Console.WriteLine(encryptedText);
}
}
```
该示例代码将 "Hello, world!" 字符串使用 AES 加密算法加密,并将加密后的结果输出到控制台。要打开加密后的数据,需要使用相同的密钥和向量,对加密后的数据进行解密处理。以下是一个使用 AES 加密算法对数据进行解密的示例代码:
```csharp
using System;
using System.IO;
using System.Security.Cryptography;
class Program
{
static void Main(string[] args)
{
// 加密密钥和向量
byte[] key = new byte[32] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20 };
byte[] iv = new byte[16] { 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30 };
// 加密文本
string encryptedText = "c0i0rR51fZ1WzLJcZL6ZLw==";
byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
// 加密器
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.Key = key;
aes.IV = iv;
// 解密流
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(encryptedBytes, 0, encryptedBytes.Length);
cs.FlushFinalBlock();
// 解密后的文本
byte[] plainBytes = ms.ToArray();
string plainText = System.Text.Encoding.UTF8.GetString(plainBytes);
// 输出解密后的文本
Console.WriteLine(plainText);
}
}
```
该示例代码将 "c0i0rR51fZ1WzLJcZL6ZLw==" 字符串使用 AES 加密算法解密,并将解密后的结果输出到控制台。