How to hash a UTF-8 string in Classic ASP

后端 未结 6 2023
终归单人心
终归单人心 2021-01-15 19:33

I\'ve been looking for a Classic ASP script that allows me to hash a string using the MD5 algorithm. I need to match this hashed string against the same string in an ASP.NET

6条回答
  •  醉话见心
    2021-01-15 19:50

    With this function you can hash the plain text into:
    SHA1, SHA256, SHA384, SHA512, MD5, RIPEMD160
    If you need more you can find it in: System.Security.Cryptography Namespace

    Function Hash(HashType, PlainText)
        On Error Resume Next
    
        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 "sha1": Set Cryptography = CreateObject("System.Security.Cryptography.SHA1Managed")
            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 "md5": Set Cryptography = CreateObject("System.Security.Cryptography.MD5CryptoServiceProvider")
            Case "ripemd160": Set Cryptography = CreateObject("System.Security.Cryptography.RIPEMD160Managed")
        End Select
    
        Cryptography.Initialize()
        BytesToHashedBytes = Cryptography.ComputeHash_2((PlainTextToBytes))
    
        For x = 1 To LenB(BytesToHashedBytes)
            HashedBytesToHex = HashedBytesToHex & Right("0" & Hex(AscB(MidB(BytesToHashedBytes, x, 1))), 2)
        Next
    
        Hash = LCase(HashedBytesToHex)
    
        If Err.Number <> 0 Then Response.Write(Err.Description)
    
        On Error GoTo 0
    End Function
    

    These can be used as follows:

    Hash("sha512", "Hello World")
    

    Produces:
    2c74fd17edafd80e8447b0d46741ee243b7eb74dd2149a0ab1b9246fb30382f27e853d8585719e0e67cbda0daa8f51671064615d645ae27acb15bfb1447f459b

    Hash("sha256", "Hello World")
    

    Produces:
    a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e

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

    Produces:
    ea07bec1f37f4b56ebe368355d1c058f

提交回复
热议问题