Ernesto Rodriguez
Ernesto Rodriguez

Reputation: 267

SHA 256 from Java to C#

I´m trying to create the equivalent code from Java to C# for the function below:

public static String SHA256 (List<String> parametros, String clave) 

{
try {
    MessageDigest sha = MessageDigest.getInstance("SHA-256");
    for(String param:parametros){
        byte p[] = new byte[param.length()];
        p = param.getBytes();
        sha.update(p);
    }
    byte bClave[] = new byte[clave.length()];
    bClave = clave.getBytes();
    byte[] hash = sha.digest(bClave);
    return ( hexString256 (hash));
   }catch (NoSuchAlgorithmException e){
   return ("Error");
  }
}

Any suggestions for the sha.update(p); line?

Upvotes: 2

Views: 4280

Answers (1)

Volkan Paksoy
Volkan Paksoy

Reputation: 6967

If it's just about calculating SHA-256 hash of some data maybe this would give some idea:

// using System.Security.Cryptography;
public static string ComputeHashSha256(byte[] toBeHashed)
{
    using (var sha256 = SHA256.Create())
    {
        return Encoding.UTF8.GetString(sha256.ComputeHash(toBeHashed));
    }
}

UPDATE:

If the goal is to compute hash of a list strings after concatenating them you can use an additional method like (or combine them both in a single one if you wish):

public static string ComputeSHA256HashOfAListOfStrings(List<string> parameters)
{
    var concatted = string.Join(string.Empty, parameters);
    var byteOfConcattedString = Encoding.UTF8.GetBytes(concatted);
    return ComputeHashSha256(byteOfConcattedString);
}

Please note I just meant this sample to be a pointer for you because I don't exactly know what the Java code above does but I hope it helps a bit.

Upvotes: 3

Related Questions