Skip to content

Commit

Permalink
Limit argon2 concurrency (#313)
Browse files Browse the repository at this point in the history
Control concurrent use of argon2, which is very cpu/ram intensive.

Running concurrent operations most often provides no benefit anyway,
since it already uses 32 threads.

We simply hold a package level mutex while deriving the key.
  • Loading branch information
klauspost authored Oct 24, 2024
1 parent 1e18d0d commit fae43f1
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions encrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"crypto/sha256"
"errors"
"io"
"sync"

"github.com/secure-io/sio-go"
"github.com/secure-io/sio-go/sioutil"
Expand Down Expand Up @@ -63,7 +64,9 @@ func EncryptData(password string, data []byte) ([]byte, error) {
}
id = pbkdf2AESGCM
} else {
argon2Mu.Lock()
key := argon2.IDKey([]byte(password), salt, argon2idTime, argon2idMemory, argon2idThreads, 32)
argon2Mu.Unlock()
if sioutil.NativeAES() {
stream, err = sio.AES_256_GCM.Stream(key)
if err != nil {
Expand Down Expand Up @@ -100,6 +103,12 @@ func EncryptData(password string, data []byte) ([]byte, error) {
return ciphertext.Bytes(), nil
}

// argon2Mu is used to control concurrent use of argon2,
// which is very cpu/ram intensive.
// Running concurrent operations most often provides no benefit anyway,
// since it already uses 32 threads.
var argon2Mu sync.Mutex

// ErrMaliciousData indicates that the stream cannot be
// decrypted by provided credentials.
var ErrMaliciousData = sio.NotAuthentic
Expand Down Expand Up @@ -132,10 +141,14 @@ func DecryptData(password string, data io.Reader) ([]byte, error) {
)
switch {
case id[0] == argon2idAESGCM:
argon2Mu.Lock()
key := argon2.IDKey([]byte(password), salt, argon2idTime, argon2idMemory, argon2idThreads, 32)
argon2Mu.Unlock()
stream, err = sio.AES_256_GCM.Stream(key)
case id[0] == argon2idChaCHa20Poly1305:
argon2Mu.Lock()
key := argon2.IDKey([]byte(password), salt, argon2idTime, argon2idMemory, argon2idThreads, 32)
argon2Mu.Unlock()
stream, err = sio.ChaCha20Poly1305.Stream(key)
case id[0] == pbkdf2AESGCM:
key := pbkdf2.Key([]byte(password), salt, pbkdf2Cost, 32, sha256.New)
Expand Down

0 comments on commit fae43f1

Please sign in to comment.