summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore2
-rw-r--r--go.mod5
-rw-r--r--go.sum2
-rw-r--r--main.go94
4 files changed, 103 insertions, 0 deletions
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)
+}