What would be the best and/or easiest way to calculate a hash in B4A, compatible with C# code ?
There is of course the encryption librray which contains amongst others, the calculation of an MD5 hash... Is the outcome compatible with the same in .NET ?
Yes, it is compatible. What hash do you want to calculate?
You will need the MAC object (encryption library) to do that.
EDIT: Didnt see you wanted an MD5 hash.
B4X:
Dim md as MessageDigest
Dim hash() as Byte
hash = md.GetMessageDigest(data.GetBytes("UTF8"),"MD5")
Dim hashstring As String
Dim su As StringUtils
hashstring = su.EncodeBase64(hash)
What do you want to use the hash for? There are many hash functions of varying complexity. Cryptographic hash functions have quite a high overhead as they are designed for security and a very low probability of two different messages generating the same hash. Simple hash functions for string comparison just use a combination of prime numbers. They are far faster but have a far higher chance of two strings generating the same hash.
A simple hash function:
B4X:
Sub Generate_Hash(Hashit As String)
Dim Prime As Long : Prime = 1125899906842597
Dim cntr As Int
Dim ReturnHash As Long
Dim c As Char
For cntr = 0 To Hashit.Length - 1
ReturnHash = 31*Prime + Asc(Hashit.CharAt(cntr))
Next
Return ReturnHash
End Sub
Hi all,
I indeed need it for security reasons (salting).
In a scenario where an Android app needs to authenticate on a C# server.
How ?
- app connects and sends the userID to the server
- the server responds with a random number
- app concatenates the users password with this number and calculates the hash
- app sends this hash to the server
- the server does the same calculation and compares its value with what it received from the server
Just a quick feedback: I tested the MD5 calculation in C# and B4A and they produce the same result.
For anyone interested:
C# code:
B4X:
string text = "Hello world";
byte[] bs = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(System.Text.Encoding.UTF8.GetBytes(text));
String encrypted = Convert.ToBase64String(bs);
B4A code (using the ByteConverter and Encryption libraries):
B4X:
Dim bc As ByteConverter
Dim b64 As Base64
Dim md As MessageDigest
Dim data() As Byte
Dim encrypted() As Byte
data = bc.StringToBytes("Hello world", "utf-8")
encrypted = md.GetMessageDigest(data, "MD5")
ToastMessageShow(b64.EncodeBtoS(encrypted, 0, encrypted.Length), True)