110,535
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace TestProject
{
public class Cryptor
{
private Encoding _encoding;
private string _keyString;
private string _ivString;
public string KeyString
{
get { return _keyString; }
set
{
if (!_keyString.Equals(value))
{
if (string.IsNullOrEmpty(value)) throw new ArgumentException("Cryptor's porperty's KeyString set handler have error.KeyString format is error.");
_keyString = value;
_provider.Key = _encoding.GetBytes(_keyString);
}
}
}
public string IvString
{
get { return _ivString; }
set
{
if (!_ivString.Equals(value))
{
if (string.IsNullOrEmpty(value)) throw new ArgumentException("Cryptor's porperty's IvString set handler have error.IvString format is error.");
_ivString = value;
_provider.IV = _encoding.GetBytes(_ivString);
}
}
}
private DESCryptoServiceProvider _provider;
public DESCryptoServiceProvider Provider
{
get { return _provider; }
}
public Encoding Encoding
{
get { return _encoding; }
set { _encoding = value; }
}
public Cryptor()
: this(Encoding.Unicode)
{
}
public Cryptor(Encoding encoding)
{
_provider = new DESCryptoServiceProvider();
_encoding = encoding;
_provider.GenerateKey();
_provider.GenerateIV();
}
public Cryptor(string keyString, string ivString)
{
_provider = new DESCryptoServiceProvider();
_encoding = Encoding.Unicode;
if (string.IsNullOrEmpty(keyString)) throw new ArgumentException("Cryptor.cs's Create funtion's arge : keyString is null or string.Empty.");
if (string.IsNullOrEmpty(ivString)) throw new ArgumentException("Cryptor.cs's Create funtion's arge : ivString is null or string.Empty.");
KeyString = keyString;
IvString = ivString;
}
public Cryptor(byte[] keyBytes, byte[] ivBytes)
{
_provider = new DESCryptoServiceProvider();
_encoding = Encoding.Unicode;
_provider.Key = keyBytes;
_provider.IV = ivBytes;
}
public string CryptoString(string source)
{
byte[] rgbKey = _provider.Key;
byte[] rgbIV = _provider.IV;
return CryptoString(source, rgbKey, rgbIV);
}
public string CryptoString(string source, byte[] rgbKey, byte[] rgbIV)
{
string result = string.Empty;
byte[] sourceBuffer = new byte[source.Length];
try
{
sourceBuffer = _encoding.GetBytes(source);
MemoryStream beCryptoStream = new MemoryStream();
ICryptoTransform cryptoTransform = _provider.CreateEncryptor(rgbKey, rgbIV);
CryptoStream cryptorStream = new CryptoStream(beCryptoStream, cryptoTransform, CryptoStreamMode.Write);
cryptorStream.Write(sourceBuffer, 0, sourceBuffer.Length);
cryptorStream.FlushFinalBlock();
result = _encoding.GetString(beCryptoStream.ToArray());
}
catch (Exception e)
{
throw new ArgumentException("Cryptor.cs's Crypto's method have error." + e);
}
return result;
}
public void CryptoFileStream(FileStream source)
{
byte[] rgbKey = _provider.Key;
byte[] rgbIV = _provider.IV;
CryptoFileStream(source, rgbKey, rgbIV);
}
public void CryptoFileStream(FileStream source, byte[] rgbKey, byte[] rgbIV)
{
byte[] sourceBuffer = new byte[source.Length];
source.Write(sourceBuffer, 0, sourceBuffer.Length);
ICryptoTransform cryptoTransform = _provider.CreateEncryptor(rgbKey, rgbIV);
CryptoStream cryptorStream = new CryptoStream(source, cryptoTransform, CryptoStreamMode.Write);
cryptorStream.Write(sourceBuffer, 0, sourceBuffer.Length);
cryptorStream.FlushFinalBlock();
}
public string DescryptoString(string source)
{
byte[] rgbKey = _provider.Key;
byte[] rgbIV = _provider.IV;
return DescryptoString(source, rgbKey, rgbIV);
}
public string DescryptoString(string source, byte[] rgbKey, byte[] rgbIV)
{
string result = string.Empty;
byte[] sourceBuffer = new byte[source.Length];
try
{
sourceBuffer = _encoding.GetBytes(source);
MemoryStream beDesCryptoStream = new MemoryStream();
ICryptoTransform cryptoTransform = _provider.CreateDecryptor(rgbKey, rgbIV);
CryptoStream cryptorStream = new CryptoStream(beDesCryptoStream, cryptoTransform, CryptoStreamMode.Write);
cryptorStream.Write(sourceBuffer, 0, sourceBuffer.Length);
cryptorStream.FlushFinalBlock();
result = _encoding.GetString(beDesCryptoStream.ToArray());
}
catch (Exception e)
{
throw new ArgumentException("Cryptor.cs's Descrypto's method have error." + e);
}
return result;
}
public void DescryptoFileStream(FileStream source)
{
byte[] rgbKey = _provider.Key;
byte[] rgbIV = _provider.IV;
DescryptoFileStream(source, rgbKey, rgbIV);
}
public void DescryptoFileStream(FileStream source, byte[] rgbKey, byte[] rgbIV)
{
byte[] sourceBuffer = new byte[source.Length];
source.Write(sourceBuffer, 0, sourceBuffer.Length);
ICryptoTransform cryptoTransform = _provider.CreateDecryptor(rgbKey, rgbIV);
CryptoStream cryptorStream = new CryptoStream(source, cryptoTransform, CryptoStreamMode.Write);
cryptorStream.Write(sourceBuffer, 0, sourceBuffer.Length);
cryptorStream.FlushFinalBlock();
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
namespace TestProject
{
public partial class TestDESCrypto : Form
{
private Cryptor _cryptor;
public TestDESCrypto()
{
InitializeComponent();
//定义加密类的Key和Iv(密钥与位移量)
byte[] keyBytes = new byte[] { 0x53, 0x61, 0x56, 0xff, 0xac, 0xfb, 0xfa, 0xfc };
byte[] ivBytes = new byte[] { 0xac, 0xfb, 0xfa, 0xfc, 0x53, 0x61, 0x56, 0xff };
//构造加密类
_cryptor = new Cryptor(keyBytes, ivBytes);
}
private void button_Crypto_Click(object sender, EventArgs e)
{
richTextBox_Result.Text = _cryptor.CryptoString(richTextBox_Source.Text);//这里加密正常
}
private void button_Descrypt_Click(object sender, EventArgs e)
{
richTextBox_Source.Text = _cryptor.DescryptoString(richTextBox_Result.Text);//这里解密虽然没有异常,但解密后的字符和原字符不一样了。怎么回事,从上面的加密类来看,加密和解密的密钥和位移量都是一样的。但结果不一样?
}
private void button_InputDescrypto_Click(object sender, EventArgs e)
{
string readFilePath = Application.StartupPath + @"\PlayersScore.xml";
FileStream fileStream = File.Open(readFilePath, FileMode.OpenOrCreate);
_cryptor.DescryptoFileStream(fileStream);//这里解密过程有错,说我的解密数据长度不足?怎么回事,我都是调用同一个Key和Iv的,在上面的加密类可以看到。
fileStream.Flush();
fileStream.Close();
DataSet dataSet = new DataSet();
dataSet.ReadXml(fileStream);
dataGridView.DataSource = dataSet.Tables[0];
}
private void button_OutputCrypto_Click(object sender, EventArgs e)
{
string readFilePath = Application.StartupPath + @"\PlayersScore.xml";
FileStream fileStream = File.Open(readFilePath, FileMode.OpenOrCreate);
_cryptor.CryptoFileStream(fileStream);//这里加密过程无任何错误
fileStream.Flush();
fileStream.Close();
}
}
}
#region DESCryptoServiceProvider
#region 密钥
private static readonly string strCryptKey = "IjoyEnDeCryptKeyForNumberAndFiles";
#endregion
#region 数据加密
/// <summary>
/// 数据加密
/// </summary>
/// <param name="strTxt"></param>
/// <returns></returns>
public static string DesEncrypt(string strTxt)
{
byte[] byKey = null;
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
try
{
byKey = Encoding.UTF8.GetBytes(strCryptKey.Substring(12, 8));
DESCryptoServiceProvider desCryptoSrvPrv = new DESCryptoServiceProvider();
byte[] inputbyArr = Encoding.UTF8.GetBytes(strTxt);
MemoryStream memStream = new MemoryStream();
CryptoStream cryStream = new CryptoStream(memStream, desCryptoSrvPrv.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
cryStream.Write(inputbyArr, 0, inputbyArr.Length);
cryStream.FlushFinalBlock();
return Convert.ToBase64String(memStream.ToArray());
}
catch (Exception ex)
{
return "Error:" + ex.Message + "\r";
}
}
#endregion
#region 数据解密
/// <summary>
/// 数据解密
/// </summary>
/// <param name="strTxt"></param>
/// <returns></returns>
public static string DesDecrypt(string strTxt)
{
byte[] byKey = null;
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
byte[] inputbyArr = new Byte[strTxt.Length];
try
{
byKey = Encoding.UTF8.GetBytes(strCryptKey.Substring(12, 8));
DESCryptoServiceProvider desCryptoSrvPrv = new DESCryptoServiceProvider();
inputbyArr = Convert.FromBase64String(strTxt);
MemoryStream ms = new MemoryStream();
CryptoStream cStream = new CryptoStream(ms, desCryptoSrvPrv.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
cStream.Write(inputbyArr, 0, inputbyArr.Length);
cStream.FlushFinalBlock();
Encoding enc = new UTF8Encoding();
return enc.GetString(ms.ToArray());
}
catch (Exception ex)
{
return "Error:" + ex.Message + "\r";
}
}
#endregion
#region 文件加密
/// <summary>
/// 文件加密
/// </summary>
/// <param name="m_InfilePath"></param>
/// <param name="m_OutFilePath"></param>
public void DesEncrypt(string m_InfilePath, string m_OutFilePath)
{
byte[] byKey = null;
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
try
{
byKey = Encoding.UTF8.GetBytes(strCryptKey.Substring(12, 8));
FileStream filInStream = new FileStream(m_InfilePath, FileMode.Open, FileAccess.Read);
FileStream filOutStream = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write);
filOutStream.SetLength(0);
byte[] bin = new byte[100];
long rdlen = 0;
long totlen = filInStream.Length;
int len;
DES des = new DESCryptoServiceProvider();
CryptoStream encStream = new CryptoStream(filOutStream, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
while (rdlen < totlen)
{
len = filInStream.Read(bin, 0, 100);
encStream.Write(bin, 0, len);
rdlen += len;
}
encStream.Close();
filOutStream.Close();
filInStream.Close();
}
catch (Exception ex)
{
HttpContext.Current.Response.Write("Error:" + ex.Message + "\r");
}
}
#endregion
#region 文件解密
/// <summary>
/// 文件解密
/// </summary>
/// <param name="m_InfilePath"></param>
/// <param name="m_OutFilePath"></param>
public void DesDecrypt(string m_InfilePath, string m_OutFilePath)
{
byte[] byKey = null;
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
try
{
byKey = Encoding.UTF8.GetBytes(strCryptKey.Substring(12, 8));
FileStream filInStream = new FileStream(m_InfilePath, FileMode.Open, FileAccess.Read);
FileStream filOutStream = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write);
filOutStream.SetLength(0);
byte[] bin = new byte[100];
long rdlen = 0;
long totlen = filInStream.Length;
int len;
DES des = new DESCryptoServiceProvider();
CryptoStream encStream = new CryptoStream(filOutStream, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
while (rdlen < totlen)
{
len = filInStream.Read(bin, 0, 100);
encStream.Write(bin, 0, len);
rdlen += len;
}
encStream.Close();
filOutStream.Close();
filInStream.Close();
}
catch (Exception ex)
{
HttpContext.Current.Response.Write("Error:" + ex.Message + "\r");
}
}
#endregion
#endregion