简单的使用.NET对称加密的例子

复制代码
using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;

/// <summary>
/// 使用对称加密的例子
/// </summary>
class Class1
{

static void Main(string[] args)
{
Class1 c
=new Class1();
c.StartDemo();
}

public void StartDemo()
{
//establish symmetric algorithm
SymmetricAlgorithm sa = Rijndael.Create();

//key and iv
sa.GenerateKey(); //产生随机的 (32*8) 位的密钥
//sa.GenerateIV(); //初始向量,在ECB模式里面可以不用IV
sa.Mode = CipherMode.ECB; //块处理模式
sa.Padding = PaddingMode.Zeros; //末尾数据块的填充模式


Console.WriteLine(
"密钥是:"); ///////////
for (int i=0; i<sa.Key.Length; i++) ///////////
{ ///////////
Console.Write("{0:X2} ",sa.Key[i]); ///////////
} ///////////
Console.WriteLine("\n"); ///////////


//establish crypto stream
MemoryStream ms = new MemoryStream();
CryptoStream cs
= new CryptoStream(ms,sa.CreateEncryptor(),CryptoStreamMode.Write);

//
string plaintext; //原始文本
byte[] cipherbytes; //加密后的数据
byte[] finalbytes; //解密后的数据

plaintext
="How are you? 这是一行文字。";
byte[] plainbytes = Encoding.UTF8.GetBytes(plaintext);


Console.WriteLine(
"原始文本是:\n{0}\n",plaintext);
//display plaint text byte array in hex format
Console.WriteLine("原始数据是:"); ///////////
for (int i=0; i<plainbytes.Length; i++) ///////////
{ ///////////
Console.Write("{0:X2} ",plainbytes[i]); ///////////
} ///////////
Console.WriteLine("\n"); ///////////

//加密过程
cs.Write(plainbytes, 0, plainbytes.Length);
cs.Close();
cipherbytes
= ms.ToArray();
ms.Close();

//display ciphertext byte array in hex format
Console.WriteLine("加密后的数据是:"); ///////////
for (int i=0; i<cipherbytes.Length; i++) ///////////
{ ///////////
Console.Write("{0:X2} ",cipherbytes[i]);///////////
} ///////////
Console.WriteLine("\n"); ///////////


//下面的为加密过程
ms=new MemoryStream(cipherbytes);
cs
=new CryptoStream(ms,sa.CreateDecryptor(),CryptoStreamMode.Read);
finalbytes
=new byte[plainbytes.Length];
cs.Read(finalbytes,
0,plainbytes.Length);

Console.WriteLine(
"解密后的数据是:"); ///////////
for (int i=0; i<finalbytes.Length; i++) ///////////
{ ///////////
Console.Write("{0:X2} ",finalbytes[i]); ///////////
} ///////////
Console.WriteLine("\n"); ///////////

string finaltext=Encoding.UTF8.GetString(finalbytes);

Console.WriteLine(
"解密后的文本是:\n{0}\n\n",finaltext );
Console.WriteLine(
"按任意键继续......");
Console.ReadLine();

}
}
复制代码

 

http://blog.csdn.net/kwanhong/archive/2005/09/22/486783.aspx

 

 

posted @   庚武  Views(384)  Comments(0Edit  收藏  举报
编辑推荐:
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
阅读排行:
· C# 13 中的新增功能实操
· Ollama本地部署大模型总结
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(4)
· langchain0.3教程:从0到1打造一个智能聊天机器人
· 2025成都.NET开发者Connect圆满结束
点击右上角即可分享
微信分享提示