Skip to content
Snippets Groups Projects
Commit 4869843d authored by Cornel Rautenbach's avatar Cornel Rautenbach
Browse files

Added encryption and decryption of byte arays

parent 024ba500
No related branches found
No related tags found
No related merge requests found
......@@ -111,6 +111,60 @@ func DecryptStruct(encryptedStruct string, key string, object any) error {
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) {
if len(key) != 32 {
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