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).

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

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。