Skip to content
Snippets Groups Projects
Commit 6b225af8 authored by Johan de Klerk's avatar Johan de Klerk
Browse files

Encrypt and decrypt text

parent 26e623ae
No related branches found
No related tags found
No related merge requests found
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)
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment