duanqin9507 2014-01-04 15:07
浏览 67
已采纳

Golang-打包和散列二进制数据

I'm attempting to learn Golang and have a background in Python. I'm currently trying to get my head around how to pack variables into a binary format (with a checksum). In Python I'd use something like:

import struct
import hashlib

a = 100
b = "foo\x00\x00"  # Padded to fixed length
packet = struct.pack('<B5s', a, b)
digest = hashlib.sha256(packet).digest()
packet += digest

To do the same thing in Go, I'm trying code like this:

package main

import (
    "crypto/sha256"
    "fmt"
    "encoding/binary"
    "bytes"
)

type packet struct {
    a uint8
    b string
}

func main() {
    var p = packet{}
    p.a = 1
    p.b = "foo\x00\x00"
    buf := new(bytes.Buffer)
    binary.Write(buf, binary.LittleEndian, &p)
    h := sha256.New()
    h.Write(buf.String())
    fmt.Printf("% x
", p)
}

Unfortunately, however I attack it I seem to get into a nightmare of clashing variable types (buffers, byte arrays and strings). I'd appreciate some guidance as to whether I'm taking even remotely the right approach.

  • 写回答

1条回答 默认 最新

  • dqyat62284 2014-01-04 15:54
    关注

    Updated to something that works.

    package main
    
    import (
       "bytes"
       "crypto/sha256"
       "encoding/binary"
       "fmt"
    )
    
    type packet struct {
       a uint8
       b []byte
    }
    
    func main() {
       var p = packet{}
       p.a = 1
       p.b = []byte("foo\x00\x00")
       buf := bytes.Buffer{}
       err := binary.Write(&buf, binary.BigEndian, p.a)
       if err != nil {
           fmt.Println(err)
       }
       _, err = buf.Write(p.b)
       if err != nil {
           fmt.Println(err)
       }
       h := sha256.New()
       h.Write(buf.Bytes())
       hash := h.Sum([]byte{})
       fmt.Printf("% x
    ", hash)
    }
    

    http://play.golang.org/p/t8ltu_WCpe

    You're right that it's a bit painful to write structs with possibly dynamic length items in them (slices and strings) using encoding/binary. You might be interested in checking out the "encoding/gob" package that encodes strings automatically (although it isn't compatible with the padded string you've got here).

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

报告相同问题?

悬赏问题

  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面