From ca629087012f6651131ea99805286423aa21c5f8 Mon Sep 17 00:00:00 2001 From: Levi Durfee Date: Tue, 6 Jan 2026 17:14:34 -0500 Subject: Init --- .gitignore | 2 ++ go.mod | 5 ++++ go.sum | 2 ++ main.go | 94 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 103 insertions(+) create mode 100644 .gitignore create mode 100644 go.mod create mode 100644 go.sum create mode 100644 main.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ab09693 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.env +/goaes diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..d39f532 --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module github.com/nerdsec/goaes + +go 1.25.0 + +require github.com/joho/godotenv v1.5.1 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..d61b19e --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= diff --git a/main.go b/main.go new file mode 100644 index 0000000..385c042 --- /dev/null +++ b/main.go @@ -0,0 +1,94 @@ +package main + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "encoding/base64" + "errors" + "fmt" + "io" + "log" + "os" + + "github.com/joho/godotenv" +) + +func main() { + err := godotenv.Load() + if err != nil { + log.Fatal("Error loading .env file") + } + + base64kek := os.Getenv("SECRET_KEY") + + kek, err := base64.StdEncoding.DecodeString(base64kek) + if err != nil { + panic(err) + } + + dek := GenCipherKey() + + encryptedDek, err := Encrypt(dek, kek) + if err != nil { + panic(err) + } + + fmt.Println("edek", encryptedDek) + + cipherText, err := Encrypt([]byte("hello"), dek) + if err != nil { + panic(err) + } + + fmt.Println("ciphertext", cipherText) +} + +type CipherKey []byte + +func GenCipherKey() CipherKey { + key := make([]byte, 32) + if _, err := io.ReadFull(rand.Reader, key); err != nil { + log.Fatalf("random key gen: %v", err) + } + return CipherKey(key) +} + +func Encrypt(plaintext []byte, key CipherKey) ([]byte, error) { + c, err := aes.NewCipher(key) + if err != nil { + return nil, err + } + + gcm, err := cipher.NewGCM(c) + if err != nil { + return nil, err + } + + nonce := make([]byte, gcm.NonceSize()) + if _, err = io.ReadFull(rand.Reader, nonce); err != nil { + return nil, err + } + + return gcm.Seal(nonce, nonce, plaintext, nil), nil +} + +func Decrypt(ciphertext []byte, key CipherKey) ([]byte, error) { + c, err := aes.NewCipher(key) + if err != nil { + return nil, err + } + + gcm, err := cipher.NewGCM(c) + if err != nil { + return nil, err + } + + nonceSize := gcm.NonceSize() + if len(ciphertext) < nonceSize { + return nil, errors.New("ciphertext too short") + } + + nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:] + return gcm.Open(nil, nonce, ciphertext, nil) +} -- cgit v1.2.3