crypto package collects common cryptographic constants and provides the interface for hash functions. It contains numerous subpackages implementing various cryptographic algorithms.
Key Subpackages
crypto/md5
MD5 hash algorithm. Note: MD5 is cryptographically broken and should not be used for security purposes.crypto/sha256
SHA-256 and SHA-224 hash algorithms.crypto/sha512
SHA-512, SHA-384, SHA-512/224, and SHA-512/256 hash algorithms.crypto/rand
Cryptographically secure random number generator.crypto/aes
AES (Advanced Encryption Standard) block cipher.crypto/rsa
RSA encryption and signing.crypto/ecdsa
Elliptic Curve Digital Signature Algorithm.crypto/hmac
Hash-based Message Authentication Code.crypto/tls
TLS 1.2 and TLS 1.3 protocols.crypto/x509
X.509 certificates and certificate validation.Practical Examples
Password Hashing with bcrypt
Secure Token Generation
File Encryption
Security Best Practices
- Use crypto/rand, not math/rand for cryptographic operations
- Don’t use MD5 or SHA-1 for security purposes (use SHA-256 or better)
- Always use authenticated encryption (like AES-GCM) instead of just encryption
- Use constant-time comparison (
hmac.Equal,subtle.ConstantTimeCompare) to prevent timing attacks - Generate random nonces/IVs for each encryption operation
- Use appropriate key sizes: AES-256 (32 bytes), RSA-2048+ bits
- Validate certificates in production (don’t use
InsecureSkipVerify) - Use standard libraries rather than implementing your own cryptography
Common Hash Functions
| Algorithm | Output Size | Security Status |
|---|---|---|
| MD5 | 128 bits | Broken - avoid |
| SHA-1 | 160 bits | Broken - avoid |
| SHA-224 | 224 bits | Secure |
| SHA-256 | 256 bits | Secure |
| SHA-384 | 384 bits | Secure |
| SHA-512 | 512 bits | Secure |
Key Sizes
Symmetric Encryption
- AES-128: 16 bytes (128 bits)
- AES-192: 24 bytes (192 bits)
- AES-256: 32 bytes (256 bits) - recommended
Asymmetric Encryption
- RSA: Minimum 2048 bits, recommended 3072-4096 bits
- ECDSA: P-256 (256 bits), P-384 (384 bits), P-521 (521 bits)