From c22170b4075400aac213637b315f3704ff4e90e3 Mon Sep 17 00:00:00 2001 From: DanB Date: Fri, 30 Oct 2020 20:11:02 +0100 Subject: [PATCH] Adding AESEncdrypt and AESDecrypt methods to coreutils --- utils/coreutils.go | 47 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/utils/coreutils.go b/utils/coreutils.go index 2eb362eaf..80465f03b 100644 --- a/utils/coreutils.go +++ b/utils/coreutils.go @@ -21,9 +21,12 @@ package utils import ( "archive/zip" "bytes" + "crypto/aes" + "crypto/cipher" "crypto/rand" "crypto/sha1" "encoding/gob" + "encoding/hex" "encoding/json" "errors" "fmt" @@ -946,3 +949,47 @@ type DurationArgs struct { Opts map[string]interface{} Tenant string } + +// AESEncrypt will encrypt the provided txt using the encKey and AES algorithm +func AESEncrypt(txt, encKey string) (encrypted string, err error) { + key, _ := hex.DecodeString(encKey) + var blk cipher.Block + if blk, err = aes.NewCipher(key); err != nil { + return + } + var aesGCM cipher.AEAD + if aesGCM, err = cipher.NewGCM(blk); err != nil { + return + } + nonce := make([]byte, aesGCM.NonceSize()) + if _, err = io.ReadFull(rand.Reader, nonce); err != nil { + return + } + return fmt.Sprintf("%x", aesGCM.Seal(nonce, nonce, []byte(txt), nil)), nil +} + +// AESDecrypt will decrypt the provided encrypted txt using the encKey and AES algorithm +func AESDecrypt(encrypted string, encKey string) (txt string, err error) { + + key, _ := hex.DecodeString(encKey) + enc, _ := hex.DecodeString(encrypted) + + var blk cipher.Block + if blk, err = aes.NewCipher(key); err != nil { + return + } + + var aesGCM cipher.AEAD + if aesGCM, err = cipher.NewGCM(blk); err != nil { + return + } + + nonceSize := aesGCM.NonceSize() + nonce, ciphertext := enc[:nonceSize], enc[nonceSize:] + var plaintext []byte + if plaintext, err = aesGCM.Open(nil, nonce, ciphertext, nil); err != nil { + return + } + + return fmt.Sprintf("%s", plaintext), nil +}