也谈.net加密解密
生活随笔
收集整理的這篇文章主要介紹了
也谈.net加密解密
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在最近的一個.net項目中,需要使用到加密技術。就是根據:用戶提供的一個key,來加密一些字符信息,最后可以根據這個key來解密信息!小弟當時確實為此,急的直抓頭。在google,百度中翻來覆去的找資料。但是,確實很失望,沒有一個很好的例子。百般無奈,自己查看MSDN,終于,寫出了下面這個類!用它可以實現前面用戶提出的需求。現在拿出來和大家分享!
??? 在這個類中主要應用到了.net的兩個基類(要不然很真不知道怎么辦),一個是System.Security,另一個是System.Security.Cryptography,很明顯一看就知道是Microsoft用來做加密信息的。廢話不多說,讓我們來看這個類! 加密,解密功能函數#region?加密,解密功能函數?
using?System;
using?System.IO;
using?System.Text;
using?System.Security;
using?System.Security.Cryptography;
namespace?Utility.Common
{
/**//**//**////?<summary>
///?加密,解密功能函數
///?</summary>?
public?class?EncryptionUtil
{
public?EncryptionUtil()
{
//
//?TODO:?Add?constructor?logic?here
//?
}
static?private?Byte[]?m_Key?=?new?Byte[8];
static?private?Byte[]?m_IV?=?new?Byte[8];
//為了安全,直接將key寫死在文件中,你也可以用一個屬性來實現?
public?string?key?=?"test$)";
/**//**//**///?
//加密函數?
public?string?EncryptData(String?strKey,?String?strData)
{
string?strResult;?//Return?Result
//1.?字符大小不能超過?90Kb.?否則,?緩存容易溢出(看第3點)?
if?(strData.Length?>?92160)
{
strResult="Error.?Data?String?too?large.?Keep?within?90Kb.";
return?strResult;
}
//2.?生成key?
if?(!InitKey(strKey))
{
strResult="Error.?Fail?to?generate?key?for?encryption";
return?strResult;
}
//3.?準備處理的字符串
//字符串的前5個字節用來存儲數據的長度
//用這個簡單的方法來記住數據的初始大小,沒有用太復雜的方法?
strData?=?String.Format("{0,5:00000}"+strData,?strData.Length);
//4.?加密數據?
byte[]?rbData?=?new?byte[strData.Length];
ASCIIEncoding?aEnc?=?new?ASCIIEncoding();
aEnc.GetBytes(strData,?0,?strData.Length,?rbData,?0);
//加密功能實現的主要類?
DESCryptoServiceProvider?descsp?=?new?DESCryptoServiceProvider();
ICryptoTransform?desEncrypt?=?descsp.CreateEncryptor(m_Key,?m_IV);
//5.?準備stream
//?mOut是輸出流.
//?mStream是輸入流
//?cs為轉換流?
MemoryStream?mStream?=?new?MemoryStream(rbData);
CryptoStream?cs?=?new?CryptoStream(mStream,?desEncrypt,?CryptoStreamMode.Read);
MemoryStream?mOut?=?new?MemoryStream();
//6.?開始加密?
int?bytesRead;
byte[]?output?=?new?byte[1024];
do
{
bytesRead?=?cs.Read(output,0,1024);
if?(bytesRead?!=?0)
mOut.Write(output,0,bytesRead);
}?while?(bytesRead?>?0);
//7.?返回加密結果
//因為是一個web項目,在這里轉換為base64,因此在http上是不會出錯的?
if?(mOut.Length?==?0)
strResult?=?"";
else
strResult?=?Convert.ToBase64String(mOut.GetBuffer(),?0,?(int)mOut.Length);
return?strResult;
}
/**//**//**///?
//解密函數?
public?string?DecryptData(String?strKey,?String?strData)
{
string?strResult;
//1.?生成解密key?
if?(!InitKey(strKey))
{
strResult="Error.?Fail?to?generate?key?for?decryption";
return?strResult;
}
//2.?初始化解密的主要類?
int?nReturn?=?0;
DESCryptoServiceProvider?descsp?=?new?DESCryptoServiceProvider();
ICryptoTransform?desDecrypt?=?descsp.CreateDecryptor(m_Key,?m_IV);
//3.?準備stream
//?mOut為輸出流
//?cs為轉換流?
MemoryStream?mOut?=?new?MemoryStream();
CryptoStream?cs?=?new?CryptoStream(mOut,?desDecrypt,?CryptoStreamMode.Write);
byte[]?bPlain?=?new?byte[strData.Length];
try
{
bPlain=Convert.FromBase64CharArray(strData.ToCharArray(),0,strData.Length);
}
catch?(Exception)
{
strResult?=?"Error.?Input?Data?is?not?base64?encoded.";
return?strResult;
}
long?lRead?=?0;
long?lTotal?=?strData.Length;
try
{
//5.?完成解密?
while?(lTotal?>=?lRead)
{
cs.Write(bPlain,0,(int)bPlain.Length);
lRead?=?mOut.Length?+?Convert.ToUInt32(((bPlain.Length?/?descsp.BlockSize)?*?descsp.BlockSize));
};
ASCIIEncoding?aEnc?=?new?ASCIIEncoding();
strResult?=?aEnc.GetString(mOut.GetBuffer(),?0,?(int)mOut.Length);
//6.去處存儲長度的前5個字節的數據?
String?strLen?=?strResult.Substring(0,5);
int?nLen?=?Convert.ToInt32(strLen);
strResult?=?strResult.Substring(5,?nLen);
nReturn?=?(int)mOut.Length;
return?strResult;
}
catch?(Exception)
{
strResult?=?"Error.?Decryption?Failed.?Possibly?due?to?incorrect?Key?or?corrputed?data";
return?strResult;
}
}
/**//**//**//?
//生成key的函數?
static?private?bool?InitKey(String?strKey)
{
try
{
//?轉換key為字節流?
byte[]?bp?=?new?byte[strKey.Length];
ASCIIEncoding?aEnc?=?new?ASCIIEncoding();
aEnc.GetBytes(strKey,?0,?strKey.Length,?bp,?0);
SHA1CryptoServiceProvider?sha?=?new?SHA1CryptoServiceProvider();
byte[]?bpHash?=?sha.ComputeHash(bp);
int?i;
//?生成初始化DESCryptoServiceProvider的參數?
for?(i=0;?i<8;?i++)
m_Key[i]?=?bpHash[i];
for?(i=8;?i<16;?i++)
m_IV[i-8]?=?bpHash[i];
return?true;
}
catch?(Exception)
{
//錯誤處理?
return?false;
}
}
}
}
#endregion
?好的,我們下面來看如何使用這個類加密,解密字符數據前臺頁面:
<%@?Page?language="c#"?Codebehind="Encode.aspx.cs"?AutoEventWireup="false"?Inherits="WebUI.Encode"?%>
<!DOCTYPE?HTML?PUBLIC?"-//W3C//DTD?HTML?4.0?Transitional//EN"?>
<HTML>
<HEAD>
<title>Encode</title>
<meta?name="GENERATOR"?Content="Microsoft?Visual?Studio?.NET?7.1">
<meta?name="CODE_LANGUAGE"?Content="C#">
<meta?name="vs_defaultClientScript"?content="JavaScript">
<meta?name="vs_targetSchema"?content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body?MS_POSITIONING="GridLayout">
<form?id="Form1"?method="post"?runat="server">
<TABLE?id="Table1"?style="Z-INDEX:?107;?LEFT:?40px;?WIDTH:?688px;?POSITION:?absolute;?TOP:?32px;?HEIGHT:?118px"
cellSpacing="0"?cellPadding="1"?width="688"?border="1">
<TR>
<TD?style="WIDTH:?111px">
<asp:Label?id="Label1"?runat="server">Clear?String</asp:Label></TD>
<TD>
<asp:TextBox?id="txt_ClearString"?runat="server"?Width="440px"></asp:TextBox></TD>
<FONT?face="宋體"></FONT>
</TR>
<TR>
<TD?style="WIDTH:?111px">
<asp:Label?id="Label2"?runat="server">Code?String</asp:Label></TD>
<TD>
<asp:TextBox?id="txt_CodeString"?runat="server"?Width="440px"?ReadOnly="True"></asp:TextBox></TD>
</TR>
<TR>
<TD?style="WIDTH:?111px"><FONT?face="宋體"></FONT></TD>
<TD>
<asp:Button?id="btn_Encode"?runat="server"?Text="Encode"></asp:Button><FONT?face="宋體"> </FONT>
<asp:Button?id="btn_Clear"?runat="server"?Width="56px"?Text="Decode"></asp:Button></TD>
</TR>
</TABLE>
</form>
</body>
</HTML>?
?后臺頁面:
后臺頁面#region?后臺頁面
using?System;
using?System.Collections;
using?System.ComponentModel;
using?System.Data;
using?System.Drawing;
using?System.Web;
using?System.Web.SessionState;
using?System.Web.UI;
using?System.Web.UI.WebControls;
using?System.Web.UI.HtmlControls;
using?Utility.Common;
namespace?WebUI
{
/**//**//**////?<summary>
///?Encode?的摘要說明。
///?</summary>?
public?class?Encode?:?System.Web.UI.Page
{
protected?System.Web.UI.WebControls.Label?Label1;
protected?System.Web.UI.WebControls.TextBox?txt_ClearString;
protected?System.Web.UI.WebControls.TextBox?txt_CodeString;
protected?System.Web.UI.WebControls.Button?btn_Encode;
protected?System.Web.UI.WebControls.Button?btn_Clear;
protected?System.Web.UI.WebControls.Label?Label2;
private?void?Page_Load(object?sender,?System.EventArgs?e)
{
//?在此處放置用戶代碼以初始化頁面?
}
Web?窗體設計器生成的代碼Web?窗體設計器生成的代碼#region?Web?窗體設計器生成的代碼?
override?protected?void?OnInit(EventArgs?e)
{
//
//?CODEGEN:?該調用是?ASP.NET?Web?窗體設計器所必需的。
//?
InitializeComponent();
base.OnInit(e);
}
/**//**//**////?<summary>
///?設計器支持所需的方法?-?不要使用代碼編輯器修改
///?此方法的內容。
///?</summary>?
private?void?InitializeComponent()
{
this.btn_Encode.Click?+=?new?System.EventHandler(this.btn_Encode_Click);
this.btn_Clear.Click?+=?new?System.EventHandler(this.btn_Clear_Click);
this.Load?+=?new?System.EventHandler(this.Page_Load);
}
#endregion?
private?void?btn_Encode_Click(object?sender,?System.EventArgs?e)
{
Utility.Common.EncryptionUtil?EU?=?new?EncryptionUtil();
this.txt_CodeString.Text?=?EU.EncryptData(EU.key,this.txt_ClearString.Text.Trim());
}
private?void?btn_Clear_Click(object?sender,?System.EventArgs?e)
{
Utility.Common.EncryptionUtil?EU?=?new?EncryptionUtil();
this.txt_ClearString.Text?=?EU.DecryptData(EU.key,this.txt_CodeString.Text.Trim());
}
}
}
#endregion
??? 在這個類中主要應用到了.net的兩個基類(要不然很真不知道怎么辦),一個是System.Security,另一個是System.Security.Cryptography,很明顯一看就知道是Microsoft用來做加密信息的。廢話不多說,讓我們來看這個類! 加密,解密功能函數#region?加密,解密功能函數?
using?System;
using?System.IO;
using?System.Text;
using?System.Security;
using?System.Security.Cryptography;
namespace?Utility.Common
{
/**//**//**////?<summary>
///?加密,解密功能函數
///?</summary>?
public?class?EncryptionUtil
{
public?EncryptionUtil()
{
//
//?TODO:?Add?constructor?logic?here
//?
}
static?private?Byte[]?m_Key?=?new?Byte[8];
static?private?Byte[]?m_IV?=?new?Byte[8];
//為了安全,直接將key寫死在文件中,你也可以用一個屬性來實現?
public?string?key?=?"test$)";
/**//**//**///?
//加密函數?
public?string?EncryptData(String?strKey,?String?strData)
{
string?strResult;?//Return?Result
//1.?字符大小不能超過?90Kb.?否則,?緩存容易溢出(看第3點)?
if?(strData.Length?>?92160)
{
strResult="Error.?Data?String?too?large.?Keep?within?90Kb.";
return?strResult;
}
//2.?生成key?
if?(!InitKey(strKey))
{
strResult="Error.?Fail?to?generate?key?for?encryption";
return?strResult;
}
//3.?準備處理的字符串
//字符串的前5個字節用來存儲數據的長度
//用這個簡單的方法來記住數據的初始大小,沒有用太復雜的方法?
strData?=?String.Format("{0,5:00000}"+strData,?strData.Length);
//4.?加密數據?
byte[]?rbData?=?new?byte[strData.Length];
ASCIIEncoding?aEnc?=?new?ASCIIEncoding();
aEnc.GetBytes(strData,?0,?strData.Length,?rbData,?0);
//加密功能實現的主要類?
DESCryptoServiceProvider?descsp?=?new?DESCryptoServiceProvider();
ICryptoTransform?desEncrypt?=?descsp.CreateEncryptor(m_Key,?m_IV);
//5.?準備stream
//?mOut是輸出流.
//?mStream是輸入流
//?cs為轉換流?
MemoryStream?mStream?=?new?MemoryStream(rbData);
CryptoStream?cs?=?new?CryptoStream(mStream,?desEncrypt,?CryptoStreamMode.Read);
MemoryStream?mOut?=?new?MemoryStream();
//6.?開始加密?
int?bytesRead;
byte[]?output?=?new?byte[1024];
do
{
bytesRead?=?cs.Read(output,0,1024);
if?(bytesRead?!=?0)
mOut.Write(output,0,bytesRead);
}?while?(bytesRead?>?0);
//7.?返回加密結果
//因為是一個web項目,在這里轉換為base64,因此在http上是不會出錯的?
if?(mOut.Length?==?0)
strResult?=?"";
else
strResult?=?Convert.ToBase64String(mOut.GetBuffer(),?0,?(int)mOut.Length);
return?strResult;
}
/**//**//**///?
//解密函數?
public?string?DecryptData(String?strKey,?String?strData)
{
string?strResult;
//1.?生成解密key?
if?(!InitKey(strKey))
{
strResult="Error.?Fail?to?generate?key?for?decryption";
return?strResult;
}
//2.?初始化解密的主要類?
int?nReturn?=?0;
DESCryptoServiceProvider?descsp?=?new?DESCryptoServiceProvider();
ICryptoTransform?desDecrypt?=?descsp.CreateDecryptor(m_Key,?m_IV);
//3.?準備stream
//?mOut為輸出流
//?cs為轉換流?
MemoryStream?mOut?=?new?MemoryStream();
CryptoStream?cs?=?new?CryptoStream(mOut,?desDecrypt,?CryptoStreamMode.Write);
byte[]?bPlain?=?new?byte[strData.Length];
try
{
bPlain=Convert.FromBase64CharArray(strData.ToCharArray(),0,strData.Length);
}
catch?(Exception)
{
strResult?=?"Error.?Input?Data?is?not?base64?encoded.";
return?strResult;
}
long?lRead?=?0;
long?lTotal?=?strData.Length;
try
{
//5.?完成解密?
while?(lTotal?>=?lRead)
{
cs.Write(bPlain,0,(int)bPlain.Length);
lRead?=?mOut.Length?+?Convert.ToUInt32(((bPlain.Length?/?descsp.BlockSize)?*?descsp.BlockSize));
};
ASCIIEncoding?aEnc?=?new?ASCIIEncoding();
strResult?=?aEnc.GetString(mOut.GetBuffer(),?0,?(int)mOut.Length);
//6.去處存儲長度的前5個字節的數據?
String?strLen?=?strResult.Substring(0,5);
int?nLen?=?Convert.ToInt32(strLen);
strResult?=?strResult.Substring(5,?nLen);
nReturn?=?(int)mOut.Length;
return?strResult;
}
catch?(Exception)
{
strResult?=?"Error.?Decryption?Failed.?Possibly?due?to?incorrect?Key?or?corrputed?data";
return?strResult;
}
}
/**//**//**//?
//生成key的函數?
static?private?bool?InitKey(String?strKey)
{
try
{
//?轉換key為字節流?
byte[]?bp?=?new?byte[strKey.Length];
ASCIIEncoding?aEnc?=?new?ASCIIEncoding();
aEnc.GetBytes(strKey,?0,?strKey.Length,?bp,?0);
SHA1CryptoServiceProvider?sha?=?new?SHA1CryptoServiceProvider();
byte[]?bpHash?=?sha.ComputeHash(bp);
int?i;
//?生成初始化DESCryptoServiceProvider的參數?
for?(i=0;?i<8;?i++)
m_Key[i]?=?bpHash[i];
for?(i=8;?i<16;?i++)
m_IV[i-8]?=?bpHash[i];
return?true;
}
catch?(Exception)
{
//錯誤處理?
return?false;
}
}
}
}
#endregion
?好的,我們下面來看如何使用這個類加密,解密字符數據前臺頁面:
<%@?Page?language="c#"?Codebehind="Encode.aspx.cs"?AutoEventWireup="false"?Inherits="WebUI.Encode"?%>
<!DOCTYPE?HTML?PUBLIC?"-//W3C//DTD?HTML?4.0?Transitional//EN"?>
<HTML>
<HEAD>
<title>Encode</title>
<meta?name="GENERATOR"?Content="Microsoft?Visual?Studio?.NET?7.1">
<meta?name="CODE_LANGUAGE"?Content="C#">
<meta?name="vs_defaultClientScript"?content="JavaScript">
<meta?name="vs_targetSchema"?content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body?MS_POSITIONING="GridLayout">
<form?id="Form1"?method="post"?runat="server">
<TABLE?id="Table1"?style="Z-INDEX:?107;?LEFT:?40px;?WIDTH:?688px;?POSITION:?absolute;?TOP:?32px;?HEIGHT:?118px"
cellSpacing="0"?cellPadding="1"?width="688"?border="1">
<TR>
<TD?style="WIDTH:?111px">
<asp:Label?id="Label1"?runat="server">Clear?String</asp:Label></TD>
<TD>
<asp:TextBox?id="txt_ClearString"?runat="server"?Width="440px"></asp:TextBox></TD>
<FONT?face="宋體"></FONT>
</TR>
<TR>
<TD?style="WIDTH:?111px">
<asp:Label?id="Label2"?runat="server">Code?String</asp:Label></TD>
<TD>
<asp:TextBox?id="txt_CodeString"?runat="server"?Width="440px"?ReadOnly="True"></asp:TextBox></TD>
</TR>
<TR>
<TD?style="WIDTH:?111px"><FONT?face="宋體"></FONT></TD>
<TD>
<asp:Button?id="btn_Encode"?runat="server"?Text="Encode"></asp:Button><FONT?face="宋體"> </FONT>
<asp:Button?id="btn_Clear"?runat="server"?Width="56px"?Text="Decode"></asp:Button></TD>
</TR>
</TABLE>
</form>
</body>
</HTML>?
?后臺頁面:
后臺頁面#region?后臺頁面
using?System;
using?System.Collections;
using?System.ComponentModel;
using?System.Data;
using?System.Drawing;
using?System.Web;
using?System.Web.SessionState;
using?System.Web.UI;
using?System.Web.UI.WebControls;
using?System.Web.UI.HtmlControls;
using?Utility.Common;
namespace?WebUI
{
/**//**//**////?<summary>
///?Encode?的摘要說明。
///?</summary>?
public?class?Encode?:?System.Web.UI.Page
{
protected?System.Web.UI.WebControls.Label?Label1;
protected?System.Web.UI.WebControls.TextBox?txt_ClearString;
protected?System.Web.UI.WebControls.TextBox?txt_CodeString;
protected?System.Web.UI.WebControls.Button?btn_Encode;
protected?System.Web.UI.WebControls.Button?btn_Clear;
protected?System.Web.UI.WebControls.Label?Label2;
private?void?Page_Load(object?sender,?System.EventArgs?e)
{
//?在此處放置用戶代碼以初始化頁面?
}
Web?窗體設計器生成的代碼Web?窗體設計器生成的代碼#region?Web?窗體設計器生成的代碼?
override?protected?void?OnInit(EventArgs?e)
{
//
//?CODEGEN:?該調用是?ASP.NET?Web?窗體設計器所必需的。
//?
InitializeComponent();
base.OnInit(e);
}
/**//**//**////?<summary>
///?設計器支持所需的方法?-?不要使用代碼編輯器修改
///?此方法的內容。
///?</summary>?
private?void?InitializeComponent()
{
this.btn_Encode.Click?+=?new?System.EventHandler(this.btn_Encode_Click);
this.btn_Clear.Click?+=?new?System.EventHandler(this.btn_Clear_Click);
this.Load?+=?new?System.EventHandler(this.Page_Load);
}
#endregion?
private?void?btn_Encode_Click(object?sender,?System.EventArgs?e)
{
Utility.Common.EncryptionUtil?EU?=?new?EncryptionUtil();
this.txt_CodeString.Text?=?EU.EncryptData(EU.key,this.txt_ClearString.Text.Trim());
}
private?void?btn_Clear_Click(object?sender,?System.EventArgs?e)
{
Utility.Common.EncryptionUtil?EU?=?new?EncryptionUtil();
this.txt_ClearString.Text?=?EU.DecryptData(EU.key,this.txt_CodeString.Text.Trim());
}
}
}
#endregion
轉載于:https://www.cnblogs.com/Nina-piaoye/archive/2006/08/30/490031.html
總結
以上是生活随笔為你收集整理的也谈.net加密解密的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MS Vs.net 2003 Sp1发布
- 下一篇: 代码生成工具的分类及比较