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

Merge branch 'main' of gitlab.bob.co.za:bob-public-utils/bobgroup-go-utils

parents 9ef8ea8f 4869843d
Branches
Tags v1.123.0
No related merge requests found
...@@ -111,6 +111,60 @@ func DecryptStruct(encryptedStruct string, key string, object any) error { ...@@ -111,6 +111,60 @@ func DecryptStruct(encryptedStruct string, key string, object any) error {
return nil return nil
} }
func EncryptByteArray(byteArray []byte, 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
}
encryptedValue := string(aesGcm.Seal(nonce, nonce, byteArray, nil))
return base64.StdEncoding.EncodeToString([]byte(encryptedValue)), nil
}
func DecryptByteArray(encryptedByteArray []byte, key string, object any) 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(encryptedByteArray) < nonceSize {
return errors.New("ciphertext too short")
}
nonce, ciphertext := encryptedByteArray[:nonceSize], encryptedByteArray[nonceSize:]
value, err := aesGcm.Open(nil, nonce, ciphertext, nil)
err = json.Unmarshal(value, object)
if err != nil {
return err
}
return nil
}
func Encrypt(plaintext string, key string) (string, error) { func Encrypt(plaintext string, key string) (string, error) {
if len(key) != 32 { if len(key) != 32 {
return "", errors.New("key should be 32 bytes") return "", errors.New("key should be 32 bytes")
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment