Skip to content

Commit

Permalink
force gc after decryption attempt
Browse files Browse the repository at this point in the history
  • Loading branch information
arriven committed Apr 23, 2022
1 parent c03518e commit 9492861
Showing 1 changed file with 19 additions and 12 deletions.
31 changes: 19 additions & 12 deletions src/utils/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package utils
import (
"bytes"
"io/ioutil"
"runtime"
"strings"
"sync"

Expand Down Expand Up @@ -53,7 +54,7 @@ func IsEncrypted(cfg []byte) bool {
}

// Decrypt decrypts config using EncryptionKeys
func Decrypt(cfg []byte) ([]byte, error) {
func Decrypt(cfg []byte) (result []byte, err error) {
keys, err := GetEncryptionKeys()
if err != nil {
return nil, err
Expand All @@ -62,25 +63,31 @@ func Decrypt(cfg []byte) ([]byte, error) {
decryptMutex.Lock()
defer decryptMutex.Unlock()

var lastErr error
// iterate over all keys and return on first success decryption
for _, key := range keys {
identity, err := age.NewScryptIdentity(key)
if err != nil {
lastErr = err
result, err = decrypt(cfg, key)
runtime.GC() // force GC to decrease memory usage

if err != nil {
continue
}

decryptedReader, err := age.Decrypt(bytes.NewReader(cfg), identity)
if err != nil {
lastErr = err
return result, nil
}

continue
}
return nil, err
}

return ioutil.ReadAll(decryptedReader)
func decrypt(cfg []byte, key string) ([]byte, error) {
identity, err := age.NewScryptIdentity(key)
if err != nil {
return nil, err
}

decryptedReader, err := age.Decrypt(bytes.NewReader(cfg), identity)
if err != nil {
return nil, err
}

return nil, lastErr
return ioutil.ReadAll(decryptedReader)
}

0 comments on commit 9492861

Please sign in to comment.