From 6b225af832e0f0a8793a0497eb891c089006e9f9 Mon Sep 17 00:00:00 2001
From: Johan de Klerk <johan@shiplogic.com>
Date: Mon, 24 Oct 2022 13:44:41 +0200
Subject: [PATCH] Encrypt and decrypt text

---
 encryption/encryption.go | 44 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 44 insertions(+)

diff --git a/encryption/encryption.go b/encryption/encryption.go
index fd5959d..12eb442 100644
--- a/encryption/encryption.go
+++ b/encryption/encryption.go
@@ -1,11 +1,16 @@
 package encryption
 
 import (
+	"crypto/aes"
+	"crypto/cipher"
 	"crypto/hmac"
 	"crypto/md5"
+	"crypto/rand"
 	"crypto/sha256"
 	"encoding/base64"
 	"fmt"
+	"gitlab.bob.co.za/bob-public-utils/bobgroup-go-utils/errors"
+	"io"
 )
 
 func Hash(input string, key string) string {
@@ -20,3 +25,42 @@ func Md5HashString(bytesToHash []byte) string {
 	hashString := fmt.Sprintf("%X", hash)
 	return hashString
 }
+
+func Encrypt(plaintext string, key string) (string, error) {
+	c, err := aes.NewCipher([]byte(key))
+	if err != nil {
+		return "", err
+	}
+
+	gcm, err := cipher.NewGCM(c)
+	if err != nil {
+		return "", err
+	}
+
+	nonce := make([]byte, gcm.NonceSize())
+	if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
+		return "", err
+	}
+
+	return string(gcm.Seal(nonce, nonce, []byte(plaintext), nil)), nil
+}
+
+func Decrypt(ciphertext string, key string) ([]byte, error) {
+	c, err := aes.NewCipher([]byte(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, []byte(nonce), []byte(ciphertext), nil)
+}
-- 
GitLab