Select Git revision
encryption.go
encryption.go 1.58 KiB
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 {
keyBytes := []byte(key)
h := hmac.New(sha256.New, keyBytes)
h.Write([]byte(input))
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
func Md5HashString(bytesToHash []byte) string {
hash := md5.Sum(bytesToHash)
hashString := fmt.Sprintf("%X", hash)
return hashString
}
func Encrypt(plaintext string, key string) (string, error) {
if len(key) != 32 {
return "", errors.New("key should be 32 bytes")
}
block, err := aes.NewCipher([]byte(key))
if err != nil {
return "", err
}
aesGcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonce := make([]byte, aesGcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
return string(aesGcm.Seal(nonce, nonce, []byte(plaintext), nil)), nil
}
func Decrypt(ciphertext string, key string) (string, error) {
if len(key) != 32 {
return "", errors.New("key should be 32 bytes")
}
block, err := aes.NewCipher([]byte(key))
if err != nil {
return "", err
}
aesGcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonceSize := aesGcm.NonceSize()
if len(ciphertext) < nonceSize {
return "", errors.New("ciphertext too short")
}