doudou521125 2017-03-07 12:04
浏览 207
已采纳

将C#SHA1代码转换为Golang

I need to convert some old C# code to Golang and I stuck somewhere. C# code looks like this `

 byte[] bytes = Encoding.Unicode.GetBytes(password);
 byte[] src = Encoding.Unicode.GetBytes(salt);
 byte[] dst = new byte[src.Length + bytes.Length];
 Buffer.BlockCopy(src, 0, dst, 0, src.Length);
 Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
 HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
 byte[] inArray = algorithm.ComputeHash(dst);
 return Convert.ToBase64String(inArray);

so I examined the code line by line and as I understand he used convert the salt and password byte array then he copied these arrays to 'dst' array. Then he used SHA1 algorithm and convert this array to base64string.

My Golang code looks like this but It doesn't create the same string which stores on database.

s := "fish123"
salt := "227EA7ABD26E40608A6EDEB209058D93A632D1D1A52246D0A27F6E447B16AEBF"

h1 := sha1.New()
h1.Write([]byte(salt))
h1.Write([]byte(s))

hashedPassword := base64.StdEncoding.EncodeToString(h1.Sum(nil))

Can anyone find my fault? Thanks

  • 写回答

1条回答 默认 最新

  • doucha7329 2017-03-07 12:55
    关注

    The problem is that the C# code is using the Encoding.Unicode. In Go it should be:

    package main
    
    import (
        "crypto/sha1"
        "encoding/base64"
        "encoding/binary"
        "fmt"
        "unicode/utf16"
    )
    
    func main() {
        s := "fish123"
        salt := "227EA7ABD26E40608A6EDEB209058D93A632D1D1A52246D0A27F6E447B16AEBF"
    
        h1 := sha1.New()
        h1.Write(convertUTF16ToLittleEndianBytes(salt))
        h1.Write(convertUTF16ToLittleEndianBytes(s))
    
        b64 := base64.StdEncoding.EncodeToString(h1.Sum(nil))
        fmt.Println(b64)
    }
    
    func convertUTF16ToLittleEndianBytes(s string) []byte {
        u := utf16.Encode([]rune(s))
        b := make([]byte, 2*len(u))
        for index, value := range u {
            binary.LittleEndian.PutUint16(b[index*2:], value)
        }
        return b
    }
    

    The convertUTF16ToLittleEndianBytes was taken from another response on SO.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 输出区间内所有的完数的个数。 要简单点的程序
  • ¥15 asp.core 权限控制怎么做,需要控制到每个方法
  • ¥20 while循环中OLED显示中断中的数据不正确
  • ¥15 这个视频里的stm32f4代码是怎么写的
  • ¥15 串口发送数据和接收数据
  • ¥15 JNA调用DLL报堆栈溢出错误(0xC00000FD)
  • ¥15 请教SGeMs软件的使用
  • ¥15 自己用vb.net编写了一个dll文件,如何只给授权的用户使用这个dll文件进行打包编译,未授权用户不能进行打包编译操作?
  • ¥50 深度学习运行代码直接中断
  • ¥20 需要完整的共散射点成像代码