diff --git a/identity/identity.go b/identity/identity.go index 292f70d..ced04af 100644 --- a/identity/identity.go +++ b/identity/identity.go @@ -2,7 +2,67 @@ package identity // GetLocalKeypair retrieves the local keypair for the Noise protocol. // Actual implementation is pending. -func GetLocalKeypair() { - // TODO: Implement keypair retrieval logic - +// TODO: Implement keypair retrieval logic +import ( + "crypto/rand" + "encoding/json" + "fmt" + "os" + + "golang.org/x/crypto/curve25519" +) + +// Keypair holds a Noise-compatible X25519 keypair +type Keypair struct { + PrivateKey [32]byte + PublicKey [32]byte +} + +// GenerateKeypair creates a new X25519 keypair +func GenerateKeypair() (*Keypair, error) { + var priv [32]byte + _, err := rand.Read(priv[:]) + if err != nil { + return nil, fmt.Errorf("failed to generate private key: %v", err) + } + + pub, err := curve25519.X25519(priv[:], curve25519.Basepoint) + if err != nil { + return nil, fmt.Errorf("failed to derive public key: %v", err) + } + + var pub32 [32]byte + copy(pub32[:], pub) + + return &Keypair{ + PrivateKey: priv, + PublicKey: pub32, + }, nil +} + +// SaveKeypair stores the keypair to a file as JSON +func SaveKeypair(kp *Keypair, filepath string) error { + f, err := os.Create(filepath) + if err != nil { + return err + } + defer f.Close() + + return json.NewEncoder(f).Encode(kp) +} + +// LoadKeypair loads a keypair from file +func LoadKeypair(filepath string) (*Keypair, error) { + f, err := os.Open(filepath) + if err != nil { + return nil, err + } + defer f.Close() + + var kp Keypair + err = json.NewDecoder(f).Decode(&kp) + if err != nil { + return nil, err + } + return &kp, nil } diff --git a/main.go b/main.go index 5194083..ce525ca 100644 --- a/main.go +++ b/main.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "msg-sdk-go/identity" "msg-sdk-go/transport" "time" ) @@ -33,6 +34,8 @@ func testTCPTransport() { fmt.Println("Error sending message:", err) return } + kp, _ := identity.GenerateKeypair() + fmt.Printf("Public Key: %x\n", kp.PublicKey) // Wait a bit if you’re testing against a local echo server *need to be optimised time.Sleep(1 * time.Second)