The Go crypto package is a meta-package that organizes cryptographic functionality into sub-packages; you never import crypto directly but instead import specific sub-packages like crypto/sha256 for hashing or crypto/rand for secure random number generation. Use crypto/rand for any security-sensitive randomness and crypto/sha256 (or similar) for hashing, ensuring you handle errors from Read operations correctly.
Here is a practical example of generating a secure random token and hashing a password:
package main
import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
)
func main() {
// 1. Generate a secure random token (32 bytes)
token := make([]byte, 32)
if _, err := rand.Read(token); err != nil {
panic(err) // In production, handle this error gracefully
}
fmt.Println("Secure Token:", hex.EncodeToString(token))
// 2. Hash a password using SHA-256
password := "mySecretPassword"
hash := sha256.Sum256([]byte(password))
fmt.Println("Password Hash:", hex.EncodeToString(hash[:]))
}
For public key cryptography, such as signing or verifying data, use crypto/rsa or crypto/ecdsa alongside crypto/x509 for certificate handling. Always prefer crypto/rand over math/rand for any security-related operations, as the latter is not cryptographically secure.
If you need to encrypt data, the standard library provides crypto/cipher for block ciphers like AES. You typically combine this with crypto/rand to generate a random Initialization Vector (IV). Here is a minimal example of setting up AES-GCM:
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
func encrypt(key, plaintext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
return gcm.Seal(nonce, nonce, plaintext, nil), nil
}
func main() {
// Key must be 16, 24, or 32 bytes for AES-128, 192, or 256
key := make([]byte, 32)
rand.Read(key)
ciphertext, err := encrypt(key, []byte("Secret Message"))
if err != nil {
panic(err)
}
fmt.Printf("Encrypted: %x\n", ciphertext)
}
Remember that the crypto package focuses on low-level primitives. For higher-level protocols like TLS, use the crypto/tls package or the net/http client which handles TLS automatically. Always verify that your key sizes and algorithms match current security standards, as older algorithms like MD5 or SHA-1 are deprecated for security purposes.