Golang - binary data for packaging and hashing

I am trying to learn Golang and have experience in Python. I'm currently trying to figure out how to pack variables into binary format (with checksum). In Python, I would 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 in Go, I try code like this:

 package main import ( "crypto/sha256" "fmt" "encoding/binary" "bytes" ) type packet struct { a uint8 b string } func main() { var p = packet{} pa = 1 pb = "foo\x00\x00" buf := new(bytes.Buffer) binary.Write(buf, binary.LittleEndian, &p) h := sha256.New() h.Write(buf.String()) fmt.Printf("% x\n", p) } 

Unfortunately, however, I am attacking this; I seem to fall into a nightmare when confronted with variable types (buffers, byte arrays and strings). I would appreciate some advice on whether I even take a remotely correct approach.

+7
python go
source share
1 answer

Updated to what works.

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

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

You are right that it is a little painful to write structures with possible dynamic length elements in them (slices and strings) using coding / binary code. You may be interested in checking out the "encoding / gob" package, which automatically encodes strings (although it is not compatible with the filled string you got here).

+5
source share

All Articles