mirror of
https://github.com/tailscale/tailscale.git
synced 2025-02-16 18:08:40 +00:00
types/key: make Public implement TextMarshaler, TextUnmarshaler
So it can be a map key with encoding/json
This commit is contained in:
parent
f51f18b42b
commit
810c1e9704
@ -7,6 +7,8 @@ package key
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
"golang.org/x/crypto/curve25519"
|
"golang.org/x/crypto/curve25519"
|
||||||
)
|
)
|
||||||
@ -35,6 +37,26 @@ func (p Public) ShortString() string {
|
|||||||
return "[" + base64.StdEncoding.EncodeToString(p[:])[:5] + "]"
|
return "[" + base64.StdEncoding.EncodeToString(p[:])[:5] + "]"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (p Public) MarshalText() ([]byte, error) {
|
||||||
|
buf := make([]byte, base64.StdEncoding.EncodedLen(len(p)))
|
||||||
|
base64.StdEncoding.Encode(buf, p[:])
|
||||||
|
return buf, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Public) UnmarshalText(txt []byte) error {
|
||||||
|
if *p != (Public{}) {
|
||||||
|
return errors.New("refusing to unmarshal into non-zero key.Public")
|
||||||
|
}
|
||||||
|
n, err := base64.StdEncoding.Decode(p[:], txt)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if n != 32 {
|
||||||
|
return fmt.Errorf("short decode of %d; want 32", n)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// B32 returns k as the *[32]byte type that's used by the
|
// B32 returns k as the *[32]byte type that's used by the
|
||||||
// golang.org/x/crypto packages. This allocates; it might
|
// golang.org/x/crypto packages. This allocates; it might
|
||||||
// not be appropriate for performance-sensitive paths.
|
// not be appropriate for performance-sensitive paths.
|
||||||
|
24
types/key/key_test.go
Normal file
24
types/key/key_test.go
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
package key
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTextUnmarshal(t *testing.T) {
|
||||||
|
p := Public{1, 2}
|
||||||
|
text, err := p.MarshalText()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var p2 Public
|
||||||
|
if err := p2.UnmarshalText(text); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if p != p2 {
|
||||||
|
t.Fatalf("mismatch; got %x want %x", p2, p)
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user