summaryrefslogtreecommitdiff
path: root/main.go
diff options
context:
space:
mode:
authorLevi Durfee <levi.durfee@gmail.com>2026-01-06 17:14:34 -0500
committerLevi Durfee <levi.durfee@gmail.com>2026-01-06 17:33:25 -0500
commitca629087012f6651131ea99805286423aa21c5f8 (patch)
tree92b7ce1c32c29ba6e51ff4139572dd82bb371968 /main.go
Init
Diffstat (limited to 'main.go')
-rw-r--r--main.go94
1 files changed, 94 insertions, 0 deletions
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)
+}