Wolle
Wolle

Reputation: 33

C# SRI Hash Generator

I would like to create a C#-function, that generates a valid SRI Hash of an url. Look here for more information: https://www.srihash.org/

All examples I have found uses OpenSSL, like "openssl dgst -sha384 -binary FILENAME.js | openssl base64 -A" but I would like to do it using C#.

I have tried with the following code, but it doesn't seem right, when I compare the results with srihash.org:

string url = "https://code.jquery.com/jquery-3.5.1.js";
string source;

using (WebClient client = new WebClient())
{
    source = client.DownloadString(url);
}

using (SHA384 sha384Hash = SHA384.Create())
{
    //From String to byte array
    byte[] sourceBytes = Encoding.UTF8.GetBytes(source);
    byte[] hashBytes = sha384Hash.ComputeHash(sourceBytes);
    string hash = BitConverter.ToString(hashBytes).Replace("-", String.Empty);

    Console.WriteLine("The SHA384 hash of " + source + " is: " + hash);
    Console.ReadLine();
}

Upvotes: 0

Views: 825

Answers (1)

Wolle
Wolle

Reputation: 33

I found a solution.

This works:

string url = "https://code.jquery.com/jquery-3.5.1.js";

var fs = new MemoryStream(new WebClient().DownloadData(url));
using (SHA384 sha384Hash = SHA384.Create())
{
    Console.WriteLine("The SHA384 hash is " + Convert.ToBase64String(sha384Hash.ComputeHash(fs)));
    Console.ReadLine();
}

Upvotes: 2

Related Questions