Hi,
I am new to Xojo, just checking it out and sharing successful founds!
One of my most important needs is to be able to hash and do crypto in XOJO that ends being compatible with VB.net and PHP.
I have the following function in VB.Net:
Function Hash_a_String(ByVal StringToHash As String) As String
Dim algorithm As SHA256 = SHA256.Create
Dim hash As Byte() = (algorithm.ComputeHash(Encoding.UTF8.GetBytes(StringToHash)))
Return Convert.ToBase64String(hash)
End Function
and I have the following code in Xojo to match it:
Dim hashedString As String
hashedString = Crypto.SHA256(StringToHash)
hashedString = hashedString.ConvertEncoding(Encodings.UTF8)
hashedString = EncodeBase64(hashedString)
Return hashedString
Which also match the following PHP code:
base64_encode(hash('sha256',$StringToHash,true));
I hope it helps somebody!
Criticism is always accepted and welcome!
You need to convert the Encoding before you put it in the Sha256, not after. Else you have unreliable result which only matches the VB code by luck if you actually passed in UTF8 string.
Your VB code is correctly ensuring the Encoding before the Hash.
PHP produces a string encoded in hex. You can either use the second parameter in the php function to produce a binary value instead, but most people prefer to use EncodeHex on the Xojo output to match the PHP output.
Edit, never mind, I see youre using Base64. In that case, you definitely want to use the $raw_output parameter of the php function.
Edit 2: Like you are… because this isnt a question this is a tip. Wow, Im shutting up.
Hi Björn Eiríksson ,
I have fixed it. Thank you so much! I just overlook that, not sure why!!
The Xojo function ended looking like this:
Dim hashedString As String
hashedString = Crypto.SHA256(StringToHash.ConvertEncoding(Encodings.UTF8))
hashedString = EncodeBase64(hashedString)
Return hashedString
Again I am just posting tips for anybody wanting to have hashing functionalities that produce the same output in VB.Net, PHP and Xojo. Cheers!