cmd/browser: remove key directory of key generation/save fails

The genkey function creates the key directory, so it should clean up
after itself if it fails after creating the directory. Without this fix,
users could end up in a state where they have to manually remove the
directory before key generation will work.

Change-Id: I63d29b303b48ad27599df19309ff1d81a10dee72
Reviewed-by: Rob Pike <>
diff --git a/cmd/browser/startup.go b/cmd/browser/startup.go
index cb67dbc..3049858 100644
--- a/cmd/browser/startup.go
+++ b/cmd/browser/startup.go
@@ -635,10 +635,13 @@
 	pub, priv, seed, err := keygen.Generate("p256")
 	if err != nil {
+		os.Remove(keyDir)
 		return "", "", err
 	err = keygen.SaveKeys(keyDir, false, pub, priv, seed)
 	if err != nil {
+		// SaveKeys may have left files behind, so RemoveAll.
+		os.RemoveAll(keyDir)
 		return "", "", err
 	return seed, keyDir, nil