hash

package
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Jan 29, 2026 License: MIT Imports: 10 Imported by: 0

README

Hash - Security Module (gokit)

Módulo de hashing de contraseñas de gokit.
Soporta bcrypt y Argon2id, con autodetección de algoritmo, configuración global y API profesional.

Diseñado para ser seguro por defecto, flexible y fácil de integrar en cualquier proyecto Go.


✨ Características

  • 🔐 Hashing con bcrypt y Argon2id
  • 🤖 Autodetección de algoritmo (bcrypt / argon2)
  • ⚙️ Configuración global
  • 🧩 API unificada (Hash / Verify)
  • 🛡️ Comparación en tiempo constante
  • 🔄 Soporte para rehash automático
  • 🔑 Generación de tokens seguros
  • 📏 Validación de contraseñas (longitud mínima/máxima)

📦 Instalación

go get github.com/AndresGT/gokit/security/hash

🚀 Uso Básico

Hash de contraseña
import "github.com/AndresGT/gokit/security/hash"

hashed, err := hash.Hash("password123")
if err != nil {
	panic(err)
}

fmt.Println(hashed)
Verificar contraseña
ok, err := hash.Verify("password123", hashed)
if err != nil {
	panic(err)
}

if ok {
	fmt.Println("Password válido")
}

⚙️ Configuración

Puedes configurar el algoritmo y parámetros globalmente:

import "github.com/AndresGT/gokit/security/hash"

func init() {
	hash.Configure(hash.Config{
		Algorithm:  hash.AlgArgon2, // o hash.AlgBcrypt
		BcryptCost: 12,
		MinLength:  8,
		MaxLength:  128,
		Argon2: hash.Argon2Params{
			Memory:      64 * 1024,
			Iterations:  3,
			Parallelism: 2,
			SaltLength:  16,
			KeyLength:   32,
		},
	})
}

🧠 Algoritmos soportados

bcrypt (default)
  • Rápido y ampliamente soportado
  • Recomendado para la mayoría de aplicaciones
Argon2id
  • Más seguro y resistente a ataques GPU/ASIC
  • Recomendado para sistemas críticos

🔄 Autodetección de algoritmo

No necesitas saber qué algoritmo se usó:

ok, _ := hash.Verify("password123", hashed)

El módulo detecta automáticamente si el hash es bcrypt o Argon2id.


🔄 Rehash

Puedes detectar si un hash necesita ser regenerado:

if hash.NeedsRehash(hashed) {
	newHash, _ := hash.Hash("password123")
}

Ejemplo típico: migrar bcrypt → Argon2.


🔑 Tokens Seguros

Token aleatorio
token, _ := hash.GenerateRandomToken(32)
Token seguro (256 bits)
token, _ := hash.GenerateSecureToken()

📏 Validación de contraseñas

Por defecto:

  • mínimo: 8 caracteres
  • máximo: 128 caracteres

Ejemplo de error:

hashed, err := hash.Hash("123")
// error: password must be at least 8 characters

🧪 Ejemplo Completo

func main() {
	hash.Configure(hash.Config{
		Algorithm: hash.AlgBcrypt,
	})

	password := "super-secret"

	hashed, _ := hash.Hash(password)

	ok, _ := hash.Verify(password, hashed)

	fmt.Println("Valid:", ok)
}

🔐 Buenas Prácticas

  • Usa Argon2id para sistemas críticos.
  • Usa bcrypt para sistemas estándar.
  • No guardes contraseñas en texto plano.
  • Usa longitud mínima >= 8.
  • Migra hashes antiguos con NeedsRehash.
  • Nunca expongas hashes en logs.

📄 Licencia

MIT



Parte de gokit — módulo de hashing listo para producción.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Configure

func Configure(cfg Config)

func GenerateRandomToken

func GenerateRandomToken(length int) (string, error)

func GenerateSecureToken

func GenerateSecureToken() (string, error)

func Hash

func Hash(password string) (string, error)

Hash genera un hash usando el algoritmo configurado

func NeedsRehash

func NeedsRehash(hash string) bool

func Verify

func Verify(password, hash string) (bool, error)

Verify verifica un password contra cualquier tipo de hash

Types

type Algorithm

type Algorithm string
const (
	AlgBcrypt Algorithm = "bcrypt"
	AlgArgon2 Algorithm = "argon2id"
)

type Argon2Params

type Argon2Params struct {
	Memory      uint32
	Iterations  uint32
	Parallelism uint8
	SaltLength  uint32
	KeyLength   uint32
}

type Config

type Config struct {
	Algorithm  Algorithm
	BcryptCost int
	Argon2     Argon2Params
	MinLength  int
	MaxLength  int
}

Jump to

Keyboard shortcuts

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