Im doing a hashed password generator, i have an endpoint at the server that generates a goroutine to create the hashed password, and then send it as a response when the goroutine ends.
this is the function that is called to generate the hashed password
func SetHash(c echo.Context) error {
hashedhPassword := make(chan string)
var wg sync.WaitGroup
wg.Add(2)
go utils.GenerateSaltedHashAsync("demoprueba", wg, hashedhPassword)
return response.Success(c, map[string]string{
"salt": <-hashedhPassword,
})
}
and this is the hashing class
package utils
import (
"encoding/base64"
"fmt"
"golang.org/x/crypto/argon2"
"sync"
"tigoApi/config"
)
const (
Time = 4
Memory = 64 * 1024
KeyLen = 80
Threads = 10
)
var environment = config.Instance()
func GenerateSaltedHashAsync(password string,wg sync.WaitGroup, hashedPassword chan string) {
cryptoKey := argon2.IDKey([]byte(password), []byte(environment.SaltedPassword), Time, Memory, uint8(Threads), KeyLen)
encodedPassword := base64.StdEncoding.EncodeToString(cryptoKey)
consoleHash := fmt.Sprintf("%s$%d$%d$%d$%d$%s$%s", environment.PepperPassword, Time, Memory, Threads, KeyLen, environment.SaltedPassword, encodedPassword)
defer wg.Done()
hashedPassword <- consoleHash
wg.Wait()
}
everything works fine when i do a single request, however when i send multiple requests at once(stress test) the app send this error.
panic: sync: negative WaitGroup counter
goroutine 1566 [running]: sync.(*WaitGroup).Add(0xc0001320a0,
0xffffffffffffffff)
/usr/local/go/src/sync/waitgroup.go:74 +0x139 sync.(*WaitGroup).Done(0xc0001320a0)
/usr/local/go/src/sync/waitgroup.go:99 +0x34 tigoApi/utils.GenerateSaltedHashAsync(0x8e5324, 0xa, 0x0, 0x2,
0xc000226240)
/home/crdzbird/goApps/src/tigoApi/utils/hashing.go:46 +0x3cc created by tigoApi/controller.SetHash
/home/crdzbird/goApps/src/tigoApi/controller/user_controller.go:23
+0xcd
Process finished with exit code 2
please anyone can tell me what is wrong with the code.
UPDATE.
Thanks to the suggestions the code working should be like this...
func SetHash(c echo.Context) error {
hashedhPassword := make(chan string)
go utils.GenerateSaltedHashAsync("lacb2208", hashedhPassword)
return response.Success(c, map[string]string{
"salt": <-hashedhPassword,
})
}
func GenerateSaltedHashAsync(password string, hashedPassword chan string) {
cryptoKey := argon2.IDKey([]byte(password), []byte(environment.SaltedPassword), Time, Memory, uint8(Threads), KeyLen)
encodedPassword := base64.StdEncoding.EncodeToString(cryptoKey)
consoleHash := fmt.Sprintf("%s$%d$%d$%d$%d$%s$%s", environment.PepperPassword, Time, Memory, Threads, KeyLen, environment.SaltedPassword, encodedPassword)
hashedPassword <- consoleHash
close(hashedPassword)
}
See Question&Answers more detail:
os