2012-04-17 18 views
9

Necesito generar un MD5 en mi aplicación.¿Cómo generar MD5 utilizando VBScript en ASP clásico?

He intentado con google pero solo encuentro el código PHP para MD5. Necesito conectarme a un sistema cliente que valide el uso del hash MD5 pero su código está en PHP, el mío está en ASP clásico usando VBScript.

Mi servidor es compatible con .Net, por lo que no puedo usar el script PHP. ¿Existe algún código MD5 para VBScript en ASP clásico?

+0

también: FYI, pero Windows IIS ejecutar código PHP muy bien. Simplemente cree un grupo de aplicaciones diferente con un controlador para el módulo FastCGI. –

+0

posible duplicado de [md5/hash en vb6?] (Http://stackoverflow.com/questions/6579523/md5-hash-on-vb6) –

+0

No no no vb 6 sino script vb en páginas asp? – user1270384

Respuesta

3

No tengo idea si este código funciona, ya que no tengo manera de probarlo. Sin embargo, parece ser lo que estás pidiendo.

http://www.bullzip.com/md5/vb/md5-vb-class.htm

Aquí es un interesante artículo de Jeff Atwood en hashes. Él tiene algunas cosas importantes que decir acerca de MD5:

http://www.codinghorror.com/blog/2012/04/speed-hashing.html

+0

Gracias por leer @camainc, pero realmente no tengo muchas opciones, el sistema con el que me estoy conectando utiliza en gran medida las teclas hash MD5 para autehtication y estos son los requisitos que han dado para conectarlos. Voy a probar el código de bullzip y aconsejar – user1270384

+0

Entiendo ... – camainc

+0

Esto ni siquiera es [etiqueta: vbscript] la implementación es para [etiqueta: vb]. – Lankymart

1

No es código JavaScript que produce una suma de comprobación MD5. Uno de ellos, derivado de la biblioteca de cierre de Google, es available here.

Es bastante fácil producir un Componente de script de Windows desde el Javascript, luego llamar ese componente desde cualquier lenguaje con COM, incluido VB.

Here's a working example.

+0

Gracias, intentaré esto también – user1270384

+0

Estos enlaces parecen estar muertos, fyi –

5

Gracias por todos los enlaces proporcionados anteriormente, fueron útiles, pero este que encontré realmente hizo el trabajo si alguien alguna vez lo necesita. VBScript-MD5

23

actualización 21/02/2017 - Ahora con HMACSHA256 añadido para JWTs

Actualizar 07/05/2016 - Ahora con SHA1 y SHA256 añadido

derecho, para todos de ustedes que han estado luchando con esto (como yo) y quieren saber, ¡es posible!

El siguiente código se divide en varias funciones para que pueda MD5/sha1/sha256 una cadena o un archivo.

Tomé prestadas las funciones GetBytes y BytesToBase64 de otro stackexchange, y el código dentro de stringToUTFBytes se basa en otro stackexchange.

function md5hashBytes(aBytes) 
    Dim MD5 
    set MD5 = CreateObject("System.Security.Cryptography.MD5CryptoServiceProvider") 

    MD5.Initialize() 
    'Note you MUST use computehash_2 to get the correct version of this method, and the bytes MUST be double wrapped in brackets to ensure they get passed in correctly. 
    md5hashBytes = MD5.ComputeHash_2((aBytes)) 
end function 

function sha1hashBytes(aBytes) 
    Dim sha1 
    set sha1 = CreateObject("System.Security.Cryptography.SHA1Managed") 

    sha1.Initialize() 
    'Note you MUST use computehash_2 to get the correct version of this method, and the bytes MUST be double wrapped in brackets to ensure they get passed in correctly. 
    sha1hashBytes = sha1.ComputeHash_2((aBytes)) 
end function 

function sha256hashBytes(aBytes) 
    Dim sha256 
    set sha256 = CreateObject("System.Security.Cryptography.SHA256Managed") 

    sha256.Initialize() 
    'Note you MUST use computehash_2 to get the correct version of this method, and the bytes MUST be double wrapped in brackets to ensure they get passed in correctly. 
    sha256hashBytes = sha256.ComputeHash_2((aBytes)) 
end function 

function sha256HMACBytes(aBytes, aKey) 
    Dim sha256 
    set sha256 = CreateObject("System.Security.Cryptography.HMACSHA256") 

    sha256.Initialize() 
    sha256.key=aKey 
    'Note you MUST use computehash_2 to get the correct version of this method, and the bytes MUST be double wrapped in brackets to ensure they get passed in correctly. 
    sha256HMACBytes = sha256.ComputeHash_2((aBytes)) 
end function 

function stringToUTFBytes(aString) 
    Dim UTF8 
    Set UTF8 = CreateObject("System.Text.UTF8Encoding") 
    stringToUTFBytes = UTF8.GetBytes_4(aString) 
end function 

function bytesToHex(aBytes) 
    dim hexStr, x 
    for x=1 to lenb(aBytes) 
     hexStr= hex(ascb(midb((aBytes),x,1))) 
     if len(hexStr)=1 then hexStr="0" & hexStr 
     bytesToHex=bytesToHex & hexStr 
    next 
end function 

Function BytesToBase64(varBytes) 
    With CreateObject("MSXML2.DomDocument").CreateElement("b64") 
     .dataType = "bin.base64" 
     .nodeTypedValue = varBytes 
     BytesToBase64 = .Text 
    End With 
End Function 

'Special version that produces the URLEncoded variant of Base64 used in JWTs. 
Function BytesToBase64UrlEncode(varBytes) 
    With CreateObject("MSXML2.DomDocument").CreateElement("b64") 
     .dataType = "bin.base64" 
     .nodeTypedValue = varBytes 
     BytesToBase64UrlEncode = replace(replace(replace(replace(replace(.Text,chr(13),""),chr(10),""),"+", "-"),"/", "_"),"=", "") 
    End With 
End Function 

Function GetBytes(sPath) 
    With CreateObject("Adodb.Stream") 
     .Type = 1 ' adTypeBinary 
     .Open 
     .LoadFromFile sPath 
     .Position = 0 
     GetBytes = .Read 
     .Close 
    End With 
End Function 

Estos pueden ser utilizados como sigue:

BytesToBase64(md5hashBytes(stringToUTFBytes("Hello World"))) 

Produce: == sQqNsWTgdUEFt6mb5y4/5Q

bytesToHex(md5hashBytes(stringToUTFBytes("Hello World"))) 

Produce: B10A8DB164E0754105B7A99BE72E3FE5

Para SHA1:

bytesToHex(sha1hashBytes(stringToUTFBytes("Hello World"))) 

Produce: 0A4D55A8D778E5022FAB701977C5D840BBC486D0

Para SHA256:

bytesToHex(sha256hashBytes(stringToUTFBytes("Hello World"))) 

Produce: A591A6D40BF420404A011733CFB7B190D62C65BF0BCDA32B57B277D9AD9F146E

Para obtener el MD5 de un archivo (útil para comprobar Amazon S3 MD5):

BytesToBase64(md5hashBytes(GetBytes(sPath))) 

Donde sPath es el camino a th e archivo local.

Y, por último, para crear un JWT:

'define the JWT header, needs to be converted to UTF bytes: 
aHead=stringToUTFBytes("{""alg"":""HS256"",""typ"":""JWT""}") 

'define the JWT payload, again needs to be converted to UTF Bytes. 
aPayload=stringToUTFBytes("{""sub"":""1234567890"",""name"":""John Doe"",""admin"":true}") 

'Your shared key. 
theKey="mySuperSecret" 

aSigSource=stringToUTFBytes(BytesToBase64UrlEncode(aHead) & "." & BytesToBase64UrlEncode(aPayload)) 

'The full JWT correctly Base 64 URL encoded. 
aJWT=BytesToBase64UrlEncode(aHead) & "." & BytesToBase64UrlEncode(aPayload) & "." & BytesToBase64UrlEncode(sha256HMACBytes(aSigSource,stringToUTFBytes(theKey))) 

que producirá el siguiente JWT válida: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.7ofvtkn0z_pTl6WcqRTxw-4eSE3NqcEq9_3ax0YcuIQ

+3

Mejor respuesta hasta el momento ... Exactamente lo que estaba buscando, excepto que utilicé bytesToHex (md5hashBytes (GetBytes (sPath))) para obtener el valor que necesitaba de los archivos. Excelente compilación de otros trabajos, señor, y la mejor parte es que no se requiere ningún archivo ejecutable o bibliotecas. El MD5 se alinea con sigcheck y otras utilidades ejecutables diferentes. –

+0

Esto es menta. He estado luchando con este por un tiempo. Bien hecho. – GWR

+0

¡Muy bien! Exactamente lo que quería encontrar. Acabo de agregar esta línea WScript.Echo bytesToHex (sha256hashBytes (GetBytes ("la ruta a mi archivo"))) – Magnus

1

En primer lugar, gracias SgtWilko! :)

De acuerdo con su información recopilada, he hecho una función para todos (no para base64/Files).
Su código fue muy útil para mí, pero estaba buscando una función PHP (simple) más parecida para tratar con texto sin formato y con un código más explícito.

Editado:
Basado en el tema How to hash a UTF-8 string in Classic ASP, que vienen con la solución ADODB.Stream. Ahora puede usar caracteres que no sean en inglés.

Editado:
Parámetro PlainText fue cambiado a Objetivo. Ahora puede usar las versiones HMAC.
Simplemente use el parámetro Target como una matriz.

Target(0) = PlainText 
Target(1) = SharedKey 

Gracias de nuevo SgtWilko;)

Announcing the first SHA1 collision (Google Blog Seguridad) de 23 de febrero de, 2017.

Con esta función se puede desmenuzar el texto sin formato en:
MD5, RIPEMD160, SHA1, SHA256, SHA384, SHA512, HMACMD5, HMACRIPEMD160, HMACSHA1, HMACSHA256, HMACSHA384 y HMACSHA512
Si necesita más que pueda encontrarlo en: System.Security.Cryptography Namespace

Function Hash(HashType, Target) 
    On Error Resume Next 

    Dim PlainText 

    If IsArray(Target) = True Then PlainText = Target(0) Else PlainText = Target End If 

    With CreateObject("ADODB.Stream") 
     .Open 
     .CharSet = "Windows-1252" 
     .WriteText PlainText 
     .Position = 0 
     .CharSet = "UTF-8" 
     PlainText = .ReadText 
     .Close 
    End With 

    Set UTF8Encoding = CreateObject("System.Text.UTF8Encoding") 
    Dim PlainTextToBytes, BytesToHashedBytes, HashedBytesToHex 

    PlainTextToBytes = UTF8Encoding.GetBytes_4(PlainText) 

    Select Case HashType 
     Case "md5": Set Cryptography = CreateObject("System.Security.Cryptography.MD5CryptoServiceProvider") '< 64 (collisions found) 
     Case "ripemd160": Set Cryptography = CreateObject("System.Security.Cryptography.RIPEMD160Managed") 
     Case "sha1": Set Cryptography = CreateObject("System.Security.Cryptography.SHA1Managed") '< 80 (collision found) 
     Case "sha256": Set Cryptography = CreateObject("System.Security.Cryptography.SHA256Managed") 
     Case "sha384": Set Cryptography = CreateObject("System.Security.Cryptography.SHA384Managed") 
     Case "sha512": Set Cryptography = CreateObject("System.Security.Cryptography.SHA512Managed") 
     Case "md5HMAC": Set Cryptography = CreateObject("System.Security.Cryptography.HMACMD5") 
     Case "ripemd160HMAC": Set Cryptography = CreateObject("System.Security.Cryptography.HMACRIPEMD160") 
     Case "sha1HMAC": Set Cryptography = CreateObject("System.Security.Cryptography.HMACSHA1") 
     Case "sha256HMAC": Set Cryptography = CreateObject("System.Security.Cryptography.HMACSHA256") 
     Case "sha384HMAC": Set Cryptography = CreateObject("System.Security.Cryptography.HMACSHA384") 
     Case "sha512HMAC": Set Cryptography = CreateObject("System.Security.Cryptography.HMACSHA512") 
    End Select 

    Cryptography.Initialize() 

    If IsArray(Target) = True Then Cryptography.Key = UTF8Encoding.GetBytes_4(Target(1)) 

    BytesToHashedBytes = Cryptography.ComputeHash_2((PlainTextToBytes)) 

    For x = 1 To LenB(BytesToHashedBytes) 
     HashedBytesToHex = HashedBytesToHex & Right("0" & Hex(AscB(MidB(BytesToHashedBytes, x, 1))), 2) 
    Next 

    If Err.Number <> 0 Then Response.Write(Err.Description) Else Hash = LCase(HashedBytesToHex) 

    On Error GoTo 0 
End Function 

Estos pueden ser utilizados de la siguiente manera:

Hash("sha512", "Hello World") 

Produce:
2c74fd17edafd80e8447b0d46741ee243b7eb74dd2149a0ab1b9246fb30382f27e853d8585719e0e67cbda0daa8f51671064615d645ae27acb15bfb1447f459b

Hash("sha256", "Hello World") 

Produce:
a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e

Hash("md5", "muñeca") 

Produce:
ea07bec1f37f4b56ebe368355d1c058f

Hash("sha512HMAC", Array("Hello World", "Shared Key")) 

Produce:
28e72824c48da5a5f14b59246905d2839e7c50e271fc078b1c0a75c89b6a3998746bd8b2dc1764b19d312702cf5e15b38ce799156af28b98ce08b85e4df65b32

+0

Me alegro de poder ayudar. Usted puede ser capaz de obtener en torno al tema UTF-8 mediante el establecimiento de la página de códigos y juegos de caracteres en el archivo ASP: Response.CodePage = 65001 Response.Charset = "UTF-8" y si también establece que en el La sesión asp también interpretará las respuestas correctamente: Session.Codepage = 65001 – SgtWilko