zl程序教程

您现在的位置是:首页 >  后端

当前栏目

asp.net字符串加密解密技术

2023-06-13 09:14:08 时间

复制代码代码如下:


usingSystem;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Collections;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Web.UI.HtmlControls;
usingSystem.Text;
usingSystem.Security.Cryptography;
usingSystem.IO;
namespacewww
{
publicpartialclassjiami:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
Bind();
}
privatevoidBind()
{
//加密
this.Title=DesEncrypt("pwd","abcd1234");
this.Title+=DesDecrypt(this.Title,"abcd1234");
Response.Write(DesDecrypt("2ikCw0TqKGo=","abcd1234"));
}
///<summary>
///加密字符串
///注意:密钥必须为8位
///</summary>
///<paramname="strText">字符串</param>
///<paramname="encryptKey">密钥</param>
///<paramname="encryptKey">返回加密后的字符串</param>
publicstringDesEncrypt(stringinputString,stringencryptKey)
{
byte[]byKey=null;
byte[]IV={0x12,0x34,0x56,0x78,0x90,0xAB,0xCD,0xEF};
try
{
byKey=System.Text.Encoding.UTF8.GetBytes(encryptKey.Substring(0,8));
DESCryptoServiceProviderdes=newDESCryptoServiceProvider();
byte[]inputByteArray=Encoding.UTF8.GetBytes(inputString);
MemoryStreamms=newMemoryStream();
CryptoStreamcs=newCryptoStream(ms,des.CreateEncryptor(byKey,IV),CryptoStreamMode.Write);
cs.Write(inputByteArray,0,inputByteArray.Length);
cs.FlushFinalBlock();
returnConvert.ToBase64String(ms.ToArray());
}
catch(System.Exceptionerror)
{
//returnerror.Message;
returnnull;
}
}
///<summary>
///解密字符串
///</summary>
///<paramname="this.inputString">加了密的字符串</param>
///<paramname="decryptKey">密钥</param>
///<paramname="decryptKey">返回解密后的字符串</param>
publicstringDesDecrypt(stringinputString,stringdecryptKey)
{
byte[]byKey=null;
byte[]IV={0x12,0x34,0x56,0x78,0x90,0xAB,0xCD,0xEF};
byte[]inputByteArray=newByte[inputString.Length];
try
{
byKey=System.Text.Encoding.UTF8.GetBytes(decryptKey.Substring(0,8));
DESCryptoServiceProviderdes=newDESCryptoServiceProvider();
inputByteArray=Convert.FromBase64String(inputString);
MemoryStreamms=newMemoryStream();
CryptoStreamcs=newCryptoStream(ms,des.CreateDecryptor(byKey,IV),CryptoStreamMode.Write);
cs.Write(inputByteArray,0,inputByteArray.Length);
cs.FlushFinalBlock();
System.Text.Encodingencoding=newSystem.Text.UTF8Encoding();
returnencoding.GetString(ms.ToArray());
}
catch(System.Exceptionerror)
{
//returnerror.Message;
returnnull;
}
}
}
}