krypto

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2025 License: Apache-2.0 Imports: 23 Imported by: 0

README

Beaver Kit - Krypto

A comprehensive and secure cryptographic utilities package for Go applications. The krypto package provides a collection of commonly needed cryptographic operations with a stable API designed to be reliable and future-proof.

Installation

go get github.com/gobeaver/beaver-kit/krypto

Features

  • Password Hashing

    • Argon2id implementation with secure salt generation
    • Bcrypt implementation with configurable work factor
  • Token Management

    • JWT token generation and validation (HS256)
    • Secure random token generation
    • OTP (One-Time Password) generation
  • Encryption

    • AES-GCM encryption and decryption
    • RSA key pair generation and validation
  • Hashing

    • SHA-256 hashing with verification
  • Security Utilities

    • Random delay function to prevent timing attacks

Configuration

The package can be initialized with environment variables:

import (
    "github.com/gobeaver/beaver-kit/config"
    "github.com/gobeaver/beaver-kit/krypto"
)

// Initialize configuration
loader := config.NewLoader()
krypto.InitConfig(loader)

Environment variables:

  • KRYPTO_JWT_KEY: Secret key for JWT signing
  • KRYPTO_RSA_PATH: Path to RSA key files
  • KRYPTO_TOKEN_SECRET: Secret for token generation

Examples

Password Hashing (Argon2id)
// Hash a password
hashedPassword, err := krypto.Argon2idHashPassword("secure_password")
if err != nil {
    // Handle error
}

// Verify a password
match, err := krypto.Argon2idVerifyPassword("secure_password", hashedPassword)
if err != nil {
    // Handle error
}
JWT Token Handling
// Create user claims
claims := krypto.UserClaims{
    First: "John",
    Last: "Doe",
    Token: "user-identifier",
    StandardClaims: jwt.StandardClaims{
        ExpiresAt: time.Now().Add(time.Hour * 24).Unix(),
    },
}

// Generate access token
token, err := krypto.NewHs256AccessToken(claims)
if err != nil {
    // Handle error
}

// Parse and validate token
parsedClaims, err := krypto.ParseHs256AccessToken(token)
if err != nil {
    // Handle error
}
Secure Token Generation
// Generate a secure random token
token, err := krypto.GenerateSecureToken(32)
if err != nil {
    // Handle error
}

// Generate OTP
otp := krypto.GenerateOTP(6)
AES Encryption
// Create encryption service
aesService := krypto.NewAESGCMService("your-encryption-key")

// Encrypt data
encrypted, err := aesService.Encrypt([]byte("sensitive data"))
if err != nil {
    // Handle error
}

// Decrypt data
decrypted, err := aesService.Decrypt(encrypted)
if err != nil {
    // Handle error
}

Security Considerations

This package follows best practices for cryptographic implementations:

  • Uses cryptographically secure random number generation
  • Implements proper error handling for all cryptographic operations
  • Uses modern algorithms with appropriate parameters
  • Avoids timing attacks with random delays where appropriate

For detailed API documentation, see the doc.md file.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Argon2idHashPassword

func Argon2idHashPassword(password string) (string, error)

Argon2idHashPassword generates an Argon2id hash from the provided password. It uses a cryptographically secure random salt and configurable parameters for iterations, memory, parallelism, and key length to generate the hash. The generated hash is encoded in a string format containing information about the hash parameters and the encoded hash itself.

Parameters:

password: The plaintext password to be hashed.

Returns:

string: The hashed password encoded in a string format containing hash parameters.
error: An error, if any, encountered during the hashing process.

func Argon2idVerifyPassword added in v0.0.2

func Argon2idVerifyPassword(password, encodedHash string) (bool, error)

Argon2idVerifyPassword verifies a password against an Argon2id hash. It parses the encoded hash string to extract the parameters and salt used to create the original hash, then applies the same parameters to the input password to verify if it matches the stored hash. This function uses constant-time comparison to prevent timing attacks.

Parameters:

password: The plaintext password to verify.
encodedHash: The encoded hash string to verify against, as returned by Argon2idHashPassword.

Returns:

bool: True if the password matches the hash, false otherwise.
error: An error if the hash format is invalid or parameters couldn't be parsed.

func BcryptCheckPasswordHash

func BcryptCheckPasswordHash(password, hash string) bool

func BcryptHashPassword

func BcryptHashPassword(password string) (string, error)

BcryptHashPassword generates a bcrypt hash from the provided password using a cost factor of 12. It returns the hashed password as a string.

Parameters:

password: The plaintext password to be hashed.

Returns:

string: The hashed password.
error: An error, if any, encountered during the hashing process.

func GenerateAESKey added in v0.0.2

func GenerateAESKey(keySize int) (string, error)

func GenerateJWTFile

func GenerateJWTFile(jwtClaims jwt.Claims, filePath string) (string, error)

GenerateJWTFile generates a JWT token using a private key

func GenerateOTP

func GenerateOTP(length int) string

GenerateOTP generates a random One-Time Password (OTP) of the specified length. It uses a cryptographically secure random number generator to ensure the randomness of the generated OTP.

Parameters:

length: The length of the OTP to be generated.

Returns:

string: The randomly generated OTP.

func GenerateRandomString

func GenerateRandomString(length int) string

GenerateRandomString generates a random string of the specified length. It utilizes a pseudo-random number generator seeded with the current time to ensure randomness in the generated string.

Parameters:

length: The length of the random string to be generated.

Returns:

string: The randomly generated string.

func GenerateSecureToken

func GenerateSecureToken(length int) (string, error)

GenerateSecureToken generates a secure token of the specified length. It utilizes the cryptographic randomness provided by the rand package to ensure the security and unpredictability of the generated token.

Parameters:

length: The length of the secure token to be generated.

Returns:

string: The randomly generated secure token in hexadecimal format.
error: An error, if any, encountered during the token generation process.

func GenerateToken64

func GenerateToken64() string

func HashSHA256

func HashSHA256(input string) string

HashSHA256 hashes the input string using SHA-256 algorithm.

Parameters:

input (string): The input string to be hashed.

Returns:

string: The hexadecimal representation of the hashed value.

func NewHs256AccessToken

func NewHs256AccessToken(claims UserClaims) (string, error)

func NewHs256RefreshToken

func NewHs256RefreshToken(claims jwt.RegisteredClaims) (string, error)

func ParseHs256RefreshToken

func ParseHs256RefreshToken(refreshToken string) *jwt.RegisteredClaims

func RandomDelayWithRange added in v0.0.2

func RandomDelayWithRange(min, max float64)

RandomDelayWithRange introduces a non-deterministic delay in program execution to help mitigate timing-based attacks. This is particularly useful when:

  1. Processing sensitive operations (login attempts, password resets, etc.) to mask whether the operation was successful or failed based on response time
  2. Preventing rate limiting bypass attempts by making the exact execution time unpredictable
  3. Mitigating timing side-channel attacks that could leak information about the system's internal state or operations
  4. Adding jitter to API responses to prevent attackers from inferring server-side processing patterns

Parameters:

min: minimum delay in seconds
max: maximum delay in seconds

Example usage:

// Add random delay between 0.5 and 2 seconds after failed login attempts
if loginAttemptFailed {
    delayRandomly(0.5, 2)
}

// Add jitter to API response timing
func handleSensitiveRequest() {
    delayRandomly(0.1, 0.5)
    // ... process request
}

Security considerations:

  • Ensure the random number generator is properly seeded (rand.Seed())
  • Consider the tradeoff between security and user experience when setting delays
  • Be aware that very short delays may not effectively mask timing differences
  • For cryptographic operations, consider using crypto/rand instead of math/rand

func RetryGenerateSecureToken

func RetryGenerateSecureToken(length int, retries int) (string, error)

func ValidateJWT

func ValidateJWT(tokenString string) (jwt.MapClaims, error)

ValidateJWT validates a JWT token using a public key

func ValidateRSAKeyPair

func ValidateRSAKeyPair(keyPair PublicPrivatePair) (bool, error)

ValidateRSAKeyPair validates an RSA key pair by encrypting and decrypting a message. It returns true if the validation succeeds, indicating that the key pair is valid. Otherwise, it returns false.

Parameters:

keyPair: The RSA public and private keys encoded in PEM format.

Returns:

bool: A boolean indicating whether the key pair is valid.
error: An error, if any, encountered during the validation process.

func VerifySHA256

func VerifySHA256(input, hashedValue string) bool

VerifySHA256 verifies if the input matches the hashed value.

Parameters:

input (string): The input string to be verified.
hashedValue (string): The hashed value to be compared with the hashed input.

Returns:

bool: Returns true if the input matches the hashed value; otherwise, returns false.

Types

type GenerateJwt

type GenerateJwt interface {
	GenerateJwtFile(claims jwt.Claims, filePath string) (string, error)
}

type PublicPrivatePair

type PublicPrivatePair struct {
	PrivateKey string
	PublicKey  string
}

func GenerateRSAKeyPair

func GenerateRSAKeyPair() (PublicPrivatePair, error)

GenerateRSAKeyPair generates a pair of RSA public and private keys with a key size of 2048 bits. It returns the public and private keys encoded in PEM format.

Returns:

PublicPrivatePair: A struct containing the RSA public and private keys
error: An error, if any, encountered during the key pair generation process.

type Service added in v0.0.2

type Service interface {
	Encrypt(data []byte) (ciphertext, nonce []byte, err error)
	Decrypt(ciphertext, nonce []byte) ([]byte, error)
	EncryptString(plaintext string) (ciphertextB64, nonceB64 string, err error)
	DecryptString(ciphertextB64, nonceB64 string) (string, error)
}

Service defines the interface for encryption operations

func NewAESGCMService added in v0.0.2

func NewAESGCMService(key string) (Service, error)

NewAESGCMService creates a new AES-GCM encryption service

type UserClaims

type UserClaims struct {
	First string `json:"first"`
	Last  string `json:"last"`
	Token string `json:"token"`
	jwt.RegisteredClaims
}

func ParseHs256AccessToken

func ParseHs256AccessToken(accessToken string) (*UserClaims, error)

Jump to

Keyboard shortcuts

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