mirror of
https://github.com/KusakabeShi/EtherGuard-VPN.git
synced 2024-11-30 03:03:10 +01:00
83 lines
1.7 KiB
Go
83 lines
1.7 KiB
Go
/* SPDX-License-Identifier: MIT
|
|
*
|
|
* Copyright (C) 2017-2019 WireGuard LLC. All Rights Reserved.
|
|
*/
|
|
|
|
package device
|
|
|
|
import (
|
|
"crypto/subtle"
|
|
"encoding/hex"
|
|
"errors"
|
|
|
|
"golang.org/x/crypto/chacha20poly1305"
|
|
)
|
|
|
|
const (
|
|
NoisePublicKeySize = 32
|
|
NoisePrivateKeySize = 32
|
|
)
|
|
|
|
type (
|
|
NoisePublicKey [NoisePublicKeySize]byte
|
|
NoisePrivateKey [NoisePrivateKeySize]byte
|
|
NoiseSymmetricKey [chacha20poly1305.KeySize]byte
|
|
NoiseNonce uint64 // padded to 12-bytes
|
|
)
|
|
|
|
func loadExactHex(dst []byte, src string) error {
|
|
slice, err := hex.DecodeString(src)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(slice) != len(dst) {
|
|
return errors.New("hex string does not fit the slice")
|
|
}
|
|
copy(dst, slice)
|
|
return nil
|
|
}
|
|
|
|
func (key NoisePrivateKey) IsZero() bool {
|
|
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
|
|
}
|
|
|
|
func (key NoisePrivateKey) ToHex() string {
|
|
return hex.EncodeToString(key[:])
|
|
}
|
|
|
|
func (key *NoisePublicKey) FromHex(src string) error {
|
|
return loadExactHex(key[:], src)
|
|
}
|
|
|
|
func (key NoisePublicKey) ToHex() string {
|
|
return hex.EncodeToString(key[:])
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
func (key *NoiseSymmetricKey) FromHex(src string) error {
|
|
return loadExactHex(key[:], src)
|
|
}
|
|
|
|
func (key NoiseSymmetricKey) ToHex() string {
|
|
return hex.EncodeToString(key[:])
|
|
}
|