Files
trpic/main_test.go
2026-04-07 13:28:59 +08:00

107 lines
2.7 KiB
Go

package main_test
import (
"crypto/subtle"
"fmt"
"testing"
"github.com/opencoff/go-srp"
)
var (
password = []byte("password string that's too long")
username = []byte("foouser")
)
func register(clientSRP *srp.SRP, username, password []byte) (string, string) {
tVerifier, err := clientSRP.Verifier(username, password)
if err != nil { panic(err) }
return tVerifier.Encode()
}
func Test_main(t *testing.T) {
clientSRP, err := srp.New(1024)
if err != nil { panic(err) }
// Register ------------------------------------------------
ih, vh := register(clientSRP, username, password)
// Store ih, vh in durable storage
fmt.Printf("Verifier Store:\n %s => %s\n", ih, vh)
DBVerifier := vh
// Register end --------------------------------------------
srpClient, err := clientSRP.NewClient(username, password)
if err != nil { panic(err) }
// client credentials (public key and identity) to send to server
ClientCreds := srpClient.Credentials()
fmt.Printf("Client Begin; <I, A> --> server:\n %s\n", ClientCreds)
// Challenge start ------------------------------
// Begin the server by parsing the client public key and identity.
_, A, err := srp.ServerBegin(ClientCreds)
if err != nil { panic(err) }
// Now, pretend to lookup the user db using "I" as the key and
// fetch salt, verifier etc.
tSRP, tVerifier, err := srp.MakeSRPVerifier(DBVerifier)
if err != nil {
panic(err)
}
fmt.Printf("Server Begin; <v, A>:\n %s\n %x\n", DBVerifier, A.Bytes())
srpServer, err := tSRP.NewServer(tVerifier, A)
if err != nil { panic(err) }
// Generate the credentials to send to client
ServerCreds := srpServer.Credentials()
// Send the server public key and salt to server
fmt.Printf("Server Begin; <s, B> --> client:\n %s\n", ServerCreds)
// Challenge end ------------------------------
// client processes the server creds and generates
// a mutual authenticator; the authenticator is sent
// to the server as proof that the client derived its keys.
cauth, err := srpClient.Generate(ServerCreds)
if err != nil {
panic(err)
}
fmt.Printf("Client Authenticator: M --> Server\n %s\n", cauth)
// Receive the proof of authentication from client
proof, ok := srpServer.ClientOk(cauth)
if !ok {
panic("client auth failed")
}
// Send proof to the client
fmt.Printf("Server Authenticator: M' --> Server\n %s\n", proof)
// Verify the server's proof
if !srpClient.ServerOk(proof) {
panic("server auth failed")
}
// Now, we have successfully authenticated the client to the
// server and vice versa.
kc := srpClient.RawKey()
ks := srpServer.RawKey()
if 1 != subtle.ConstantTimeCompare(kc, ks) {
panic("Keys are different!")
}
fmt.Printf("Client Key: %x\nServer Key: %x\n", kc, ks)
}