wireguard-go/device/noise-types.go

92 lines
1.8 KiB
Go
Raw Normal View History

2019-01-02 00:55:51 +00:00
/* SPDX-License-Identifier: MIT
*
* Copyright (C) 2017-2020 WireGuard LLC. All Rights Reserved.
*/
2019-03-03 03:04:41 +00:00
package device
import (
2017-08-04 14:15:53 +00:00
"crypto/subtle"
"encoding/hex"
"errors"
2019-05-14 07:09:52 +00:00
"golang.org/x/crypto/chacha20poly1305"
)
const (
NoisePublicKeySize = 32
NoisePrivateKeySize = 32
)
type (
2017-06-23 11:45:32 +00:00
NoisePublicKey [NoisePublicKeySize]byte
NoisePrivateKey [NoisePrivateKeySize]byte
NoiseSymmetricKey [chacha20poly1305.KeySize]byte
2017-06-23 11:45:32 +00:00
NoiseNonce uint64 // padded to 12-bytes
)
2017-06-01 19:31:30 +00:00
func loadExactHex(dst []byte, src string) error {
slice, err := hex.DecodeString(src)
if err != nil {
return err
}
2017-06-01 19:31:30 +00:00
if len(slice) != len(dst) {
2018-05-13 17:33:41 +00:00
return errors.New("hex string does not fit the slice")
}
2017-06-01 19:31:30 +00:00
copy(dst, slice)
return nil
}
func (key NoisePrivateKey) IsZero() bool {
2017-08-04 14:15:53 +00:00
var zero NoisePrivateKey
return key.Equals(zero)
}
func (key NoisePrivateKey) Equals(tar NoisePrivateKey) bool {
return subtle.ConstantTimeCompare(key[:], tar[:]) == 1
}
func (key *NoisePrivateKey) FromHex(src string) (err error) {
err = loadExactHex(key[:], src)
key.clamp()
return
2017-06-01 19:31:30 +00:00
}
func (key *NoisePrivateKey) FromMaybeZeroHex(src string) (err error) {
err = loadExactHex(key[:], src)
if key.IsZero() {
return
}
key.clamp()
return
}
2017-06-01 19:31:30 +00:00
func (key NoisePrivateKey) ToHex() string {
return hex.EncodeToString(key[:])
}
2017-06-01 19:31:30 +00:00
func (key *NoisePublicKey) FromHex(src string) error {
return loadExactHex(key[:], src)
}
func (key NoisePublicKey) ToHex() string {
return hex.EncodeToString(key[:])
}
2017-08-04 14:15:53 +00:00
func (key NoisePublicKey) IsZero() bool {
var zero NoisePublicKey
return key.Equals(zero)
}
func (key NoisePublicKey) Equals(tar NoisePublicKey) bool {
return subtle.ConstantTimeCompare(key[:], tar[:]) == 1
}
2017-06-01 19:31:30 +00:00
func (key *NoiseSymmetricKey) FromHex(src string) error {
return loadExactHex(key[:], src)
}
2017-06-01 19:31:30 +00:00
func (key NoiseSymmetricKey) ToHex() string {
return hex.EncodeToString(key[:])
}