Files
transit/pubkey/pubkey.go

46 lines
1.0 KiB
Go

package pubkey
import (
"encoding/base64"
"github.com/mleku/transit/chk"
"github.com/mleku/transit/ec/schnorr"
"github.com/mleku/transit/errorf"
)
const Len = schnorr.PubKeyBytesLen
var EncodedLen = base64.RawURLEncoding.EncodedLen(Len)
// P is public key in base64 URL format.
type P struct{ Key []byte }
// New creates a new .
func New(pub []byte) (i *P) { return &P{Key: pub} }
func (i *P) MarshalJSON() (b []byte, err error) {
if len(i.Key) != Len {
err = errorf.E("pubkey must be %d bytes long, got %d", Len, len(i.Key))
return
}
b = make([]byte, EncodedLen+2)
b[0] = '"'
b[len(b)-1] = '"'
base64.RawURLEncoding.Encode(b[1:], i.Key)
return
}
func (i *P) UnmarshalJSON(b []byte) (err error) {
if len(b) != EncodedLen+2 {
err = errorf.E("encoded pubkey must be %d bytes long, got %d", EncodedLen+2, len(b))
return
}
i.Key = make([]byte, Len)
var n int
if n, err = base64.RawURLEncoding.Decode(i.Key, b[1:EncodedLen+1]); chk.E(err) {
err = errorf.E("error: decoding failed at %d: %s", n, err.Error())
return
}
return
}