keyring: Add key serialization

This commit is contained in:
Armon Dadgar 2015-05-28 15:49:52 -07:00
parent c60970e743
commit c095861a02
2 changed files with 38 additions and 0 deletions

View File

@ -35,6 +35,21 @@ type Key struct {
InstallTime time.Time
}
// Serialize is used to create a byte encoded key
func (k *Key) Serialize() ([]byte, error) {
buf, err := json.Marshal(k)
return buf, err
}
// DeserializeKey is used to deserialize and return a new key
func DeserializeKey(buf []byte) (*Key, error) {
k := new(Key)
if err := json.Unmarshal(buf, k); err != nil {
return nil, fmt.Errorf("deserialization failed: %v", err)
}
return k, nil
}
// NewKeyring creates a new keyring
func NewKeyring() *Keyring {
k := &Keyring{

View File

@ -171,3 +171,26 @@ func TestKeyring_Serialize(t *testing.T) {
}
}
}
func TestKey_Serialize(t *testing.T) {
k := &Key{
Term: 10,
Version: 1,
Value: []byte("foobarbaz"),
InstallTime: time.Now(),
}
buf, err := k.Serialize()
if err != nil {
t.Fatalf("err: %v", err)
}
out, err := DeserializeKey(buf)
if err != nil {
t.Fatalf("err: %v", err)
}
if !reflect.DeepEqual(k, out) {
t.Fatalf("bad: %#v", out)
}
}