2013-11-29 8 views
6

Ho una stringa in PHP che viene convertita in un array di byte e hash.Stringa con risultato hash Convert.ToChar (0) diverso da chr (0) in PHP quando hash hash_hmac

La stringa essendo convertiti alla matrice di byte assomiglia:

"g". chr (0). "cacca";

ho bisogno di array di byte equivalente in C# in modo da posso ottenere lo stesso hash ..

EDIT: Qui è il problema PIENA, con conseguente hash non è la stessa.

PHP

$api_secret = '5432919427bd18884fc2a6e48b65dfba48fd9a1a46e3468b52fadbc6d6b463425'; 
$data = 'payment_currency=USD&group_orders=0&count=100&nonce=1385689989977529'; 
$endpoint = '/info/orderbook'; 

$signature = hash_hmac('sha512', $endpoint . chr(0) . $data, $api_secret); 

$result = base64_encode($signature); 

codifica C#

var apiSecret = "5432919427bd18884fc2a6e48b65dfba48fd9a1a46e3468b52fadbc6d6b463425"; 
var data = "payment_currency=USD&group_orders=0&count=100&nonce=1385689989977529"; 
var endPoint = "/info/orderbook"; 

System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); 

String message = endpPoint + Convert.ToChar(0) + data; 

var hmacsha512 = new HMACSHA512(encoding.GetBytes(message)); 
var result = Convert.ToBase64String(hmacsha512.Hash); 

ho provato Base64 diversa, come:

public static string ByteToString(byte[] buff) 
    { 
     string sbinary = ""; 
     for (int i = 0; i < buff.Length; i++) 
      sbinary += buff[i].ToString("X2"); /* hex format */ 
     return sbinary; 
    } 

ma in ultima analisi, il problema sembra essere il ByteArray che è hash a causa di usa chr (0) php.

+0

Presumo che si desidera qualcosa di simile: "g" + (char) 0 + "cacca".questa stringa in php significa che vuoi concatenare "g" con null e poi con "poo"? –

+0

sì è corretto .. quindi ho bisogno di convertirlo in un array di byte .. ma non capisco come fare lo stesso tipo di stringa in C# .. l'array di byte e il successivo hash che faccio da esso sono diversi –

+0

I ha risposto come renderlo come array di byte. –

risposta

3

Sto rispondendo di nuovo, perché hai cambiato l'intera domanda, quindi c'è una nuova soluzione per il tuo ne w domanda.

In primo luogo, HMACSHA512 non darà lo stesso risultato del codice php. Tra l'altro, il vostro PHP generato hash è:

41028bb90af31dc6e7fa100a8ceb1e220bfedf67ea723292db9a4e1c14f69c73adf30eeba61ab054cdc91c82f6be2f76dd602392be630b5e99b1f86da1460cbe 

Per rendere lo stesso risultato in C#, ho creato la classe BillieJeansSHA512 per rendere l'hash è uguale a come PHP. Inoltre, usando invece encoding.GetBytes per convertire il byte [] in String, ho creato il metodo ByteToString per convertirlo correttamente.

Ow, il seguente codice non è semplice come PHP, ma sfido te o chiunque a fare questo più semplice con lo stesso hash di PHP! Ti sfido, ho DOPPIO OSTA! Andiamo al codice:

//These are not default imports, so you need to use it 
using System.Text; 
using System.Security.Cryptography; 

//Before your actual class, you need to make your custom 512 
public class BillieJeansSHA512 : HMAC 
{ 
    public BillieJeansSHA512(byte[] key) 
    { 
     HashName = "System.Security.Cryptography.SHA512CryptoServiceProvider"; 
     HashSizeValue = 512; 
     BlockSizeValue = 128; 
     Key = (byte[])key.Clone(); 
    } 
} 

//Now, there's your actual class 
public class HelloWorld{ 


    //First, use this method to convert byte to String like a boss 
    static string ByteToString(byte[] buff) 
    { 
     string sbinary = ""; 
     for (int i = 0; i < buff.Length; i++) 
      sbinary += buff[i].ToString("x2"); /* hex format */ 
     return sbinary; 
    }  

    //Now let's get it started! 
    public static void Main(String []args){ 
     System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); 

     //Your data 
     var apiSecret = "5432919427bd18884fc2a6e48b65dfba48fd9a1a46e3468b52fadbc6d6b463425"; 
     var data = "payment_currency=USD&group_orders=0&count=100&nonce=1385689989977529"; 
     var endPoint = "/info/orderbook"; 

     String message = endPoint + Convert.ToChar(0) + data; 

     //Hash will be stored here 
     String hash = ""; 

     //put your key at your custom 512 
     BillieJeansSHA512 hmacsha512 = new BillieJeansSHA512(encoding.GetBytes(apiSecret)); 
     //hash'em all 
     byte[] result = hmacsha512.ComputeHash(encoding.GetBytes(message)); 

     //convert bytes to string 
     hash = ByteToString(result); 

     //See it :) 
     Console.WriteLine(hash); 

     //Or if you using it at a web-page, this is it. 
     //Response.Write(hash) 

     //Now the easy part, convert it to base64 
     var bytesTo64 = System.Text.Encoding.UTF8.GetBytes(hash); 
     String hash64 = System.Convert.ToBase64String(bytesTo64); 
    } 
} 

... beh, questo è tutto. String hash hanno lo stesso hash come PHP fa:

41028bb90af31dc6e7fa100a8ceb1e220bfedf67ea723292db9a4e1c14f69c73adf30eeba61ab054cdc91c82f6be2f76dd602392be630b5e99b1f86da1460cbe 

e String hash64 ha lo stesso valore codificato Base64 che PHP fa:

NDEwMjhiYjkwYWYzMWRjNmU3ZmExMDBhOGNlYjFlMjIwYmZlZGY2N2VhNzIzMjkyZGI5YTRlMWMxNGY2OWM3M2FkZjMwZWViYTYxYWIwNTRjZGM5MWM4MmY2YmUyZjc2ZGQ2MDIzOTJiZTYzMGI1ZTk5YjFmODZkYTE0NjBjYmU= 
+1

Voglio sinceramente ringraziarvi! Perché hai dovuto creare la 512 personalizzata? La dimensione del blocco è diversa in PHP o qualcosa ?? Amico ... mi sono strappato i capelli. Grazie! –

+2

Sì! è stato difficile, ho passato almeno 3 ore su quello !! Divertiti ora :) –

+1

@WagnerLeonardi Mi hai appena salvato il culo. Grazie mille per aver postato questo. –

0

È possibile utilizzare il metodo Convert.ToChar(Int32) per rappresentare i valori unicode come caratteri.

Usage: "g" + Convert.ToChar(0) + "poo"

1

Egli ha anche chiesto come byte array, è il più importante, perché devono utilizzare char alla conversione byte:

//Conversion object 
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); 

//Your any String text 
String stringText = "g" + Convert.ToChar(0) + "poo"; 

//Convert to the wanted byte array 
byte[] byteArray = encoding.GetBytes(stringText); 

È anche possibile fare la stessa cosa in una sola riga , se preferisci :)

byte[] byteArray = new System.Text.UTF8Encoding().GetBytes("g" + Convert.ToChar(0) + "poo"); 
+0

Quando ho cancellato che il risultato è diverso da quando la "g" + Convert.ToChar (0) + "poo" è hash in php –

+0

Bene, questa non è la stessa domanda. Ho fatto una nuova risposta per questo, quindi dai un'occhiata. –