Hash et CSharp

De Banane Atomic
Révision datée du 18 mai 2015 à 15:21 par Nicolas (discussion | contributions) (→‎String to Bit array)
(diff) ← Version précédente | Voir la version actuelle (diff) | Version suivante → (diff)
Aller à la navigationAller à la recherche

Comparaison

Csharp.svg
byte[] hash = null;
using (SHA512 shaM = new SHA512Managed())
{
    hash = shaM.ComputeHash(Encoding.UTF8.GetBytes("password"));
}

var hashString = BitConverter.ToString(hash).Replace("-","");
if (hashString == "hash")

Bit array to String

Csharp.svg
byte[] hash;
string s = BitConverter.ToString(hash).Replace("-", "");

var sb = new StringBuilder(hash.Length * 2);
foreach (byte b in hash)
{
    sb.AppendFormat("{0:x2}", b);
}
string s = sb.ToString();

String to Bit array

Csharp.svg
string s;
byte[] bytes = Encoding.UTF8.GetBytes(s);

int nbChars = s.Length;
byte[] bytes = new byte[nbChars / 2];
for (int i = 0; i < nbChars; i += 2)
{
    bytes[i / 2] = Convert.ToByte(s.Substring(i, 2), 16);
}