This example demonstrates how to use the auth package for establishing a secure, authenticated communication channel between two peers.
The authenticated_messaging example showcases:
- Creating and connecting two
Peerinstances using an in-memory transport. - Deriving identity keys for each peer.
- Sending an encrypted and signed message from one peer to another.
- Receiving and decrypting the message on the recipient's side.
- Sending a reply back to the original sender.
// Create two transport pairs
aliceTransport := NewMemoryTransport()
bobTransport := NewMemoryTransport()
// Connect the transports
aliceTransport.Connect(bobTransport)
bobTransport.Connect(aliceTransport)
// Create two wallets with random keys
// ... (wallet creation code) ...
// Create peers
alicePeer := auth.NewPeer(&auth.PeerOptions{
Wallet: aliceWallet,
Transport: aliceTransport,
})
bobPeer := auth.NewPeer(&auth.PeerOptions{
Wallet: bobWallet,
Transport: bobTransport,
})This section explains the initial setup of in-memory transport, wallets, and peer instances for Alice and Bob.
// Get identity keys
// ... (identity key retrieval code) ...
// Set up message listeners
alicePeer.ListenForGeneralMessages(func(senderPublicKey *ec.PublicKey, payload []byte) error {
fmt.Printf("Alice received message from %s: %s\n", senderPublicKey.Compressed(), string(payload))
return nil
})
bobPeer.ListenForGeneralMessages(func(senderPublicKey *ec.PublicKey, payload []byte) error {
fmt.Printf("Bob received message from %s: %s\n", senderPublicKey.Compressed(), string(payload))
// Reply to Alice
err := bobPeer.ToPeer(context.Background(), []byte("Hello back, Alice!"), senderPublicKey, 5000)
if err != nil {
log.Printf("Bob failed to reply: %v", err)
}
return nil
})
// Alice sends a message to Bob
err = alicePeer.ToPeer(context.Background(), []byte("Hello, Bob!"), bobIdentityResult.PublicKey, 5000)
if err != nil {
log.Fatalf("Failed to send message: %v", err)
}This section details how peers listen for messages and how Alice sends an initial message to Bob, who then replies. The ToPeer method handles encryption and signing.
To run this example:
go run authenticated_messaging.goNote: This example uses an in-memory transport (MemoryTransport) for simplicity. In a real-world application, you would use a network-based transport like WebSockets. It also uses a MinimalWalletImpl which is a mock; a full wallet implementation would be required for production use.
To integrate authenticated messaging into your application:
- Implement
auth.Transportfor your chosen communication protocol (e.g., WebSockets, HTTP). - Ensure both peers have a fully implemented
wallet.Interface. - Initialize
auth.Peerfor each communicating party with their respective wallets and the chosen transport. - Use
peer.ToPeer()to send authenticated messages andpeer.ListenForGeneralMessages()to receive them.
For more information, see: