Search code examples
.netwindows-phone-8windows-8portable-class-library

Sha256 hash in Portable Library .Net


I need to compute the hash of a byte array in a Portable Library.

I'm trying to find an equivalent of System.Security.Cryptography.SHA256Managed for my Portable library targeting .NET 4.5 + win 8 + WP 8.0 .

I tried the PclContrib but it seems I can't install it for a library targeting those platforms.

Is there any library providing hash algorithms implementations which can be referenced in the context of a Portable Library?

Thanks


Solution

  • You can use this port of Bouncy Castle. AArnott has prepared a PCL Version that is not yet accepted but which might help you. You can also integrate some mono source code directly into yours.

    A Bouncy Castle sample :

            var data = System.Text.Encoding.UTF8.GetBytes("test");
            Org.BouncyCastle.Crypto.Digests.Sha256Digest hash = new Org.BouncyCastle.Crypto.Digests.Sha256Digest();
            hash.BlockUpdate(data, 0,data.Length);
            byte[] result = new byte[hash.GetDigestSize()];
            hash.DoFinal(result, 0);
    

    Update: I do not maintain my original port and I strongly recommend using one the available ones on GitHub such as : https://github.com/onovotny/BouncyCastle-PCL . It supports way more platforms as well.

    Update 2: As of today, I would rather recommend the usage of PCLCrypto. This library is maintained by AArnott (who originally helped me with Bouncy castle PCL support). The main advantage of this library is that, thanks nuget bait and switch, it will use native crypto APIs instead of managed slow and potentially insecured implementations. Complete list of supported Algorithms is available here.

    Update 3: Net Standard based class libraries should now be the answer for most use cases. PCLCrypto seems to remain the best when it comes to Xamarin development.