argon2

package module
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 8, 2025 License: MIT Imports: 7 Imported by: 1

README

Argon2

Overview

This Go package provides a simple set of tools to generate and validate Argon2id password hashes using the golang.org/x/crypto/argon2 package.

It also includes utilities for managing Argon2 hashing settings and supports seamless integration with SQL databases by implementing the sql.Scanner and driver.Value interfaces.

Features

  • Generate Argon2id password hashes.
  • Validate hashed passwords.
  • Manage and serialize Argon2 settings.
  • Store and retrieve hashes from SQL databases.

Usage

Generating a Hash
package main

import (
	"fmt"
    
	"github.com/wneessen/argon2"
)

func main() {
	hash, err := argon2.Derive("my_secure_password", argon2.DefaultSettings)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Generated Hash: %x\n", hash)
}
Validating a Password
package main

import (
	"fmt"

	"github.com/wneessen/argon2"
)

func main() {
	hash, err := argon2.Derive("my_secure_password", argon2.DefaultSettings)
	if err != nil {
		panic(err)
	}
	isValid := hash.Validate("my_secure_password")
	if isValid {
		fmt.Println("Password is valid!")
	} else {
		fmt.Println("Invalid password!")
	}
}
Using Custom Argon2 Settings
package main

import (
	"fmt"

	"github.com/wneessen/argon2"
)

func main() {
	settings := argon2.NewSettings(65536, 3, 2, 32, 32)
	hash, err := argon2.Derive("my_secure_password", settings)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Generated Hash: %x\n", hash)
}

License

This project is licensed under the MIT License. See the LICENSE file for details.

Author

Developed by Winni Neessen wn@neessen.dev

Documentation

Overview

Package argon2 provides a simple set of tools to generate and validate Argon2id hashes using the underlying golang.org/x/crypto package.

Index

Constants

View Source
const SerializedSettingsLength = 18

SerializedSettingsLength defines the fixed size in bytes required to serialize the Settings struct using little-endian encoding.

Variables

View Source
var DefaultSettings = Settings{
	Memory:     1024 * 1024,
	Time:       2,
	Threads:    4,
	SaltLength: 16,
	KeyLength:  32,
}

DefaultSettings is the default configuration for Argon2 hashing.

This variable provides default values for the `Settings` struct that can be used in hash derivation and validation when custom settings are not specified. The values are chosen to provide a reasonable balance between security and performance, suitable for most general use cases.

The default settings are as follows:

  • Memory: 1536 MB (1536 * 1024 KB)
  • Time: 2 iterations
  • Threads: 4 parallel threads
  • SaltLength: 16 bytes for the salt
  • KeyLength: 32 bytes for the derived key

Functions

This section is empty.

Types

type Argon2

type Argon2 []byte

Argon2 represents a slice of bytes used for storing Argon2 password hash or derived key.

func Derive

func Derive(password string, settings Settings) (Argon2, error)

Derive generates an Argon2id hash using the provided password and settings.

This function generates a random salt of the specified length from the provided settings and serializes the settings to create a hash. It then derives an Argon2id key based on the password, salt, and settings, and combines the serialized settings, salt, and derived key into a final hash. The resulting hash is returned along with any errors encountered during the process.

Parameters:

  • password: The password to derive the key from. This should be a string.
  • settings: A Settings struct containing parameters for Argon2 hash generation.

Returns:

  • A byte slice containing the concatenated serialized settings, salt, and derived key.
  • An error if any issues occur during salt generation or key derivation.

func (Argon2) Key added in v0.0.2

func (a Argon2) Key() []byte

Key extracts and returns the derived key from the Argon2 hash.

This method retrieves the key that was generated during the Argon2 key derivation process. If the stored Argon2 hash is shorter than the expected serialized settings length, it returns an empty byte slice.

Steps performed:

  • Copies the Argon2 hash to avoid modifying the original data.
  • Checks if the data length is valid; if not, returns an empty slice.
  • Extracts the Settings from the serialized portion of the hash.
  • Returns the derived key portion of the hash based on the extracted settings.

Returns:

  • A byte slice containing the derived key extracted from the Argon2 hash.
  • If the stored data is invalid or too short, an empty slice is returned.

func (Argon2) Salt added in v0.0.2

func (a Argon2) Salt() []byte

Salt extracts and returns the salt from the Argon2 hash.

This method retrieves the salt used during the Argon2 key derivation process. If the stored Argon2 hash is shorter than the expected serialized settings length, it returns an empty byte slice.

Steps performed:

  • Copies the Argon2 hash to avoid mutating the original data.
  • Checks if the data length is valid; if not, returns an empty slice.
  • Extracts the Settings from the serialized portion of the hash.
  • Returns the salt portion of the hash based on the extracted settings.

Returns:

  • A byte slice containing the salt extracted from the Argon2 hash.
  • If the stored data is invalid or too short, an empty slice is returned.

func (*Argon2) Scan

func (a *Argon2) Scan(src any) error

Scan implements the sql.Scanner interface so Argon2 can be read from databases transparently. Currently, database types that map to string and []byte are supported.

func (Argon2) Validate

func (a Argon2) Validate(password string) bool

Validate verifies whether the given password matches the Argon2 hash.

This method takes a plaintext password and checks if it matches the stored Argon2 hash. It ensures that even if an invalid or zero-length byte slice is passed, the function still executes the Argon2 key derivation function (KDF) with default settings to prevent timing attacks.

Steps performed:

  • Copies the Argon2 hash data to prevent mutation.
  • If the input data is too short or empty, it falls back to `DefaultSettings` and generates a random salt and key.
  • If the stored hash does not match the expected structure (e.g., incorrect key length), it regenerates random values to avoid leaking information about tampered or invalid hashes.
  • Computes the Argon2 key from the provided password using the extracted settings and salt.
  • Compares the derived key with the stored key using subtle.ConstantTimeCompare.

Parameters:

  • password: The plaintext password to validate against the Argon2 hash.

Returns:

  • true if the password is valid and matches the stored Argon2 hash.

Security considerations:

  • Even when an invalid hash is provided, the function executes the Argon2 KDF to prevent timing attacks that could hint at the validity of stored data.
  • Uses constant-time comparison to mitigate side-channel attacks.

func (Argon2) Value

func (a Argon2) Value() (driver.Value, error)

Value implements the driver.Valuer interface so that Argon2 can be written to databases transparently. Currently, Argon2 maps to a byte slice.

type Settings

type Settings struct {
	Memory     uint32
	Time       uint32
	Threads    uint8
	SaltLength uint32
	KeyLength  uint32
}

Settings holds the configuration for generating an Argon2 hash.

This struct contains the parameters required for Argon2 hashing, including memory cost, time cost, parallelism, salt length, and key length. These settings are used during both hash derivation (in the Derive function) and validation (in the `Validate` function) to configure the Argon2 algorithm according to the user's requirements.

Fields:

  • Memory: The memory cost for Argon2, specified in kilobytes. This determines how much memory Argon2 will use during the hash computation.
  • Time: The time cost for Argon2, specified as the number of iterations. This affects the computation time for generating or validating the hash.
  • Threads: The number of parallel threads to use during the hash computation. This affects the speed of the hash calculation but also impacts performance based on the hardware.
  • SaltLength: The length of the random salt in bytes. The salt is used to ensure that the same password results in different hashes when hashed multiple times with different salts.
  • KeyLength: The length of the derived key in bytes. This is the length of the hash output that will be used as the final result after Argon2 computation.

func NewSettings

func NewSettings(mem, time uint32, threads uint8, saltLen, keyLen uint32) Settings

NewSettings creates a new Settings struct with the specified parameters.

This function initializes a Settings struct with the given memory, time, threads, salt length, and key length values. It provides a convenient way to configure Argon2 key derivation settings.

Parameters:

  • mem: The amount of memory (in KB) to be used by the Argon2 algorithm.
  • time: The number of iterations (or passes) for Argon2.
  • threads: The number of parallel threads used during hashing.
  • saltLen: The length of the salt in bytes.
  • keyLen: The length of the derived key in bytes.

Returns:

  • A Settings struct initialized with the provided values.

func SettingsFromBytes

func SettingsFromBytes(p []byte) Settings

SettingsFromBytes deserializes a byte slice into a Settings struct.

This function takes a byte slice representing serialized `Settings` data and converts it back into a `Settings` struct. The byte slice must contain the serialized data in little-endian byte order, with the following field sizes and order:

  • Memory (4 bytes)
  • Time (4 bytes)
  • Threads (2 bytes, converted from uint16 to uint8)
  • SaltLength (4 bytes)
  • KeyLength (4 bytes)

The function returns a `Settings` struct with the values extracted from the byte slice.

Parameters:

  • p: A byte slice containing the serialized Settings data in little-endian byte order.

Returns:

  • A Settings struct populated with the values extracted from the byte slice.

func (Settings) Serialize

func (s Settings) Serialize() []byte

Serialize converts the Settings struct into a byte slice.

This method serializes the fields of the Settings struct into a byte slice using little-endian byte order. The resulting byte slice can be used for storage or transmission of the settings in a compact format. The serialized byte slice contains the following fields in this order:

  • Memory (4 bytes)
  • Time (4 bytes)
  • Threads (2 bytes, converted to uint16)
  • SaltLength (4 bytes)
  • KeyLength (4 bytes)

The total size of the resulting byte slice is determined by the constant `SerializedSettingsLength`.

Returns:

  • A byte slice containing the serialized Settings struct in little-endian byte order.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL