package crypto
import (
"crypto/sha1"
"encoding/binary"
"encoding/hex"
"fmt"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"go.uber.org/zap/zapcore"
)
type Key [256 ]byte
func (k Key ) String () string {
return "(redacted)"
}
func (k Key ) Zero () bool {
return k == Key {}
}
func (k Key ) ID () [8 ]byte {
raw := sha1 .Sum (k [:])
var id [8 ]byte
copy (id [:], raw [12 :])
return id
}
func (k Key ) AuxHash () [8 ]byte {
raw := sha1 .Sum (k [:])
var id [8 ]byte
copy (id [:], raw [0 :8 ])
return id
}
func (k Key ) WithID () AuthKey {
return AuthKey {
Value : k ,
ID : k .ID (),
}
}
type AuthKey struct {
Value Key
ID [8 ]byte
}
func (a *AuthKey ) DecodeJSON (d *jx .Decoder ) error {
return d .ObjBytes (func (d *jx .Decoder , key []byte ) error {
switch string (key ) {
case "value" :
data , err := d .Base64 ()
if err != nil {
return errors .Wrap (err , "decode value" )
}
copy (a .Value [:], data )
case "id" :
id , err := d .Int64 ()
if err != nil {
return errors .Wrap (err , "decode id" )
}
a .SetIntID (id )
default :
return d .Skip ()
}
return nil
})
}
func (a *AuthKey ) UnmarshalJSON (data []byte ) error {
return a .DecodeJSON (jx .DecodeBytes (data ))
}
func (a AuthKey ) EncodeJSON (e *jx .Encoder ) error {
e .ObjStart ()
e .FieldStart ("value" )
e .Base64 (a .Value [:])
e .FieldStart ("id" )
e .Int64 (a .IntID ())
e .ObjEnd ()
return nil
}
func (a AuthKey ) MarshalJSON () ([]byte , error ) {
e := jx .GetEncoder ()
if err := a .EncodeJSON (e ); err != nil {
return nil , err
}
return e .Bytes (), nil
}
func (a AuthKey ) Zero () bool {
return a == AuthKey {}
}
func (a AuthKey ) IntID () int64 {
return int64 (binary .LittleEndian .Uint64 (a .ID [:]))
}
func (a *AuthKey ) SetIntID (v int64 ) {
binary .LittleEndian .PutUint64 (a .ID [:], uint64 (v ))
}
func (a AuthKey ) String () string {
return fmt .Sprintf ("Key(id: %x)" , a .ID )
}
func (a AuthKey ) MarshalLogObject (encoder zapcore .ObjectEncoder ) error {
encoder .AddString ("id" , hex .EncodeToString (a .ID [:]))
return nil
}
The pages are generated with Golds v0.6.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds .