asp.net 字符串加密解密技术
程序员文章站
2024-03-11 22:19:55
复制代码 代码如下:using system; using system.data; using system.configuration; using system.co...
复制代码 代码如下:
using system;
using system.data;
using system.configuration;
using system.collections;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;
using system.text;
using system.security.cryptography;
using system.io;
namespace www
{
public partial class jiami : system.web.ui.page
{
protected void page_load(object sender, eventargs e)
{
bind();
}
private void bind()
{
//加密
this.title = desencrypt("pwd", "abcd1234");
this.title += desdecrypt(this.title, "abcd1234");
response.write(desdecrypt("2ikcw0tqkgo=", "abcd1234"));
}
/// <summary>
/// 加密字符串
/// 注意:密钥必须为8位
/// </summary>
/// <param name="strtext">字符串</param>
/// <param name="encryptkey">密钥</param>
/// <param name="encryptkey">返回加密后的字符串</param>
public string desencrypt(string inputstring, string encryptkey)
{
byte[] bykey = null;
byte[] iv = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };
try
{
bykey = system.text.encoding.utf8.getbytes(encryptkey.substring(0, 8));
descryptoserviceprovider des = new descryptoserviceprovider();
byte[] inputbytearray = encoding.utf8.getbytes(inputstring);
memorystream ms = new memorystream();
cryptostream cs = new cryptostream(ms, des.createencryptor(bykey, iv), cryptostreammode.write);
cs.write(inputbytearray, 0, inputbytearray.length);
cs.flushfinalblock();
return convert.tobase64string(ms.toarray());
}
catch (system.exception error)
{
//return error.message;
return null;
}
}
/// <summary>
/// 解密字符串
/// </summary>
/// <param name="this.inputstring">加了密的字符串</param>
/// <param name="decryptkey">密钥</param>
/// <param name="decryptkey">返回解密后的字符串</param>
public string desdecrypt(string inputstring, string decryptkey)
{
byte[] bykey = null;
byte[] iv = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };
byte[] inputbytearray = new byte[inputstring.length];
try
{
bykey = system.text.encoding.utf8.getbytes(decryptkey.substring(0, 8));
descryptoserviceprovider des = new descryptoserviceprovider();
inputbytearray = convert.frombase64string(inputstring);
memorystream ms = new memorystream();
cryptostream cs = new cryptostream(ms, des.createdecryptor(bykey, iv), cryptostreammode.write);
cs.write(inputbytearray, 0, inputbytearray.length);
cs.flushfinalblock();
system.text.encoding encoding = new system.text.utf8encoding();
return encoding.getstring(ms.toarray());
}
catch (system.exception error)
{
//return error.message;
return null;
}
}
}
}