赞
踩
在C#中实现加密功能,您可以使用.NET框架提供的System.Security.Cryptography命名空间下的多种加密算法类。这里我将给出一个使用AES(Advanced Encryption Standard)对称加密算法的简单示例:
- using System;
- using System.IO;
- using System.Security.Cryptography;
- using System.Text;
-
- public class AesEncryptionExample
- {
- public static void Main()
- {
- // 加密部分
- string plainText = "这是一段需要加密的文本";
- byte[] keyBytes = Encoding.UTF8.GetBytes("这是一个16字节的密钥"); // AES密钥必须为16/24/32个字节
- byte[] ivBytes = new byte[16]; // 初始化向量,AES要求16个字节
-
- // 使用随机数生成器初始化IV
- RandomNumberGenerator.Create().GetBytes(ivBytes);
-
- using (AesManaged aes = new AesManaged())
- {
- aes.Key = keyBytes;
- aes.IV = ivBytes;
-
- ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
-
- using (MemoryStream ms = new MemoryStream())
- {
- using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
- {
- using (StreamWriter sw = new StreamWriter(cs))
- {
- sw.Write(plainText);
- }
- byte[] cipherTextBytes = ms.ToArray();
- Console.WriteLine("加密后的数据:");
- Console.WriteLine(Convert.ToBase64String(cipherTextBytes));
- }
- }
- }
-
- // 解密部分
- byte[] encryptedData = Convert.FromBase64String("这里是加密后Base64编码的数据");
- using (AesManaged aesDecryptor = new AesManaged())
- {
- aesDecryptor.Key = keyBytes;
- aesDecryptor.IV = ivBytes;
-
- ICryptoTransform decryptor = aesDecryptor.CreateDecryptor();
-
- using (MemoryStream msDecrypt = new MemoryStream(encryptedData))
- {
- using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
- {
- using (StreamReader srDecrypt = new StreamReader(csDecrypt))
- {
- string decryptedText = srDecrypt.ReadToEnd();
- Console.WriteLine("\n解密后的数据:");
- Console.WriteLine(decryptedText);
- }
- }
- }
- }
- }
- }
这个例子展示了如何使用AES加密和解密字符串。注意在实际应用中,密钥应通过安全的方式存储和传递,并且可能需要使用密码派生函数(如Rfc2898DeriveBytes)从用户输入的密码生成密钥和初始化向量。此外,在传输或存储密文时,通常会一起保存IV,以便于解密。
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。