Replicating PHP’s sha1() in VBScript
The reason I wanted to do this will become obvious at a later date, but for now I wanted to get this little script up on its own because I wasn’t able to find a complete solution when I went looking for it.
The following code replicates the basic functionality of the sha1() function in PHP:
Option Explicit Dim asc, enc, bytes, instr, outstr, pos instr = "test string" 'Borrow some objects from .NET (supported from 1.1 onwards) Set asc = CreateObject("System.Text.UTF8Encoding") Set enc = CreateObject("System.Security.Cryptography.SHA1CryptoServiceProvider") 'Convert the string to a byte array and hash it bytes = asc.GetBytes_4(instr) bytes = enc.ComputeHash_2((bytes)) outstr = "" 'Convert the byte array to a hex string For pos = 1 To Lenb(bytes) outstr = outstr & LCase(Right("0" & Hex(Ascb(Midb(bytes, pos, 1))), 2)) Next WScript.Echo outstr
As you can see from the comments, this essentially cheats by borrowing some COM objects from .NET to do the hard work. These classes are available from .NET 1.0 onwards, so should run on Windows Server 2003 SP2 and later out of the box. I’m not 100% sure about a Server Core install of 2008, but it worked on a Server Core install of 2008 R2.
If you want the raw output instead of the hex string, simply output the bytes variable and omit lines 15-20.
Caveat: This code works for UTF-8 strings. I haven’t tested PHPs sha1() function with Unicode, but in theory you should only have to substitute UTF8Encoding for UnicodeEncoding on line 8.
Bonus: You can replicate the md5() function with the same code, but substitute SHA1CryptoServiceProvider for MD5CryptoServiceProvider on line 9. Unfortunately, the same trick doesn’t work for the newer hash algorithms in .NET such as SHA256 or SHA512.