Skip to content

Commit

Permalink
feat: implement json marshal and unmarshal methods for wireguard key
Browse files Browse the repository at this point in the history
  • Loading branch information
ironman0x7b2 committed Jan 27, 2025
1 parent 901ec61 commit 2198709
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ require (
github.com/shirou/gopsutil/v4 v4.24.11
github.com/showwin/speedtest-go v1.7.9
github.com/spf13/cobra v1.8.1
github.com/spf13/viper v1.19.0
github.com/spf13/pflag v1.0.5
github.com/v2fly/v2ray-core/v5 v5.23.0
golang.org/x/crypto v0.31.0
google.golang.org/grpc v1.69.4
Expand Down Expand Up @@ -126,7 +126,7 @@ require (
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/spf13/afero v1.11.0 // indirect
github.com/spf13/cast v1.6.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.19.0 // indirect
github.com/stretchr/testify v1.9.0 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect
Expand Down
22 changes: 22 additions & 0 deletions wireguard/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"encoding/json"
"errors"
"fmt"

Expand Down Expand Up @@ -33,6 +34,27 @@ func (k *Key) Public() *Key {
return (*Key)(&pub)
}

// MarshalJSON encodes the Key as a base64 string.
func (k *Key) MarshalJSON() ([]byte, error) {
return json.Marshal(k.String())
}

// UnmarshalJSON decodes a base64 string into a Key.
func (k *Key) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return fmt.Errorf("failed to unmarshal key: %w", err)
}

key, err := NewKeyFromString(s)
if err != nil {
return fmt.Errorf("failed to decode key: %w", err)
}

*k = *key
return nil
}

// NewPresharedKey generates a new random 32-byte key.
func NewPresharedKey() (*Key, error) {
var k Key
Expand Down

0 comments on commit 2198709

Please sign in to comment.