From 83c3b9732f299b11d7b022014994f428f4be2f5c Mon Sep 17 00:00:00 2001 From: Dimitri Sokolyuk Date: Sun, 30 Apr 2017 00:35:59 +0200 Subject: Add sig pkg --- sig/sig.go | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ sig/sig_test.go | 20 +++++++++++++++++ 2 files changed, 89 insertions(+) create mode 100644 sig/sig.go create mode 100644 sig/sig_test.go (limited to 'sig') diff --git a/sig/sig.go b/sig/sig.go new file mode 100644 index 0000000..4e91336 --- /dev/null +++ b/sig/sig.go @@ -0,0 +1,69 @@ +// Package sig implements signify file format +package sig + +import ( + "bytes" + "encoding/base64" + "errors" + "fmt" + "io" + "io/ioutil" + "strings" +) + +// Block represents a encoded signify key or signature +// +// The encoded form is: +// untrusted comment: comment +// base64-encoded key +// optinal message +type Block struct { + Comment string + Bytes []byte + Message []byte +} + +const commentHdr = "untrusted comment:" + +var ErrUntrustedComment = errors.New("expected untrusted comment") + +func Encode(w io.Writer, b *Block) error { + fmt.Fprintln(w, commentHdr, b.Comment) + fmt.Fprintln(w, base64.StdEncoding.EncodeToString(b.Bytes)) + w.Write(b.Message) + return nil +} + +func EncodeToMemory(b *Block) []byte { + buf := new(bytes.Buffer) + Encode(buf, b) + return buf.Bytes() +} + +func Decode(data []byte) (*Block, error) { + r := bytes.NewBuffer(data) + comment, err := r.ReadString('\n') + if err != nil { + return nil, err + } + if !strings.HasPrefix(comment, commentHdr) { + return nil, ErrUntrustedComment + } + raw, err := r.ReadString('\n') + if err != nil { + return nil, err + } + b, err := base64.StdEncoding.DecodeString(raw) + if err != nil { + return nil, err + } + message, err := ioutil.ReadAll(r) + if err != nil { + return nil, err + } + return &Block{ + Comment: strings.TrimSpace(comment[len(commentHdr):]), + Bytes: b, + Message: message, + }, nil +} diff --git a/sig/sig_test.go b/sig/sig_test.go new file mode 100644 index 0000000..06be3c0 --- /dev/null +++ b/sig/sig_test.go @@ -0,0 +1,20 @@ +package sig + +import ( + "bytes" + "testing" +) + +func TestSig(t *testing.T) { + b := &Block{ + Comment: "comment", + Bytes: []byte{'t', 'e', 's', 't'}, + } + b2, err := Decode(EncodeToMemory(b)) + if err != nil { + t.Error(err) + } + if b.Comment != b2.Comment || !bytes.Equal(b.Bytes, b2.Bytes) { + t.Errorf("got %v, want %v", b2, b) + } +} -- cgit v1.2.3