using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
///
//对字符串加密的思想:利用加解密类DESCryptoServiceProvider类
/并结合CryptoStram内存流对输入的字符串进行加解密
注意加密的密钥和字符串都要先转换为字节数组,加密密钥也要转换为字节数组
namespace ConsoleApplication1
{
/// <summary>
/// 对字符串实现加解密
/// </summary>
class Edstr
{
static string encryptKey = "Oyea"; //加密密钥
static void Main(string[] args)
{
Console.WriteLine("请您输入字符串:");
string strName = Console.ReadLine();
//DESCryptoServiceProvider加解密类对象
//并结合CryptoStream内存流对输入的字符串进行加解秘
DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();
//定义字节数组来存放密钥
byte[] key = Encoding.Unicode.GetBytes(encryptKey);
//定义字节数组来存放加密的字符串
byte[] data = Encoding.Unicode.GetBytes(strName);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, descsp.CreateEncryptor(key, key), CryptoStreamMode.Write);
cs.Write(data, 0, data.Length);//像加密流中写入数据
cs.FlushFinalBlock();//释放加密流
string names = Convert.ToBase64String(ms.ToArray());//ToArray():是把流转换为字节数组
Console.WriteLine("加密后的字符串为:" + names);
//定义字节数组来存放需要解密的字符串
byte[] data2 = Convert.FromBase64String(names);
ms=new MemoryStream();
//使用内存流解密
cs = new CryptoStream(ms, descsp.CreateDecryptor(key, key), CryptoStreamMode.Write);
cs.Write(data2, 0, data2.Length); //像解密流中写入数据
cs.FlushFinalBlock();
string strde = Encoding.Unicode.GetString(ms.ToArray());
Console.WriteLine("解密后的字符串为:" + strde);
ms.Close();
cs.Close();
Console.ReadLine();
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
///
//对字符串加密的思想:利用加解密类DESCryptoServiceProvider类
/并结合CryptoStram内存流对输入的字符串进行加解密
注意加密的密钥和字符串都要先转换为字节数组,加密密钥也要转换为字节数组
namespace ConsoleApplication1
{
/// <summary>
/// 对字符串实现加解密
/// </summary>
class Edstr
{
static string encryptKey = "Oyea"; //加密密钥
static void Main(string[] args)
{
Console.WriteLine("请您输入字符串:");
string strName = Console.ReadLine();
//DESCryptoServiceProvider加解密类对象
//并结合CryptoStream内存流对输入的字符串进行加解秘
DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();
//定义字节数组来存放密钥
byte[] key = Encoding.Unicode.GetBytes(encryptKey);
//定义字节数组来存放加密的字符串
byte[] data = Encoding.Unicode.GetBytes(strName);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, descsp.CreateEncryptor(key, key), CryptoStreamMode.Write);
cs.Write(data, 0, data.Length);//像加密流中写入数据
cs.FlushFinalBlock();//释放加密流
string names = Convert.ToBase64String(ms.ToArray());//ToArray():是把流转换为字节数组
Console.WriteLine("加密后的字符串为:" + names);
//定义字节数组来存放需要解密的字符串
byte[] data2 = Convert.FromBase64String(names);
ms=new MemoryStream();
//使用内存流解密
cs = new CryptoStream(ms, descsp.CreateDecryptor(key, key), CryptoStreamMode.Write);
cs.Write(data2, 0, data2.Length); //像解密流中写入数据
cs.FlushFinalBlock();
string strde = Encoding.Unicode.GetString(ms.ToArray());
Console.WriteLine("解密后的字符串为:" + strde);
ms.Close();
cs.Close();
Console.ReadLine();
}
}
}