NSData Sha512 Hashing with Xamarin

116 views Asked by At

I have an example of SHA512 hash of two NSData objects (Objective-C) Objective C SHA512 hash of two NSData that's in objective C, using the CommonCrypto, however I have tried to do the same thing using the SHA512Managed Class but could not get the same results.

PS: I am looking to be able to hash 2 NSData objects not a string.

Is there any way to do it using C#?

What would be the equivalent of CC_SHA512_Update and CC_SHA512_Final for Xamarin.iOS?

2

There are 2 answers

1
Lucas Zhang On

You could create the NSData with the string .

        SHA512 shaM = new SHA512Managed();
        byte[] data = shaM.ComputeHash(Encoding.UTF8.GetBytes(""));

        StringBuilder sBuilder = new StringBuilder();

        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }

        string stringyHash = sBuilder.ToString();

        NSData dataStr = NSData.FromString(stringyHash,NSStringEncoding.UTF8);
0
AISAC On

I think, I've found the answer: To reproduce the same output as the native code mentioned in my question I would use the following method:

   public NSData SHA512HashWithSalt(NSData contentData, NSData saltData)
    {
        HashAlgorithm algorithm = new SHA256Managed();

        //Convert NSData to array of bytes
        byte[] salt = saltData.ToArray();
        byte[] content = contentData.ToArray();

        byte[] plainTextWithSaltBytes =
          new byte[content.Length + salt.Length];

        for (int i = 0; i < content.Length; i++)
        {
            plainTextWithSaltBytes[i] = content[i];
        }
        for (int i = 0; i < salt.Length; i++)
        {
            plainTextWithSaltBytes[content.Length + i] = salt[i];
        }

        return NSData.FromArray(algorithm.ComputeHash(plainTextWithSaltBytes));
    }