aboutsummaryrefslogtreecommitdiff
path: root/sig/sig.go
diff options
context:
space:
mode:
Diffstat (limited to 'sig/sig.go')
-rw-r--r--sig/sig.go69
1 files changed, 69 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
+}