A command-line tool using the saltpack messaging format and the keys.pub Go library.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.7 KiB

package salty
import (
"bufio"
"encoding/base64"
"fmt"
"io"
"strings"
"time"
"github.com/keys-pub/keys"
)
const privateKeySizeLimit = 1 << 8 // 256 bytes
// GenerateKeys creates a new pair of Ed25519 keys and writes the Private Key
// to the `out io.Writer` and returns the Private and Public Keys.
// The Private Key written to `out` is Base64 encoded.
func GenerateKeys(out io.Writer) (*keys.EdX25519Key, string) {
k := keys.GenerateEdX25519Key()
fmt.Fprintf(out, "# created: %s\n", time.Now().Format(time.RFC3339))
fmt.Fprintf(out, "# public key: %s\n", k.PublicKey().ID().String())
fmt.Fprintf(out, "%s\n", base64.StdEncoding.EncodeToString(k.Private()))
return k, k.PublicKey().ID().String()
}
// ParseIdentity parses the Salty Identity file given by `r io.Reader` which has a
// line-oriented format where comments (lines beginning with a #) and the and blank
// lines are ignored and the private key is the first non-comment / non-blank line.
// The Private Key is a Base64 decoded.
// This returns the parsed Ed25519 key on success or nil key and error if it fails.
func ParseIdentity(r io.Reader) (*keys.EdX25519Key, error) {
scanner := bufio.NewScanner(io.LimitReader(r, privateKeySizeLimit))
var n int
for scanner.Scan() {
line := scanner.Text()
n++
if strings.HasPrefix(line, "#") || line == "" {
continue
}
bs, err := base64.StdEncoding.DecodeString(line)
if err != nil {
return nil, fmt.Errorf("error at line %d: %v", n, err)
}
return keys.NewEdX25519KeyFromPrivateKey(keys.Bytes64(bs)), nil
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("failed to read identity file: %v", err)
}
return nil, fmt.Errorf("no key found")
}