VB中实现MD5加密[3]

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 bucher 的 blog

public function digestfiletohexstr(filename as string) as string
    open filename for binary access read as #1
    md5init
    do while not eof(1)
        get #1, , bytebuffer
        if loc(1) < lof(1) then
            bytecounter = bytecounter + 64
            md5transform bytebuffer
        end if
    loop
    bytecounter = bytecounter + (lof(1) mod 64)
    close #1
    md5final
    digestfiletohexstr = getvalues
end function

'
' function to digest a text string and output the result as a string
' of hexadecimal characters.
'
public function digeststrtohexstr(sourcestring as string) as string
    md5init
    md5update len(sourcestring), stringtoarray(sourcestring)
    md5final
    digeststrtohexstr = getvalues
end function

'
' a utility function which converts a string into an array of
' bytes.
'
private function stringtoarray(instring as string) as byte()
    dim i as integer
    dim bytbuffer() as byte
    redim bytbuffer(len(instring))
    for i = 0 to len(instring) - 1
        bytbuffer(i) = asc(mid(instring, i + 1, 1))
    next i
    stringtoarray = bytbuffer
end function

'
' concatenate the four state vaules into one string
'
public function getvalues() as string
    getvalues = longtostring(state(1)) & longtostring(state(2)) & longtostring(state(3)) & longtostring(state(4))
end function

'
' convert a long to a hex string
'
private function longtostring(num as long) as string
        dim a as byte
        dim b as byte
        dim c as byte
        dim d as byte
       
        a = num and &hff&
        if a < 16 then
            longtostring = "0" & hex(a)
        else
            longtostring = hex(a)
        end if
              
        b = (num and &hff00&) \ 256
        if b < 16 then
            longtostring = longtostring & "0" & hex(b)
        else
            longtostring = longtostring & hex(b)
        end if
       
        c = (num and &hff0000) \ 65536
        if c < 16 then
            longtostring = longtostring & "0" & hex(c)
        else
            longtostring = longtostring & hex(c)
        end if
      
        if num < 0 then
            d = ((num and &h7f000000) \ 16777216) or &h80&
        else
            d = (num and &hff000000) \ 16777216
        end if
       
        if d < 16 then
            longtostring = longtostring & "0" & hex(d)
        else
            longtostring = longtostring & hex(d)
        end if
   
end function

'
' initialize the class
'   this must be called before a digest calculation is started
'

本文关键:MD5,VB6
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top