Allow automatic generation of GPG keys

This commit is contained in:
2024-03-07 23:35:38 -05:00
parent 7d17af9b61
commit 5a12eaf4cf
3 changed files with 50 additions and 12 deletions
+8 -5
View File
@@ -6,11 +6,14 @@ import (
func TempInitCli() {
// gpgID
//generateGPG := inputBinary("Auto-generate GPG key?")
uidSlice := offline.GpgUIDListGen()
gpgIDInt := inputMenuGen("Select GPG key:", uidSlice)
gpgID := uidSlice[gpgIDInt-1]
var gpgID string
if inputBinary("Auto-generate GPG key?") {
gpgID = offline.GpgKeyGen()
} else {
uidSlice := offline.GpgUIDListGen()
gpgIDInt := inputMenuGen("Select GPG key:", uidSlice)
gpgID = uidSlice[gpgIDInt-1]
}
// textEditor
textEditor := input("Text editor (leave blank for $EDITOR, falls back to \"vi\"):")
+18 -7
View File
@@ -12,13 +12,7 @@ func TempInit(configFileMap map[string]string) {
dirInit()
// remove existing config file
err := os.Remove(ConfigPath)
if err != nil {
// ignore error if file does not exist
if !os.IsNotExist(err) {
fmt.Println(AnsiError + "Failed to remove existing libmutton.ini:" + err.Error() + AnsiReset)
}
}
removeFile(ConfigPath)
// ensure textEditor is set
if configFileMap["textEditor"] == "" {
@@ -54,3 +48,20 @@ func GpgUIDListGen() []string {
}
return uidSlice
}
// GpgKeyGen generates a new GPG key and returns the key ID as a string
func GpgKeyGen() string {
createFile(ConfigDir+"/gpg-gen", []string{"Key-Type: eddsa", "Key-Curve: ed25519", "Key-Usage: sign", "Subkey-Type: ecdh", "Subkey-Curve: cv25519", "Subkey-Usage: encrypt", "Name-Real: libmutton", "Name-Comment: gpg-libmutton", "Name-Email: github.com/rwinkhart/libmutton", "Expire-Date: 0"})
cmd := exec.Command("gpg", "-q", "--batch", "--generate-key", ConfigDir+"/gpg-gen")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
cmd.Run()
cmd = exec.Command("gpg", "-k", "--with-colons")
gpgOutputBytes, _ := cmd.Output()
gpgOutputLines := strings.Split(string(gpgOutputBytes), "\n")
uid := strings.Split(gpgOutputLines[len(gpgOutputLines)-4], ":")[9]
fmt.Println(uid)
return uid
}
+24
View File
@@ -134,3 +134,27 @@ func EntryIsNotEmpty(entryData []string) bool {
}
return false
}
// removeFile removes a file at targetLocation and does not error if the file does not exist
func removeFile(targetLocation string) {
// remove existing config file
err := os.Remove(targetLocation)
if err != nil {
// ignore error if file does not exist
if !os.IsNotExist(err) {
fmt.Println(AnsiError + "Failed to remove \"" + targetLocation + "\":" + err.Error() + AnsiReset)
}
}
}
// createFile creates and writes a file at targetLocation with fileData - it removes the file if it already exists
func createFile(targetLocation string, fileData []string) {
removeFile(targetLocation)
file, err := os.OpenFile(targetLocation, os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
fmt.Println(AnsiError + "Failed to create \"" + targetLocation + "\":" + err.Error() + AnsiReset)
os.Exit(1)
}
defer file.Close()
file.WriteString(strings.Join(fileData, "\n"))
}