Search code examples
gogo-gormgo-templatesgo-fiber

Golang Gorm Fiber / argon2.Config undefined


I'm trying to switch from PHP to GO, but I'm stuck at one point, I ask for your help.

I'm trying to create a password hashing function using Argon2, but I keep getting the error "undefined: argon2.Config" when I use "argon2.Config{}". I've recompiled the project multiple times, but I can't seem to find a solution. I'm requesting your assistance with this issue.

func hashPassword(password string) []byte {
    // Şifreleme parametreleri
    timeCost := 1                 // İşlem süresi
    memory := 64 * 1024           // // Bellek miktarı
    threads := 4                  //  İş parçacığı sayısı
    keyLength := 32               // Oluşturulacak hash uzunluğu
    salt := []byte("unique_salt") // Her kullanıcı için benzersiz

    // Argon2 işlemi için hasher oluştur
    hasher := argon2.Config{
        Time:    uint32(timeCost),
        Memory:  uint32(memory),
        Threads: uint8(threads),
        KeyLen:  uint32(keyLength),
    }

    // Şifreyi hashle
    hashedPassword := hasher.Hash(password, salt, nil)

    return hashedPassword
}

undefined: argon2.Config


Solution

  • if you are using the package "golang.org/x/crypto/argon2" you can use argon2.IDKey() method. Here is a working example:

    func HashPassword(password string) (hashedPassword string) {
    
        const (
            timeCost  uint32 = 1         // İşlem süresi
            memory    uint32 = 64 * 1024 // // Bellek miktarı
            threads   uint8  = 4         //  İş parçacığı sayısı
            keyLength uint32 = 32        // Oluşturulacak hash uzunluğu
        )
    
        salt := []byte("unique_salt") // Her kullanıcı için benzersiz
    
        // generate hashedpassword
        hash := argon2.IDKey([]byte(password), salt, timeCost, memory, threads, keyLength)
    
        // Base64 encode the salt and hashed password.
        b64Salt := base64.RawStdEncoding.EncodeToString(salt)
        b64Hash := base64.RawStdEncoding.EncodeToString(hash)
    
        format := "$argon2id$v=%d$models=%d,t=%d,p=%d$%s$%s"
    
        // final password in recommended format
        hashedPassword = fmt.Sprintf(format, argon2.Version, memory, timeCost, threads, b64Salt, b64Hash)
        return hashedPassword
    }