aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDimitri Sokolyuk <demon@dim13.org>2017-04-30 00:35:59 +0200
committerDimitri Sokolyuk <demon@dim13.org>2017-04-30 00:35:59 +0200
commit83c3b9732f299b11d7b022014994f428f4be2f5c (patch)
treec8b900dc4c11c9ca3144f48a139963bc2a5cacbf
parent1a87fe8789699298eccbecc93e8016a73283cfec (diff)
Add sig pkg
-rw-r--r--sig/sig.go69
-rw-r--r--sig/sig_test.go20
2 files changed, 89 insertions, 0 deletions
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)
+ }
+}