2012-08-03 2 views
1

Nous avons un service web python. Il a besoin d'un hachage comme paramètre. Le hachage en python est généré de cette façon.Python hmac et C# hmac

hashed_data = hmac.new("ant", "bat", hashlib.sha1) 
    print hashed_data.hexdigest() 

Maintenant, voici comment générer le hachage à partir de C#.

ASCIIEncoding encoder = new ASCIIEncoding(); 
    Byte[] code = encoder.GetBytes("ant"); 
    HMACSHA1 hmSha1 = new HMACSHA1(code); 
    Byte[] hashMe = encoder.GetBytes("bat"); 
    Byte[] hmBytes = hmSha1.ComputeHash(hashMe); 
    Console.WriteLine(Convert.ToBase64String(hmBytes)); 

Cependant, je vais sortir avec un résultat différent.

Dois-je changer l'ordre du hachage?

Merci,

Jon

Répondre

11

Pour imprimer le résultat:

  • En Python que vous utilisez: .hexdigest()
  • En C# que vous utilisez: Convert.ToBase64String

Ces 2 fonctions ne font pas la même chose du tout. Le code hexadécimal de Python convertit simplement le tableau d'octets en chaîne hexadécimale, tandis que la méthode C# utilise le codage Base64 pour convertir le tableau d'octets. Donc, pour obtenir le même résultat définir simplement une fonction:

public static string ToHexString(byte[] array) 
{ 
    StringBuilder hex = new StringBuilder(array.Length * 2); 
    foreach (byte b in array) 
    { 
     hex.AppendFormat("{0:x2}", b); 
    } 
    return hex.ToString(); 
} 

puis:

ASCIIEncoding encoder = new ASCIIEncoding(); 
Byte[] code = encoder.GetBytes("ant"); 
HMACSHA1 hmSha1 = new HMACSHA1(code); 
Byte[] hashMe = encoder.GetBytes("bat"); 
Byte[] hmBytes = hmSha1.ComputeHash(hashMe); 
Console.WriteLine(ToHexString(hmBytes)); 

Maintenant, vous obtiendrez le même résultat que dans Python:

739ebc1e3600d5be6e9fa875bd0a572d6aee9266