日期:2009-10-21  浏览次数:20388 次

在我的编程实践中,需要从.NET的Web Form页面传递加密的字符串信息(如用户名和密码等)到ASP页面,然后在该页面对该加密字符串进行解密。如果传递的不是加密串,通过GET或POST的方式就可以直接传递并在ASP页面中接收,但问题是在.NET的Web Form页面中加了密的字符串如何才能在ASP中进行解密呢?这主要由于ASP并不能直接访问由.NET提供的托管类和组件。这时我们就只能借助于COM组件来实现了,通过COM的互操作我们可通过.NET生成COM组件,然后在ASP页面中访问该COM组件就可以了。



本文实现的是将加密的用户名与密码从.ASPx页面传递到.ASP页面,下面就来介绍这些操作的具体步骤:



一、制作具有加密、解密字符串的.NET程序集(VS.NET类库工程)

这个程序集将会变成COM组件,使用DES对称加密代码,可以加密码,可以加密解密,支持中文!

//文件名:StringCrypt.cs

using System;

using System.Runtime.InteropServices;

using System.Security.Cryptography;

using System.IO;

using System.Text;



namespace jonson

{

// 首先建立接口,这个是Com必须使用的

[Guid("BF6F9C17-37FA-4ad9-9601-C11AD5316F2C")]

public interface IEncrypt

{

string Encrypt(string pToEncrypt,string sKey);

string Decrypt(string pToDecrypt,string sKey);

}



//接口的实现

[Guid("3FBDBB63-3C36-4602-89E1-73EDB0F167D0")]

public class StringCrypt : IEncrypt

{

// 加密的方法

public string Encrypt(string pToEncrypt, string sKey)

{

DESCryptoServiceProvider des = new DESCryptoServiceProvider();

//把字符串放到byte数组中

byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);

//byte[] inputByteArray=Encoding.Unicode.GetBytes(pToEncrypt);



//建立加密对象的密钥和偏移量

//原文使用ASCIIEncoding.ASCII方法的GetBytes方法

//使得输入密码必须输入英文文本

des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);

des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

MemoryStream ms = new MemoryStream();

CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(),CryptoStreamMode.Write);

//Write the byte array into the crypto stream

//(It will end up in the memory stream)

cs.Write(inputByteArray, 0, inputByteArray.Length);

cs.FlushFinalBlock();

//Get the data back from the memory stream, and into a string

StringBuilder ret = new StringBuilder();

foreach(byte b in ms.ToArray())

{

//Format as hex

ret.AppendFormat("{0:X2}", b);

}

ret.ToString();

return ret.ToString();

}



// 解密的方法

public string Decrypt(string pToDecrypt, string sKey)

{

DESCryptoServiceProvider des = new DESCryptoServiceProvider();



//Put the input string into the byte array

byte[] inputByteArray = new byte[pToDecrypt.Length / 2];

for(int x = 0; x < pToDecrypt.Length / 2; x++)

{

int i = (Convert.ToInt32(pToDecrypt.Substr