-2

I need to figure out how to convert the below JavaScript into C#.

CryptoJS.enc.Base64.stringify(CryptoJS.SHA256(myString))

I have tried using the normal go-to methods for converting to SHA256 and then converting to a base64 string, but the output is differnet.

DavidJ
  • 3
  • 1

1 Answers1

-1

I have found my answer using a couple of different threads on this forum. Links in the code.

The main code:

string encoded = Convert.ToBase64String(StringToByteArray(sha256_hash(myString)));

Methods to support this:

        // https://stackoverflow.com/a/321404
        public static byte[] StringToByteArray(string hex)
        {
            return Enumerable.Range(0, hex.Length)
                             .Where(x => x % 2 == 0)
                             .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                             .ToArray();
        }

        // https://stackoverflow.com/a/17001289/16241628
        public static string sha256_hash(String value)
        {
            StringBuilder Sb = new StringBuilder();

            using (SHA256 hash = SHA256Managed.Create())
            {
                Encoding enc = Encoding.UTF8;
                Byte[] result = hash.ComputeHash(enc.GetBytes(value));

                foreach (Byte b in result)
                    Sb.Append(b.ToString("x2"));
            }

            return Sb.ToString();
        }
DavidJ
  • 3
  • 1
  • Hex encoding and decoding is completely unnecessary. The hash can be Base64 encoded directly, significantly shortening the code: `Convert.ToBase64String(SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(myString)))`. – Topaco Dec 02 '21 at 19:38