argon2

package module
v0.0.0-...-d107519 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2022 License: Apache-2.0 Imports: 6 Imported by: 0

README

🔐 argon2

Build Status

argon2 provides a pure Go implementation for Argon2 password hashing.

Intended to be a drop in replacement for lhecker's argon2 library.

tl;dr

package main

import (
    "fmt"

    "github.com/mitsimi/argon2"
)


func main() {
    argon := argon2.DefaultConfig()

    // Waaahht??! It includes magic salt generation for me ! Yasss...
    encoded, err := argon.HashEncoded([]byte("p@ssw0rd"))
    if err != nil {
        panic(err) // 💥
    }
    
    fmt.Println(string(encoded))
    // > $argon2id$v=19$m=65536,t=1,p=4$WXJGqwIB2qd+pRmxMOw9Dg$X4gvR0ZB2DtQoN8vOnJPR2SeFdUhH9TyVzfV98sfWeE

    ok, err := argon2.VerifyEncoded([]byte("p@ssw0rd"), encoded)
    if err != nil {
        panic(err) // 💥
    }
    
    matches := "no 🔒"
    if ok {
        matches = "yes 🔓"
    }
    fmt.Printf("Password Matches: %s\n", matches)
}

Example

For a fuller example check out _example/example.go for a step-by-step introduction.

go run _example/example.go

Limitations

  • Config.Parallelism is a uint8 instead of uint32 as required by the underlying crypto library
  • The crypto implementation does not support generation using Argon2d. Argon2id is now generally recommended.
  • Errors still need to be properly implemented at the Go end
    • This is mainly a case of implementing the PHC/Argon2 C++ pre-hash validation checks.

👌

Benchmarks

Benchmarks are run on each build. Follow the build badge link to check the latest status on benchmarking results via TravisCI.

Build Status

The following manual benchmark was performed on a i7-7700 @ 3.60GHz with AData DDR4 2132MHz memory.

Note:

  • The native benchmarks have now been moved into a separate branch for reference in order to keep go mod dependencies tidy.
goos: windows
goarch: amd64
pkg: github.com/mitsimi/argon2
BenchmarkHash
BenchmarkHash-8                               50          23479754 ns/op
BenchmarkNativeArgonBindingsHash
BenchmarkNativeArgonBindingsHash-8            38          31814984 ns/op
BenchmarkVerify
BenchmarkVerify-8                             49          22755661 ns/op
BenchmarkNativeArgonBindingsVerify
BenchmarkNativeArgonBindingsVerify-8          38          32342853 ns/op
BenchmarkEncode
BenchmarkEncode-8                        8693931               142 ns/op         604.42 MB/s
BenchmarkDecode
BenchmarkDecode-8                        5852835               208 ns/op         414.27 MB/s
BenchmarkSecureZeroMemory16
BenchmarkSecureZeroMemory16-8          289155232              4.09 ns/op        3914.11 MB/s
BenchmarkSecureZeroMemory64
BenchmarkSecureZeroMemory64-8          284339167              4.21 ns/op       15215.14 MB/s
BenchmarkSecureZeroMemory256
BenchmarkSecureZeroMemory256-8         160209489              7.51 ns/op       34093.00 MB/s
BenchmarkSecureZeroMemory1024
BenchmarkSecureZeroMemory1024-8         75083060              16.4 ns/op       62457.50 MB/s
BenchmarkSecureZeroMemory4096
BenchmarkSecureZeroMemory4096-8         20678958              60.3 ns/op       67922.23 MB/s
BenchmarkSecureZeroMemory1048576
BenchmarkSecureZeroMemory1048576-8         52404             22442 ns/op       46724.63 MB/s
PASS
ok      github.com/mitsimi/argon2     18.481s

Documentation

Overview

Package argon2 implements the key derivation function Argon2.

Argon2 was selected as the winner of the Password Hashing Competition and can be used to derive cryptographic keys from passwords.

Index

Constants

View Source
const (

	// ModeArgon2i uses data-independent memory access, which is
	// preferred for password hashing and password-based key derivation
	// (e.g. hard drive encryption), but it's slower as it makes
	// more passes over the memory to protect from TMTO attacks.
	ModeArgon2i

	// ModeArgon2id is a hybrid of Argon2i and Argon2d, using a
	// combination of data-depending and data-independent memory accesses,
	// which gives some of Argon2i's resistance to side-channel cache timing
	// attacks and much of Argon2d's resistance to GPU cracking attacks.
	ModeArgon2id
)
View Source
const (
	// Version10 of the Argon2 algorithm. Deprecated: Use Version13 instead.
	Version10 = 0x10

	// Version13 of the Argon2 algorithm. Recommended.
	Version13 = 0x13
)
View Source
const (
	ARGON2_MIN_TIME = uint32(1)
	ARGON2_MAX_TIME = uint32(4294967295)
)

Variables

View Source
var (
	ErrOutputPtrNull         = Error("output pointer is null")
	ErrOutputTooShort        = Error("output is too short")
	ErrOutputTooLong         = Error("output is too long")
	ErrPwdTooShort           = Error("password is too short")
	ErrPwdTooLong            = Error("password is too long")
	ErrSaltTooShort          = Error("salt is too short")
	ErrSaltTooLong           = Error("salt is too long")
	ErrAdTooShort            = Error("associated data is too short")
	ErrAdTooLong             = Error("associated data is too long")
	ErrSecretTooShort        = Error("secret is too short")
	ErrSecretTooLong         = Error("secret is too long")
	ErrTimeTooSmall          = Error("time cost is too small")
	ErrTimeTooLarge          = Error("time cost is too large")
	ErrMemoryTooLittle       = Error("memory cost is too small")
	ErrMemoryTooMuch         = Error("memory cost is too large")
	ErrLanesTooFew           = Error("too few lanes")
	ErrLanesTooMany          = Error("too many lanes")
	ErrPwdPtrMismatch        = Error("password pointer is null, but password length is not 0")
	ErrSaltPtrMismatch       = Error("salt pointer is null, but salt length is not 0")
	ErrSecretPtrMismatch     = Error("secret pointer is null, but secret length is not 0")
	ErrAdPtrMismatch         = Error("associated data pointer is null, but ad length is not 0")
	ErrMemoryAllocationError = Error("memory allocation error")
	ErrFreeMemoryCbkNull     = Error("the free memory callback is null")
	ErrAllocateMemoryCbkNull = Error("the allocate memory callback is null")
	ErrIncorrectParameter    = Error("argon2_context context is null")
	ErrIncorrectType         = Error("there is no such version of argon2")
	ErrOutPtrMismatch        = Error("output pointer mismatch")
	ErrThreadsTooFew         = Error("not enough threads")
	ErrThreadsTooMany        = Error("too many threads")
	ErrMissingArgs           = Error("missing arguments")
	ErrEncodingFail          = Error("encoding failed")
	ErrDecodingFail          = Error("decoding failed")
	ErrThreadFail            = Error("threading failure")
	ErrDecodingLengthFail    = Error("some of encoded parameters are too long or too short")
	ErrVerifyMismatch        = Error("the password does not match the supplied hash")
)

Functions

func SecureZeroMemory

func SecureZeroMemory(b []byte)

SecureZeroMemory is a helper method which sets all bytes in `b` (up to it's capacity) to `0x00`, erasing it's contents.

func VerifyEncoded

func VerifyEncoded(pwd []byte, encoded []byte) (bool, error)

VerifyEncoded returns true if `pwd` matches the encoded hash `encoded` and otherwise false.

Types

type Config

type Config struct {
	// HashLength specifies the length of the resulting hash in Bytes.
	//
	// Must be > 0.
	HashLength uint32

	// SaltLength specifies the length of the resulting salt in Bytes,
	// if one of the helper methods is used.
	//
	// Must be > 0.
	SaltLength uint32

	// TimeCost specifies the number of iterations of argon2.
	//
	// Must be > 0.
	// If you use ModeArgon2i this should *always* be >= 3 due to TMTO attacks.
	// Additionally if you can afford it you might set it to >= 10.
	TimeCost uint32

	// MemoryCost specifies the amount of memory to use in Kibibytes.
	//
	// Must be > 0.
	MemoryCost uint32

	// Parallelism specifies the amount of threads to use.
	//
	// Must be > 0.
	Parallelism uint8

	// Mode specifies the hashing method used by argon2.
	//
	// If you're writing a server and unsure what to choose,
	// use ModeArgon2i with a TimeCost >= 3.
	Mode Mode

	// Version specifies the argon2 version to be used.
	Version Version
}

Config contains all configuration parameters for the Argon2 hash function.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config struct suitable for most servers. These default settings are based on RFC9106 recommendations.

Refer:

The memory constrained settings result in around 50ms of computation time while using 64 MiB of memory during hashing. Tested on an Intel Core i7-7700 @ 3.6 GHz with DDR4 @ 2133 MHz.

func MemoryConstrainedDefaults

func MemoryConstrainedDefaults() Config

MemoryConstrainedDefaults provides configuration based on the second recommended option as described in RFC9106.

If much less memory is available, a uniformly safe option is Argon2id with t=3 iterations, p=4 lanes, m=2^(16) (64 MiB of RAM), 128-bit salt, and 256-bit tag size.

func RecommendedDefaults

func RecommendedDefaults() Config

RecommendedDefaults provides configuration based on the first recommended option as described in RFC9106.

If a uniformly safe option that is not tailored to your application or hardware is acceptable, select Argon2id with t=1 iteration, p=4 lanes, m=2^(21) (2 GiB of RAM), 128-bit salt, and 256-bit tag size.

func (*Config) Hash

func (c *Config) Hash(pwd []byte, salt []byte) (Raw, error)

Hash takes a password and optionally a salt and returns an Argon2 hash.

If salt is nil a appropriate salt of Config.SaltLength bytes is generated for you.

func (*Config) HashEncoded

func (c *Config) HashEncoded(pwd []byte) (encoded []byte, err error)

HashEncoded is a helper function around Hash() which automatically generates a salt and encodes the result for you.

func (*Config) HashRaw

func (c *Config) HashRaw(pwd []byte) (Raw, error)

HashRaw is a helper function around Hash() which automatically generates a salt for you.

type Error

type Error string

Error represents the error code returned by argon2.

func (Error) Error

func (e Error) Error() string

type Mode

type Mode uint32

Mode exists for type check purposes. See Config.

func (Mode) String

func (m Mode) String() string

String simply maps a ModeArgon{d,i,id} constant to a "Argon{d,i,id}" string or returns "unknown" if `m` does not match one of the constants.

type Raw

type Raw struct {
	Config Config
	Salt   []byte
	Hash   []byte
}

Raw wraps a salt and hash pair including the Config with which it was generated.

A Raw struct is generated using Decode() or the Hash*() methods above.

You MUST ensure that a Raw instance is not changed after creation, otherwise you risk race conditions. If you do need to change it during runtime use a Mutex and simply create a copy of your shared Raw instance in the critical section and store it on your local stack. That way your critical section is very short, while allowing you to safely call all the member methods on your local "immutable" copy.

func Decode

func Decode(encoded []byte) (Raw, error)

Decode takes a stringified/encoded argon2 hash and turns it back into a Raw struct.

This decoder ignores "data" attributes as they are likely to be deprecated.

func (*Raw) Encode

func (raw *Raw) Encode() []byte

Encode turns a Raw struct into the official stringified/encoded argon2 representation.

The resulting byte slice can safely be turned into a string.

func (*Raw) Verify

func (raw *Raw) Verify(pwd []byte) (bool, error)

Verify returns true if `pwd` matches the hash in `raw` and otherwise false.

type Version

type Version uint32

Version exists for type check purposes. See Config.

func (Version) String

func (v Version) String() string

String simply maps a Version{10,13} constant to a "{10,13}" string or returns "unknown" if `v` does not match one of the constants.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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