網路上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("script_ing.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
'私有流程、方法結束--------------------------
'公共方法開始--www.devdao.com------------------------
'''''''''''發送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,"]]>","]]>"))
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 = "無法正確接收資料" & "Descript_ion: " & 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元件,下載位址: 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台不同的伺服器上面進行資料交互,可廣泛應用於各種異質平台。
四、下載地址請到偶的小站,手機主題網查看演示和下載程式包演示地址: http://www.shouji138.com/aspnet2/filemd5.asp
程式下載打包下載: