2011-01-31 17 views
0

使用this code一个JavaScript散列和JavaScript端的等效.NET算法

Using sha As New SHA256Managed 
     Using memStream As New MemoryStream(Encoding.ASCII.GetBytes("Hello World!")) 
      Dim hash() As Byte = sha.ComputeHash(memStream) 
      Dim res As String = Encoding.Default.GetString(hash) 
     End Using 
    End Using 

我已经无法重新创建与代码这两个比特具有相同的值相同的散列。

JavaScript实现返回7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069,VB.NET示例返回ƒ±eñüS¹-ÁH¡Ö]ü-K£Öw(JÝÒ mi"

我错过了什么?我认为这是与字符编码有关?

解决方法:这是一个简单的变化:

Using sha As New SHA256Managed 
     Using memStream As New MemoryStream(Encoding.ASCII.GetBytes("Hello World!")) 
      Dim hash() As Byte = sha.ComputeHash(memStream) 
      Dim res As String = BitConverter.ToString(hash) 
     End Using 
    End Using 

回答

1

你治疗hash阵列的ASCII字符的序列。你需要的十六进制表示,这样你们可以开始使用BitConverter.ToString,这样的事情:

​​
+0

感谢您的帮助! – 2011-02-01 00:31:08

1

我不知道够不够VB提供的代码,但问题是,你是治疗的字节数组作为编码的字符串,并试图对其进行解码。实际上应该将字节数组转换为十六进制字符串。例如,请参阅here

0

它们基本上是同样的事情...你可能想看看:How do you convert Byte Array to Hexadecimal String, and vice versa?

你可以用它来将字符串转换回它的十六进制表示。

一个例子来证明它的工作方式相同,请参阅:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Security.Cryptography; 
using System.IO; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      using (var sha = new SHA256Managed()) 
      { 
       using (var stream = new MemoryStream(
        Encoding.ASCII.GetBytes("Hello World!"))) 
       { 
        var hash = sha.ComputeHash(stream); 
        var result = Encoding.Default.GetString(hash); 

        //print out each byte as hexa in consecutive manner 
        foreach (var h in hash) 
        { 
         Console.Write("{0:x2}", h); 
        } 
        Console.WriteLine(); 

        //Show the resulting string from GetString 
        Console.WriteLine(result); 
        Console.ReadLine(); 
       } 
      } 
     } 
    } 
} 
+0

或者只是`字符串十六进制= string.Concat(hash.Select(X => x.ToString( “X2”)) );`。不确定究竟VB是什么。 – LukeH 2011-01-31 10:22:06