There are many MD5s for ASP encrypted characters on the Internet, and they are very common, but MD5 for files is indeed very rare because of the limitations of the ASP language itself. We know that md5 of a string can irreversibly encrypt plain text to ensure the security of data storage or transmission. Similarly, md5 encryption of files is also used to ensure that they are not modified and verified during network transmission. Another use is in personal sites: it can ensure that the uploaded pictures or files are unique. The principle is that after uploading to the server, the md5 value of the uploaded file is recorded in the database at the same time. In this way, the next time the same file is uploaded, we can query the database to see if it is the same file. If the md5 value is the same, we will consider it to be the same. For files, the md5 value is the "ID card" of the file. In fact, Baidu also has applications in this area. After searching for pictures on Baidu and clicking on the picture, sometimes "You can also click on the following link to view this picture: XXX URL" , the principle is the same, md5 the file.
Without further ado, let’s get started.
1. asp calls .Net program through xml interactive mode to implement file md5
Due to the limitations of its own language, asp cannot implement md5 of files, but .net can indeed do it. Is it possible to perform md5 on the file through .net, and then send the information to asp to receive it, so that the md5 of asp can be achieved? Answer That's for sure. This involves the interaction between ASP and .NET programs. I have written an ASP class before: "ASP Processing XML Data Sending and Receiving Classes". You can view it on my Baidu space: http://hi.baidu.com /manbutianmi/blog/item/dec182fc6db36587b801a0f6.html is about asp processing of sending and receiving xml data, and can be used for communication between API interfaces between various heterogeneous systems. This article happens to be an application of this class. The code is as follows:
asp side code
xmlcls.asp
<%
Rem handles sending and receiving classes of xml data
'------------------------------------------------ -
'This copyright information must be retained when reprinting
'Author: walkman
'Website: Mobile Theme Network: http://www.shouji138.com
'Version: ver1.0
'------------------------------------------------ -
ClassXmlClass
Rem variable definition
Private XmlDoc,XmlHttp
Private MessageCode,SysKey,XmlPath
Private m_GetXmlDoc,m_url
Private m_XmlDocAccept
Rem initialization
Private Sub Class_Initialize()
On Error Resume Next
MessageCode = ""
XmlPath = ""
Set XmlDoc = Server.CreateObject("msxml2.FreeThreadedDOMDocument.3.0")
XmlDoc.ASYNC = False
End Sub
Rem destroys the object
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
'Public attribute definition starts--------------------------
Rem error message
Public Property Get Message()
Message = MessageCode
End Property
Rem the address to send xml to
Public Property Let URL(str)
m_url = str
End Property
'End of public attribute definition--------------------------
'Private process and method start--------------------------
Rem load 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 character conversion
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 character conversion
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 appends characters to the file
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
'Private process and method end--------------------------
'Public method starts--www.devdao.com------------------------
''''''''''' Send the xml part to start
Rem populate XmlDoc object from external xml file
Public Sub LoadXmlFromFile(path)
XmlPath = Server.MapPath(path)
LoadXmlData()
End Sub
Rem fill XmlDoc object with string
Public Sub LoadXmlFromString(str)
XmlDoc.LoadXml str
End Sub
Rem sets node parameters such as NodeValue "appID",AppID,1,False
'------------------------------------------------ -
'parameter:
'NodeName node name
'NodeText value
'NodeType save type [text=0,cdata=1]
'blnEncode whether to encode [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
'------------------------------------------------ -
'Get the value of the node in the sent packet XML
'parameter:
'Str node name
'------------------------------------------------ -
Public Property GetXmlNode(ByvalStr)
If XmlDoc.documentElement.selectSingleNode(Str) is Nothing Then
XmlNode = "Null"
Else
XmlNode = XmlDoc.documentElement.selectSingleNode(Str).text
End If
End Property
'------------------------------------------------- ---
'Get the returned XML data object
'example:
'When GetXmlData is not NULL, GetXmlData is an XML object
'------------------------------------------------ -
Public Property Get GetXmlData()
Set GetXmlData = m_GetXmlDoc
End Property
'------------------------------------------------ -
'Send xml package
'------------------------------------------------ -
Public Sub SendHttpData()
Dim i,GetXmlDoc,LoadAppid
Set Xmlhttp = Server.CreateObject("MSXML2.ServerXMLHTTP.3.0")
Set GetXmlDoc = Server.CreateObject("msxml2.FreeThreadedDOMDocument.3.0") ' Return xml package
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 = "Error in requesting data!"
Exit Sub
End If
Set GetXmlDoc = Nothing
Set XmlHttp = Nothing
End Sub
'------------------------------------------------ -
'Print send request XML data
'------------------------------------------------ -
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
'------------------------------------------------ -
'Print returned XML data
'------------------------------------------------ -
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 saves the send request xml data to a file named sendxml_date.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 saves the returned XML data to a file named getxml_date.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
'------------------------------------------------ -
'Get the node information of the returned 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
''''''''''''''''''End of sending xml part
''''''''''''''''''The receiving xml part starts
'------------------------------------------------ -
'Receive XML package, error information is obtained through Message object
'------------------------------------------------ -
Public Function AcceptHttpData()
Dim XMLdom
Set XMLdom = Server.CreateObject("Microsoft.XMLDOM")
XMLdom.Async = False
XMLdom.Load(Request)
If XMLdom.parseError.errorCode <> 0 Then
MessageCode = "Unable to receive data correctly" & "Descript_ion: " & XMLdom.parseError.reason & "<br>Line: " & XMLdom.parseError.Line
Set m_XmlDocAccept = Null
Else
Set m_XmlDocAccept = XMLdom
End If
End Function
'------------------------------------------------- ---
'Return to receive XML package node information
'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
'------------------------------------------------ -
'Print the XML data received by the receiving end
'------------------------------------------------ -
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 saves the received XML packet data to a file named acceptxml_date.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
''''''''''''''''''Receive the xml part and end
Rem. Save the debugging data to a file named debugnote_date.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
'Public method ends--------------------------
End Class
%>
filemd5fun.asp
<!--#Include File="xmlcls.asp"-->
<%
Rem gets the md5 of the file, the parameter is the file name
Function GetFileMD5(filename)
Const Apisysno = "k8n6g2b0m1a6b0f6e8" 'The Key value of the interface should be consistent to prevent illegal application of the interface
DimXmlClassObj
Set XmlClassObj = new XmlClass 'Create object
XmlClassObj.LoadXmlFromString("<?xml version=""1.0"" encoding=""gb2312""?><root/>") 'Fill the XMLDOC object with xml characters and use it to send xml
XmlClassObj.URL = " http://www.shouji138.com/aspnet2/FileMD5.aspx " 'Set the response url, which should be changed to your URL
Rem xml format
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 value of the interface to prevent illegal application
XmlClassObj.NodeValue "apiaction","createfilemd5",0,False 'Response action of the interface, used to define an interface for multiple purposes
XmlClassObj.NodeValue "filename",filename,0,False 'File path and file name, use relative
path'XmlClassObj.SaveSendXmlDataToFile() 'Save the sent xml database package into a txt file for debugging purposes
XmlClassObj.SendHttpData() 'Send xml data
'XmlClassObj.SaveGetXmlDataToFile() 'Save the received xml data
Rem processing result
Dim message, status
status = XmlClassObj.GetSingleNode("//status") 'Display status, if it is OK, it means success, otherwise an error occurs
message = XmlClassObj.GetSingleNode("//message") 'Display the MD5 value obtained. If the status is not OK, the message is an error message
Set XmlClassObj = Nothing
If status = "OK" Then
GetFileMD5 = message
Else
GetFileMD5 = ""
End If
End Function
%>
test.asp
<!--#Include File="filemd5fun.asp"-->
<%
Response.Write "The md5 value of web.config is:" & GetFileMD5("web.config") & "<br />"
Response.Write "The md5 value of files/logo-yy.gif is:" & GetFileMD5("files/logo-yy.gif") & "<br />"
Response.Write "The md5 value of xmlcls.asp is:" & GetFileMD5("xmlcls.asp") & "<br />"
%>
.net side code:
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 result;
}
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>Mobile theme website: 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 = "Unspecified error";
string net2sysno = ConfigurationManager.AppSettings["sysno"];
XmlDocument doc = new XmlDocument();
try
{
doc.Load(Request.InputStream);
sysno = doc.SelectSingleNode("//sysno").InnerText.Trim();
if (net2sysno != sysno)
{
message = "Illegal application!";
}
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(); //Clear html characters
Response.ContentType = "text/xml";
Response.Charset = "GB2312";//If the xml string contains Chinese
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>
The sysno of web.config should be consistent with the Apisysno in filemd5fun.asp. During specific application, you should change this key to your own value to ensure security.
Demo address: http://www.shouji138.com/aspnet2/filemd5.asp
Although the code is long, the principle is simple. ASP sends xml data to asp.net (the xml contains the file name to be md5) -> asp.net receives the xml and performs md5 on the file -> asp.net returns the result to asp through xml (The xml contains the obtained md5 value)->asp obtains the returned xml and parses out the md5 value.
Application scope:
1. When transferring files between two systems, you can perform file md5 before transmission and file md5 after transmission to check whether the two values are equal. If they are equal, it means that they have not been modified during the transmission process.
2. In the upload system, if it is required that the same file cannot be uploaded, the md5 of the uploaded file can be stored in the database. In this way, if the same file is uploaded next time, the md5 will be the same and the upload will be refused.
3. In search engines and Xunlei b2b software, for file md5, files with the same md5 are considered to be the same file, regardless of whether the file names are the same, and files can be shared from multiple sources.
4. Other applications. . . . .
2. asp implements md5 through COM components (the component needs to be registered on the server)
to register an asp file md5 component, download address: DelphiASPObj.in_path=Server.Mappath("Web.config") 'File path
Response.Write "The md5 value of web.config is:" & DelphiASPObj.get_path_md5 & "<br />"
Set DelphiASPObj=nothing
%>
3. Comparison of two ways to obtain file md5.
The first method is to obtain the md5 of the file by interacting with xml data with the asp.net program. The server needs to support asp.net. General virtual hosts provide an asp.net environment, but The price is higher;
The second method is implemented by registering COM components, which requires server permissions and is more suitable for those who own a server.
In addition, the first method of interaction makes ASP more flexible and can be used on two different servers for data interaction, and can be widely used on various heterogeneous platforms.
4. For the download address, please go to my website and mobile theme network to view the demo and download the program package demo address: http://www.shouji138.com/aspnet2/filemd5.asp
Program download package download: