diff --git a/encryption/encryption.go b/encryption/encryption.go index fd5959d5326fc648a0e9e4b1ef37ed7b60ced01d..12eb442f37ba6b6a214e682e2c3ffac013ffa0a1 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) +}