17

I've got a ASP.NET 5 RC1 (soon to be ASP.NET Core) Web Application project.

It needs to compute SHA1 hashes.

Various SHA1 subclasses are available and build under DNX 4.5.1, but there doesn't seem to be any available implementation under DNX Core 5.0.

Do I have to add a reference to bring that code in, or is it simply not available for .NET Core yet?

According to this article:

.NET Core consists of a set of libraries, called “CoreFX”, and a small, optimized runtime, called “CoreCLR”.

Sure enough, in the CoreFX repo, there are no subclasses of SHA1:

https://github.com/dotnet/corefx/tree/master/src/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography

However in CoreCLR the subclasses are there as you'd expect, within mscorlib:

https://github.com/dotnet/coreclr/tree/43b39a73cbf832ec13ec29ed356cb75834e7a8d7/src/mscorlib/src/System/Security/Cryptography

Why is there overlap between coreclr and corefx? Is this mscorlib code not available for .NET Core projects?

The description of the System.Security.Crytpography.Algorithms package on NuGet says:

Provides base types for cryptographic algorithms, including hashing, encryption, and signing operations.

Is there another package that includes actual algorithms and not just base classes? Is this something that simply hasn't been ported yet? Is there somewhere you can review the status of APIs and a roadmap, as Mono has?

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
  • 1
    CoreCLR is the Core runtime while CoreFX are the libraries. If SHA1 is part of the *runtime* itself, you should be able to use it. Have you tried creating implementations of the algorithm through the factory methods? – Panagiotis Kanavos Feb 12 '16 at 13:40
  • @PanagiotisKanavos, hehe, completely missed the factory method (despite linking to it). With that, my code compiles. If you'd like to post that as an answer, I'll accept it. – Drew Noakes Feb 12 '16 at 13:49

2 Answers2

38

Add the System.Security.Cryptography.Algorithms nuget package.

Then

var sha1 = System.Security.Cryptography.SHA1.Create();

var hash = sha1.ComputeHash(myByteArray)
blowdart
  • 55,577
  • 12
  • 114
  • 149
  • At the time of the comment, SHA1 is IDisposable and shoud be disposed with the using keyword: "using var sha1 = System.Security.Cryptography.SHA1.Create();" – Daniel Genezini Feb 01 '23 at 10:34
1

string form of Sha1

using System.Security.Cryptography;
using System.Text;

public static string Sha1(string input)
{
    using var sha1 = SHA1.Create();
    var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input));
    var sb = new StringBuilder(hash.Length * 2);

    foreach (byte b in hash)
    {
        sb.Append(b.ToString("x2"));
    }
    return sb.ToString();
}
erandac
  • 575
  • 5
  • 8