package auth
import "golang.org/x/crypto/bcrypt"
func HashPassword(pw string, cost int) ([]byte, error) {
if cost == 0 {
cost = bcrypt.DefaultCost
}
return bcrypt.GenerateFromPassword([]byte(pw), cost)
}
func CheckPassword(hash []byte, pw string) bool {
return bcrypt.CompareHashAndPassword(hash, []byte(pw)) == nil
}
Never store passwords as raw strings, and don’t invent your own hashing scheme. I use bcrypt with a cost that’s calibrated for the environment (fast enough for login throughput, slow enough to resist offline cracking). The trick is to treat the cost as config and revisit it periodically as hardware changes. I also compare hashes with bcrypt.CompareHashAndPassword and keep error messages generic so attackers can’t distinguish “user missing” vs “bad password.” In addition, I re-hash on login if the stored hash is below the current cost, which lets you upgrade security gradually without forcing resets. This snippet is simple, but it represents a core part of user security. Pair it with rate limiting and MFA and you get a modern baseline.
Related snips
package api
import (
"net/http"
"runtime/debug"
)
Expose build metadata for debugging deploys
payload = {
sub: user.id,
iss: 'https://auth.example.com',
aud: 'codesnips-api',
exp: 15.minutes.from_now.to_i,
iat: Time.now.to_i,
JWT issuance and verification without common footguns
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
#!/usr/bin/env bash
set -euo pipefail
export VAULT_ADDR="https://vault.internal:8200"
export VAULT_TOKEN="${VAULT_TOKEN:?missing VAULT_TOKEN}"
Secrets management with environment isolation and Vault
import { randomBytes, createHash } from "crypto";
import jwt from "jsonwebtoken";
import { RefreshTokenStore } from "./store";
const ACCESS_SECRET = process.env.ACCESS_SECRET!;
const ACCESS_TTL = "15m";
JWT access + refresh token rotation (conceptual)
package files
import (
"context"
"time"
Presigned S3 upload URLs (AWS SDK v2)
Share this code
Here's the card — post it anywhere.