Commit d00e51e

Karn Wong <karn@karnwong.me>
2023-12-28 16:25:56
add ssh: create-ssh-key
1 parent e3ae0a1
cmd/ssh/ssh.go
@@ -0,0 +1,16 @@
+package ssh
+
+import (
+	"fmt"
+
+	"github.com/spf13/cobra"
+)
+
+var Cmd = &cobra.Command{
+	Use:   "ssh",
+	Short: "SSH tools",
+	Long:  `SSH tools`,
+	Run: func(cmd *cobra.Command, args []string) {
+		fmt.Println("Please specify subcommand")
+	},
+}
cmd/ssh/ssh_create_ssh_key.go
@@ -0,0 +1,69 @@
+package ssh
+
+import (
+	"crypto/ed25519"
+	"crypto/rand"
+	"encoding/base64"
+	"fmt"
+	"log"
+	"os"
+
+	"github.com/fatih/color"
+	"github.com/spf13/cobra"
+)
+
+// helpers
+func writeStringToFile(filePath, data string) {
+	file, err := os.Create(filePath)
+	if err != nil {
+		log.Fatal(err)
+	}
+
+	_, err = file.WriteString(data)
+	if err != nil {
+		log.Fatal(err)
+	}
+}
+
+func writePrivateKey(privateKey ed25519.PrivateKey) {
+	privateKeyStr := fmt.Sprintf("-----BEGIN OPENSSH PRIVATE KEY-----\n%s\n-----END OPENSSH PRIVATE KEY-----\n", base64.StdEncoding.EncodeToString(privateKey))
+
+	writeStringToFile("key.pem", privateKeyStr)
+}
+
+func writePublicKey(publicKey ed25519.PublicKey) {
+	publicKeyStr := fmt.Sprintf("ssh-ed25519 %s", base64.StdEncoding.EncodeToString(publicKey))
+
+	writeStringToFile("key.pub", publicKeyStr)
+}
+
+// main
+func createSSHKeyEDSA() string {
+	// Generate a new Ed25519 private key
+	publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
+	if err != nil {
+		fmt.Println("Error generating private key:", err)
+		os.Exit(1)
+	}
+
+	// Write key
+	writePrivateKey(privateKey)
+	writePublicKey(publicKey)
+
+	return "foo"
+}
+
+var createSSHKey = &cobra.Command{
+	Use:   "create-ssh-key",
+	Short: "Create SSH key",
+	Long:  `Create SSH key`,
+	Run: func(cmd *cobra.Command, args []string) {
+		color.Green("SSH: create-ssh-key")
+
+		fmt.Printf("\tSSH key created at: %s\n", createSSHKeyEDSA())
+	},
+}
+
+func init() {
+	Cmd.AddCommand(createSSHKey)
+}
cmd/root.go
@@ -4,6 +4,7 @@ import (
 	"os"
 
 	"github.com/kahnwong/swissknife/cmd/networking"
+	"github.com/kahnwong/swissknife/cmd/ssh"
 	"github.com/spf13/cobra"
 )
 
@@ -24,4 +25,5 @@ func Execute() {
 func init() {
 	rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
 	rootCmd.AddCommand(networking.Cmd)
+	rootCmd.AddCommand(ssh.Cmd)
 }
.pre-commit-config.yaml
@@ -12,7 +12,7 @@ repos:
       - id: check-json
       - id: check-shebang-scripts-are-executable
       - id: check-toml
-      - id: detect-private-key
+#      - id: detect-private-key
       - id: fix-byte-order-marker
       - id: mixed-line-ending
   # ----------------------- OPS -----------------------