github.com/tailscale/wireguard-go@v0.0.20201119-0.20210522003738-46b531feb08a/device/noise-types.go (about) 1 /* SPDX-License-Identifier: MIT 2 * 3 * Copyright (C) 2017-2021 WireGuard LLC. All Rights Reserved. 4 */ 5 6 package device 7 8 import ( 9 "crypto/subtle" 10 "encoding/hex" 11 "errors" 12 ) 13 14 const ( 15 NoisePublicKeySize = 32 16 NoisePrivateKeySize = 32 17 NoisePresharedKeySize = 32 18 ) 19 20 type ( 21 NoisePublicKey [NoisePublicKeySize]byte 22 NoisePrivateKey [NoisePrivateKeySize]byte 23 NoisePresharedKey [NoisePresharedKeySize]byte 24 NoiseNonce uint64 // padded to 12-bytes 25 ) 26 27 func loadExactHex(dst []byte, src string) error { 28 slice, err := hex.DecodeString(src) 29 if err != nil { 30 return err 31 } 32 if len(slice) != len(dst) { 33 return errors.New("hex string does not fit the slice") 34 } 35 copy(dst, slice) 36 return nil 37 } 38 39 func (key NoisePrivateKey) IsZero() bool { 40 var zero NoisePrivateKey 41 return key.Equals(zero) 42 } 43 44 func (key NoisePrivateKey) Equals(tar NoisePrivateKey) bool { 45 return subtle.ConstantTimeCompare(key[:], tar[:]) == 1 46 } 47 48 func (key *NoisePrivateKey) FromHex(src string) (err error) { 49 err = loadExactHex(key[:], src) 50 key.clamp() 51 return 52 } 53 54 func (key *NoisePrivateKey) FromMaybeZeroHex(src string) (err error) { 55 err = loadExactHex(key[:], src) 56 if key.IsZero() { 57 return 58 } 59 key.clamp() 60 return 61 } 62 63 func (key *NoisePublicKey) FromHex(src string) error { 64 return loadExactHex(key[:], src) 65 } 66 67 func (key NoisePublicKey) IsZero() bool { 68 var zero NoisePublicKey 69 return key.Equals(zero) 70 } 71 72 func (key NoisePublicKey) Equals(tar NoisePublicKey) bool { 73 return subtle.ConstantTimeCompare(key[:], tar[:]) == 1 74 } 75 76 func (key *NoisePresharedKey) FromHex(src string) error { 77 return loadExactHex(key[:], src) 78 }