Skip to content

Commit

Permalink
keyutil: docs and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
elimisteve committed Jan 5, 2017
1 parent bea9b7f commit a3aad67
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 2 deletions.
5 changes: 5 additions & 0 deletions keyutil/fmt.go
Expand Up @@ -7,6 +7,8 @@ import (
"fmt"
)

// Format formats the given key in the format a,b,c,...,z which is
// human-readable and suitable to be read by backend.UpdateKey().
func Format(key *[32]byte) string {
if key == nil {
return "<nil>"
Expand All @@ -16,6 +18,9 @@ func Format(key *[32]byte) string {
return FormatSlice(k[:])
}

// Format formats the given byte slice (probably a nonce slice-ified
// key) in the format a,b,c,...,z which is human-readable and suitable
// to be read by backend.UpdateKey().
func FormatSlice(b []byte) string {
if b == nil {
return "<nil>"
Expand Down
45 changes: 45 additions & 0 deletions keyutil/fmt_test.go
@@ -0,0 +1,45 @@
// Steve Phillips / elimisteve
// 2017.01.05

package keyutil

import (
"testing"

"github.com/stretchr/testify/assert"
)

type keyTest struct {
key *[32]byte
keystr string
}

var keyTests = []keyTest{
{
&[32]byte{},
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0",
},
{
&[32]byte{
0, 1, 2, 3, 4, 5, 6, 7,
0, 1, 2, 3, 4, 5, 6, 7,
0, 1, 2, 3, 4, 5, 6, 7,
0, 1, 2, 3, 4, 5, 6, 7,
},
"0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7",
},
}

func TestFormat(t *testing.T) {
for _, test := range keyTests {
got := Format(test.key)
assert.Equal(t, got, test.keystr)
}
}

var keyTestsErr = []keyTest{
{
nil,
"<nil>",
},
}
10 changes: 8 additions & 2 deletions keyutil/parse.go
Expand Up @@ -11,16 +11,22 @@ import (

var keyRegex = regexp.MustCompile(`(\d+)`)

const validKeyLength = 32

// Parse takes the string representation of a crypto key
// (comma-separated numbers) and parses it into a usable key.
func Parse(cliDigits string) (*[32]byte, error) {
// Pluck out all digit sequences, convert to numbers
nums := keyRegex.FindAllString(cliDigits, -1)
if len(nums) != 32 {
return nil, fmt.Errorf("Key must include 32 numbers, not %d", len(nums))
if len(nums) != validKeyLength {
return nil, fmt.Errorf("Key must include %d numbers, not %d",
validKeyLength, len(nums))
}

var newKey [32]byte

for i := 0; i < len(newKey); i++ {
// Parse string of numbers as (8-bit) bytes represented in base 10
n, err := strconv.ParseUint(nums[i], 10, 8)
if err != nil {
return nil, fmt.Errorf("Number #%d '%v' was invalid: %v\n", i+1,
Expand Down

0 comments on commit a3aad67

Please sign in to comment.