Skip to content

feat(identity): implement X25519 keypair generation and file storage #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 63 additions & 3 deletions identity/identity.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
3 changes: 3 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"fmt"
"msg-sdk-go/identity"
"msg-sdk-go/transport"
"time"
)
Expand Down Expand Up @@ -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)
Expand Down