97 lines
2.1 KiB
Go
97 lines
2.1 KiB
Go
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"os"
|
|
|
|
"custodial/pkg/crypto"
|
|
)
|
|
|
|
var KEY_DIR string = os.Getenv("KEYPAIR_DIR")
|
|
|
|
func main() {
|
|
var command string = ""
|
|
if len(os.Args) > 1 {
|
|
command = os.Args[1]
|
|
}
|
|
|
|
switch command {
|
|
case "generate":
|
|
if len(os.Args) < 3 {
|
|
fmt.Println("Usage: keypair generate <dir>")
|
|
os.Exit(1)
|
|
}
|
|
kp, err := crypto.KeyPair{}.Random()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
kp.Save(os.Args[2])
|
|
case "encrypt":
|
|
EnvWarn()
|
|
kp := crypto.KeyPair{}.Load(KEY_DIR)
|
|
pub := kp.PublicKeyBase64()
|
|
NoPipe(func() {
|
|
fmt.Println("Enter a string to encrypt:")
|
|
fmt.Println("")
|
|
})
|
|
reader := bufio.NewReader(os.Stdin)
|
|
text, _ := reader.ReadString('\n')
|
|
NoPipe(func() {
|
|
fmt.Println("Result:")
|
|
fmt.Println("")
|
|
})
|
|
fmt.Println(pub.EncryptToString(text))
|
|
case "decrypt":
|
|
EnvWarn()
|
|
kp := crypto.KeyPair{}.Load(KEY_DIR)
|
|
priv := kp.PrivateKeyBase64()
|
|
NoPipe(func() {
|
|
fmt.Println("Enter a string to decrypt:")
|
|
fmt.Println("")
|
|
})
|
|
reader := bufio.NewReader(os.Stdin)
|
|
text, _ := reader.ReadString('\n')
|
|
NoPipe(func() {
|
|
fmt.Println("Result:")
|
|
fmt.Println("")
|
|
})
|
|
fmt.Println(priv.DecryptToString(text))
|
|
case "":
|
|
fmt.Println("Usage: keypair [command]")
|
|
fmt.Println("")
|
|
fmt.Println("Commands:")
|
|
fmt.Println(" generate <dir> - Generate a new keypair and save it to <dir>")
|
|
fmt.Println(" encrypt - Encrypt a string using the public key")
|
|
fmt.Println(" decrypt - Decrypt a string using the private key")
|
|
fmt.Println("")
|
|
fmt.Println("Flags:")
|
|
fmt.Println(" --pipe - Pipe the result to stdout")
|
|
fmt.Println("")
|
|
fmt.Println("Environment Variables:")
|
|
fmt.Println(" KEYPAIR_DIR - The directory where the keypair is stored, defaults to the current working directory")
|
|
}
|
|
}
|
|
|
|
func NoPipe(cb func()) {
|
|
var isPipe bool = false
|
|
if os.Args[len(os.Args)-1] == "--pipe" {
|
|
isPipe = true
|
|
}
|
|
if isPipe {
|
|
return
|
|
} else {
|
|
cb()
|
|
}
|
|
}
|
|
|
|
func EnvWarn() {
|
|
if KEY_DIR == "" {
|
|
NoPipe(func() {
|
|
fmt.Println("Warning: KEYPAIR_DIR environment variable not set")
|
|
fmt.Println("Using current working directory")
|
|
})
|
|
KEY_DIR, _ = os.Getwd()
|
|
}
|
|
}
|