Crypto
Cryptographic utilities — AES-256-GCM encryption, HMAC, SHA-256, and random generation.
The crypto package provides common cryptographic operations.
Random Generation
import "github.com/RAiWorks/RapidGo/v2/core/crypto"
// Random bytes
bytes, err := crypto.RandomBytes(32)
// Random hex string (64 chars for 32 bytes)
hex := crypto.RandomHex(32)
// URL-safe base64 string
b64 := crypto.RandomBase64(32)
Hashing
// SHA-256 hash
hash := crypto.SHA256Hash("hello world")
// "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
HMAC Signatures
// Sign a message
signature := crypto.HMACSign("message", "secret-key")
// Verify (constant-time comparison)
valid := crypto.HMACVerify("message", signature, "secret-key")
AES-256-GCM Encryption
// Key must be exactly 32 bytes
key := []byte("your-32-byte-encryption-key!!")
// Encrypt
encrypted, err := crypto.Encrypt("sensitive data", key)
// Decrypt
plaintext, err := crypto.Decrypt(encrypted, key)
The encrypted output is URL-safe base64 encoded and includes the GCM nonce, so each encryption of the same plaintext produces different ciphertext.
Function Reference
| Function | Description |
|---|---|
RandomBytes(n) |
n cryptographically random bytes |
RandomHex(n) |
Random hex string (2n chars) |
RandomBase64(n) |
URL-safe base64 random string |
SHA256Hash(data) |
Hex-encoded SHA-256 hash |
HMACSign(msg, key) |
HMAC-SHA256 signature |
HMACVerify(msg, sig, key) |
Constant-time HMAC verification |
Encrypt(plaintext, key) |
AES-256-GCM encryption |
Decrypt(ciphertext, key) |
AES-256-GCM decryption |