asp获取文件md5值

网上asp加密字符的MD5很多,也很普遍,因为受到asp语言本身的限制,对文件进行md5介绍的文章很少,本文通过2种方式来谈谈如何通过asp获取文件的md5值。

网上asp加密字符的MD5很多,也很普遍,但是对文件进行md5的确很少,因为受到asp语言本身的限制。我们知道字符串的md5可以对明文进行不可逆的加密,从而保证数据储存或者传送的安全性。同样的,对文件进行md5加密也是为了保证在网络传送时不被修改和校验,另外还有一个用途就是在个人站点里面的应用:可以保证上传的图片或文件具有唯一性。原理是,上传到服务器之后,同时在数据库中记录该上传文件的md5值,这样在下次传同样文件的时候,可以通过查询数据库是否是相同的文件,md5值相同,我们就认为它是相同的文件,md5值就是文件的“身份证”,其实百度也有这方面的应用,在百度搜索图片,点开图片后,有时候会出现“您还可以点击以下链接查看到这张图片:XXX网址”,原理也是一样,对文件进行md5。
废话少说,开始正文。
一、asp通过xml交互方式调用.Net程序实现文件md5
asp由于本身语言的限制,无法实现文件的md5,但是.net确可以,那是不是可以通过.net对文件进行md5,然后发送信息给asp接收,这样就可以做到asp的md5了呢,答案是肯定的。这里涉及到asp与.net程序间的交互,我以前写过一个asp的类:《asp处理xml数据的发送、接收类》,可以上我的百度空间看:http://hi.baidu.com/manbutianmi/blog/item/dec182fc6db36587b801a0f6.html,讲的是asp处理xml数据的发送与接收,可用于各种异构系统之间API接口间通讯。本文正好是这个类的一个应用。代码如下:
asp端代码
xmlcls.asp
<%
Rem 处理xml数据的发送、接收类
'--------------------------------------------------
'转载的时候必须保留此版权信息
'作者:walkman
'网址:手机主题网:http://www.shouji138.com
'版本:ver1.0
'--------------------------------------------------
Class XmlClass

Rem 变量定义
Private XmlDoc,XmlHttp
Private MessageCode,SysKey,XmlPath
Private m_GetXmlDoc,m_url
Private m_XmlDocAccept
Rem 初始化
Private Sub Class_Initialize()
On Error Resume Next
MessageCode = ""
XmlPath = ""
Set XmlDoc = Server.CreateObject("msxml2.FreeThreadedDOMDocument.3.0")
XmlDoc.ASYNC = False
End Sub

Rem 销毁对象
Private Sub Class_Terminate()
If IsObject(XmlDoc) Then Set XmlDoc = Nothing
If IsObject(m_XmlDocAccept) Then Set m_XmlDocAccept = Nothing
If IsObject(m_GetXmlDoc) Then Set m_GetXmlDoc = Nothing
End Sub

'公共属性定义开始--------------------------
Rem 错误信息
Public Property Get Message()
Message = MessageCode
End Property

Rem 发送xml的地址
Public Property Let URL(str)
m_url = str
End Property
'公共属性定义结束--------------------------

'私有过程、方法开始--------------------------
Rem 加载xml
Private Sub LoadXmlData()
If XmlPath <> "" Then
If Not XmlDoc.Load(XmlPath) Then
XmlDoc.LoadXml "<?xml version=""1.0"" encoding=""gb2312""?><root/>"
End If
Else
XmlDoc.LoadXml "<?xml version=""1.0"" encoding=""gb2312""?><root/>"
End If
End Sub
Rem 字符转化
Private Function AnsiToUnicode(ByVal str)
Dim i, j, c, i1, i2, u, fs, f, p
AnsiToUnicode = ""
p = ""
For i = 1 To Len(str)
c = Mid(str, i, 1)
j = AscW(c)
If j < 0 Then
j = j + 65536
End If
If j >= 0 And j <= 128 Then
If p = "c" Then
AnsiToUnicode = " " & AnsiToUnicode
p = "e"
End If
AnsiToUnicode = AnsiToUnicode & c
Else
If p = "e" Then
AnsiToUnicode = AnsiToUnicode & " "
p = "c"
End If
AnsiToUnicode = AnsiToUnicode & ("&#" & j & ";")
End If
Next
End Function

Rem 字符转化
Private Function strAnsi2Unicode(asContents)
Dim len1,i,varchar,varasc
strAnsi2Unicode = ""
len1=LenB(asContents)
If len1=0 Then Exit Function
For i=1 to len1
varchar=MidB(asContents,i,1)
varasc=AscB(varchar)
If varasc > 127 Then
If MidB(asContents,i+1,1)<>"" Then
strAnsi2Unicode = strAnsi2Unicode & chr(ascw(midb(asContents,i+1,1) & varchar))
End If
i=i+1
Else
strAnsi2Unicode = strAnsi2Unicode & Chr(varasc)
End If
Next
End Function

Rem 往文件中追加字符
Private Sub WriteStringToFile(filename,str)
On Error Resume Next
Dim fs,ts
Set fs= createobject("scripting.filesystemobject")
If Not IsObject(fs) Then Exit Sub
Set ts=fs.OpenTextFile(Server.MapPath(filename),8,True)
ts.writeline(str)
ts.close
Set ts=Nothing
Set fs=Nothing
End Sub
'私有过程、方法结束--------------------------

'公共方法开始--------------------------

'''''''''''发送xml部分开始
Rem 从外部xml文件填充XmlDoc对象
Public Sub LoadXmlFromFile(path)
XmlPath = Server.MapPath(path)
LoadXmlData()
End Sub

Rem 用字符串填充XmlDoc对象
Public Sub LoadXmlFromString(str)
XmlDoc.LoadXml str
End Sub

Rem 设置node的参数 如 NodeValue "appID",AppID,1,False
'--------------------------------------------------
'参数 :
'NodeName 节点名
'NodeText 值
'NodeType 保存类型 [text=0,cdata=1]
'blnEncode 是否编码 [true,false]
'--------------------------------------------------
Public Sub NodeValue(Byval NodeName,Byval NodeText,Byval NodeType ,Byval blnEncode)
Dim ChildNode,CreateCDATASection
NodeName = Lcase(NodeName)
If XmlDoc.documentElement.selectSingleNode(NodeName) is nothing Then
Set ChildNode = XmlDoc.documentElement.appendChild(XmlDoc.createNode(1,NodeName,""))
Else
Set ChildNode = XmlDoc.documentElement.selectSingleNode(NodeName)
End If
If blnEncode = True Then
NodeText = AnsiToUnicode(NodeText)
End If
If NodeType = 1 Then
ChildNode.Text = ""
Set CreateCDATASection = XmlDoc.createCDATASection(Replace(NodeText,"]]>","]]&gt;"))
ChildNode.appendChild(createCDATASection)
Else
ChildNode.Text = NodeText
End If
End Sub

'--------------------------------------------------
'获取发送包XML中节点的值
'参数 :
'Str 节点名
'--------------------------------------------------
Public Property Get XmlNode(Byval Str)
If XmlDoc.documentElement.selectSingleNode(Str) is Nothing Then
XmlNode = "Null"
Else
XmlNode = XmlDoc.documentElement.selectSingleNode(Str).text
End If
End Property
'--------------------------------------------------
'获取返回XML数据对象
'例:
'当GetXmlData不为NULL时,GetXmlData为XML对象
'--------------------------------------------------
Public Property Get GetXmlData()
Set GetXmlData = m_GetXmlDoc
End Property

'--------------------------------------------------
'发送xml包
'--------------------------------------------------
Public Sub SendHttpData()
Dim i,GetXmlDoc,LoadAppid
Set Xmlhttp = Server.CreateObject("MSXML2.ServerXMLHTTP.3.0")
Set GetXmlDoc = Server.CreateObject("msxml2.FreeThreadedDOMDocument.3.0") ' 返回xml包
XmlHttp.Open "POST", m_url, false
XmlHttp.SetRequestHeader "content-type", "text/xml"
XmlHttp.Send XmlDoc
'Response.Write strAnsi2Unicode(xmlhttp.responseBody)
If GetXmlDoc.load(XmlHttp.responseXML) Then
Set m_GetXmlDoc = GetXmlDoc
Else
MessageCode = "请求数据错误!"
Exit Sub
End If
Set GetXmlDoc = Nothing
Set XmlHttp = Nothing
End Sub

'--------------------------------------------------
'打印发送请求XML数据
'--------------------------------------------------
Public Sub PrintSendXmlData()
Response.Clear
Response.ContentType = "text/xml"
Response.CharSet = "gb2312"
Response.Expires = 0
Response.Write "<?xml version=""1.0"" encoding=""gb2312""?>"&vbNewLine
Response.Write XmlDoc.documentElement.XML
End Sub

'--------------------------------------------------
'打印返回XML数据
'--------------------------------------------------
Public Sub PrintGetXmlData()

Response.Clear
Response.ContentType = "text/xml"
Response.CharSet = "gb2312"
Response.Expires = 0
If IsObject(m_GetXmlDoc) Then
Response.Write "<?xml version=""1.0"" encoding=""gb2312""?>"&vbNewLine
Response.Write m_GetXmlDoc.documentElement.XML
Else
Response.Write "<?xml version=""1.0"" encoding=""gb2312""?><root></root>"
End If
End Sub

Rem 保存发送请求xml数据到文件,文件名为sendxml_日期.txt
Public Sub SaveSendXmlDataToFile()
Dim filename,str
filename = "sendxml_" & DateValue(now) & ".txt"
str = ""
str = str & ""& Now() & vbNewLine
str = str & "---------------------------------------------"& vbNewLine
str = str & "<?xml version=""1.0"" encoding=""gb2312""?>" & vbNewLine
str = str & XmlDoc.documentElement.XML & vbNewLine
str = str & "---------------------------------------------"& vbNewLine
str = str & vbNewLine & vbNewLine & vbNewLine
WriteStringToFile filename,str
End Sub

Rem 保存返回XML数据到文件,文件名为getxml_日期.txt
Public Sub SaveGetXmlDataToFile()
Dim filename,str
filename = "getxml_" & DateValue(now) & ".txt"
str = ""
str = str & ""& Now() & vbNewLine
str = str & "---------------------------------------------"& vbNewLine
If IsObject(m_GetXmlDoc) Then
str = str & "<?xml version=""1.0"" encoding=""gb2312""?>" & vbNewLine
str = str & m_GetXmlDoc.documentElement.XML
Else
str = str & "<?xml version=""1.0"" encoding=""gb2312""?>" & vbNewLine & "<root>" & vbNewLine & "</root>"
End If
str = str & vbNewLine
str = str & "---------------------------------------------"& vbNewLine
str = str & vbNewLine & vbNewLine & vbNewLine
WriteStringToFile filename,str
End Sub

'--------------------------------------------------
'获取返回xml的节点信息
'XmlClassObj.GetSingleNode("//msg")
'--------------------------------------------------
Public Function GetSingleNode(nodestring)
If IsObject(m_GetXmlDoc) Then
GetSingleNode = m_GetXmlDoc.documentElement.selectSingleNode(nodestring).text
Else
GetSingleNode = ""
End If
End Function
''''''''''''''''''发送xml部分结束

''''''''''''''''''接收xml部分开始
'--------------------------------------------------
'接收XML包,错误信息通过Message对象获取
'--------------------------------------------------
Public Function AcceptHttpData()
Dim XMLdom
Set XMLdom = Server.CreateObject("Microsoft.XMLDOM")
XMLdom.Async = False
XMLdom.Load(Request)
If XMLdom.parseError.errorCode <> 0 Then
MessageCode = "不能正确接收数据" & "Description: " & XMLdom.parseError.reason & "<br>Line: " & XMLdom.parseError.Line
Set m_XmlDocAccept = Null
Else
Set m_XmlDocAccept = XMLdom
End If
End Function
'--------------------------------------------------
'返回接收XML包节点信息
'XmlClassObj.GetSingleNode("//msg")
'--------------------------------------------------
Public Function AcceptSingleNode(nodestring)
If IsObject(m_XmlDocAccept) Then
AcceptSingleNode = m_XmlDocAccept.documentElement.selectSingleNode(nodestring).text
Else
AcceptSingleNode = ""
End If
End Function

'--------------------------------------------------
'打印接收端接收到的XML数据
'--------------------------------------------------
Public Sub PrintAcceptXmlData()
Response.Clear
Response.ContentType = "text/xml"
Response.CharSet = "gb2312"
Response.Expires = 0
If IsObject(m_XmlDocAccept) Then
Response.Write "<?xml version=""1.0"" encoding=""gb2312""?>"&vbNewLine
Response.Write m_XmlDocAccept.documentElement.XML
Else
Response.Write "<?xml version=""1.0"" encoding=""gb2312""?><root></root>"
End If
End Sub

Rem 保存接收的XML包数据到文件,文件名为acceptxml_日期.txt
Public Sub SaveAcceptXmlDataToFile()
Dim filename,str
filename = "acceptxml_" & DateValue(now) & ".txt"
str = ""
str = str & ""& Now() & vbNewLine
str = str & "---------------------------------------------"& vbNewLine
If IsObject(m_XmlDocAccept) Then
str = str & "<?xml version=""1.0"" encoding=""gb2312""?>" & vbNewLine
str = str & m_XmlDocAccept.documentElement.XML
Else
str = str & "<?xml version=""1.0"" encoding=""gb2312""?>" & vbNewLine & "<root>" & vbNewLine & "</root>"
End If
str = str & vbNewLine
str = str & "---------------------------------------------"& vbNewLine
str = str & vbNewLine & vbNewLine & vbNewLine
WriteStringToFile filename,str
End Sub

''''''''''''''''''接收xml部分结束
Rem 保存调试数据到文件,文件名为debugnote_日期.txt
Public Sub SaveDebugStringToFile(debugstr)
Dim filename,str
filename = "debugnote_" & DateValue(now) & ".txt"
str = ""
str = str & ""& Now() & vbNewLine
str = str & "---------------------------------------------"& vbNewLine
str = str & debugstr & vbNewLine
str = str & "---------------------------------------------"
str = str & vbNewLine & vbNewLine & vbNewLine
WriteStringToFile filename,str
End Sub
'公共方法结束--------------------------

End Class
%>
filemd5fun.asp
<!--#Include File="xmlcls.asp"-->
<%
Rem 取得文件的md5,参数为文件名
Function GetFileMD5(filename)
Const Apisysno = "k8n6g2b0m1a6b0f6e8" '接口的Key值,防止被非法适用 接口应该保持一致
Dim XmlClassObj
Set XmlClassObj = new XmlClass '创建对象
XmlClassObj.LoadXmlFromString("<?xml version=""1.0"" encoding=""gb2312""?><root/>") '用xml字符填充XMLDOC对象,用来发送xml
XmlClassObj.URL = "http://www.shouji138.com/aspnet2/FileMD5.aspx" '设置响应的url,这里应该改成你的网址

Rem xml格式
Rem "<?xml version="1.0" encoding="gb2312"?>
Rem <root>
Rem <sysno></sysno>
Rem <apiaction></apiaction>
Rem <filename></filename>
Rem </root>

XmlClassObj.NodeValue "sysno",Apisysno,0,False '接口的Key值,防止被非法适用
XmlClassObj.NodeValue "apiaction","createfilemd5",0,False '接口的响应动作,用于定义一个接口用于多种用途
XmlClassObj.NodeValue "filename",filename,0,False '文件路径和文件名,用相对路径
'XmlClassObj.SaveSendXmlDataToFile() '将发送的xml数据库包存入txt文件,用于调试之用
XmlClassObj.SendHttpData() '发送xml数据
'XmlClassObj.SaveGetXmlDataToFile() '保存接收到的xml数据

Rem 处理结果
Dim message,status
status = XmlClassObj.GetSingleNode("//status") '显示状态,如果为OK则表示成功,否则有错误发生
message = XmlClassObj.GetSingleNode("//message") '显示取到的MD5值,如果status不为OK,则message为错误信息
Set XmlClassObj = Nothing
If status = "OK" Then
GetFileMD5 = message
Else
GetFileMD5 = ""
End If
End Function
%>
test.asp
<!--#Include File="filemd5fun.asp"-->
<%
Response.Write "web.config的md5值是:" & GetFileMD5("web.config") & "<br />"
Response.Write "files/logo-yy.gif的md5值是:" & GetFileMD5("files/logo-yy.gif") & "<br />"
Response.Write "xmlcls.asp的md5值是:" & GetFileMD5("xmlcls.asp") & "<br />"
%>

.net端代码:
MD5.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace Winsteps.FileMD5
{
public class MD5
{
public static string md5_hash(string path)
{
try
{
FileStream get_file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
System.Security.Cryptography.MD5CryptoServiceProvider get_md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] hash_byte = get_md5.ComputeHash(get_file);
string resule = System.BitConverter.ToString(hash_byte);
resule = resule.Replace("-", "");
return resule;
}
catch (Exception e)
{
return e.Message;
}
}
}
}
FileMD5.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileMD5.aspx.cs" Inherits="Winsteps.FileMD5.FileMD5" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>手机主题网:http://www.shouji138.com</title>
</head>
<body>
<form id="form1" runat="server">
<div>

</div>
</form>
</body>
</html>
FileMD5.aspx.cs
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.Xml;
using System.Configuration;
namespace Winsteps.FileMD5
{
public partial class FileMD5 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string sysno = "11111";
string status = "False";
string message = "未指定的错误";
string net2sysno = ConfigurationManager.AppSettings["sysno"];
XmlDocument doc = new XmlDocument();
try
{

doc.Load(Request.InputStream);
sysno = doc.SelectSingleNode("//sysno").InnerText.Trim();
if (net2sysno != sysno)
{
message = "非法适用!";
}
else
{
string filename = Server.MapPath(doc.SelectSingleNode("//filename").InnerText.Trim());
message = MD5.md5_hash(filename);
status = "OK";
}
}
catch(Exception ex)
{
message = ex.Message;
}
finally
{
if (doc != null)
doc = null;
}
Response.Clear(); //清楚html字符
Response.ContentType = "text/xml";
Response.Charset = "GB2312";//如果xml字符串中包含中文
Response.Write("<?xml version=\"1.0\" encoding=\"GB2312\"?>");
Response.Write("<root>");
Response.Write(" <status>" + status + "</status>");
Response.Write(" <message>" + message + "</message>");
Response.Write("</root>");
Response.End();
}
}
}

Web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="sysno" value="k8n6g2b0m1a6b0f6e8"></add>
</appSettings>
<system.web>
<httpRuntime executionTimeout="3600" maxRequestLength="1048576"/>
<compilation debug="true" defaultLanguage="c#" />
<customErrors mode="Off" />
<identity impersonate="true"/>
<authentication mode="Forms">
<forms name="forums" path="/" loginUrl="Login.aspx" protection="All" timeout="40">
</forms>
</authentication>
<pages validateRequest="false"></pages>
<globalization requestEncoding="gb2312" responseEncoding="gb2312" culture="zh-CN" uiCulture="zh-CN"/>
</system.web>
</configuration>

web.config的sysno要跟filemd5fun.asp里面的Apisysno保持一致,具体应用时应该要把这个key改成你自己的值来保证安全。
演示地址:http://www.shouji138.com/aspnet2/filemd5.asp
代码虽然长,但是原理简单,asp发送xml数据给asp.net(xml中包含了要md5的文件名)->asp.net接收xml对文件进行md5->asp.net将结果通过xml返回给asp(xml中包含了获取到的md5值)->asp获取返回的xml,解析出md5值。
应用范围:
1. 在两个系统之间传送文件时,可以在传送前进行文件md5,传送后进行文件md5,检查两值是否相等,如果相等则表示在传送过程中没有被修改。
2. 做上传系统中,如果要求不能上传同文件的话,可以在上传之后的文件进行md5存入数据库中,这样下次上传同样文件,则md5会相同,拒绝上传。
3. 在搜索引擎、迅雷本b2b软件中,对文件md5,具有相同md5的文件被认为是相同文件,而不管文件名是否相同,可以从多个源来分享文件。
4. 其他应用。。。。。

二、asp通过COM组件实现md5(需要在服务器上注册组件)
注册一个asp的文件md5组件,下载地址:http://www.shouji138.com/aspnet2/files/aspmd5.rar
然后将PARmf.dll文件拷贝到服务器的c:\WINDOWS\system32目录,运行regsvr32 parmf.dll进行注册,重启IIS。
调用代码:
<%
Set DelphiASPObj = Server.CreateObject("PARmf.md5file")
DelphiASPObj.in_path=Server.Mappath("Web.config") '文件路径
Response.Write "web.config的md5值是:" & DelphiASPObj.get_path_md5 & "<br />"
Set DelphiASPObj=nothing
%>

三、两种方式获取文件md5的对比

第一种方法通过与asp.net程序交互xml数据来得到文件的md5,需要服务器支持asp.net,一般的虚拟主机都提供asp.net环境,但是价格高点;
第二种方法通过注册COM组件实现,需要有服务器的权限,对于拥有服务器的比较合适。
另外第一种方式的这种交互方法使得asp具有更大的灵活性,可以应用在2台不同的服务器上面进行数据交互,可广泛应用于各种异构平台。

上一篇
下一篇