如何在Golang中实现数据加密_Golang crypto包加密与解密方法

用 crypto/aes 做 AES 加密必须手动补位(如 PKCS#7)和随机生成 IV 并与密文拼接;crypto/cipher 不自动补位,未对齐会静默截断;推荐改用 chacha20poly1305 等 AEAD 方案。

crypto/aes 做 AES 加密必须自己补位和处理 IV

AES 是分组密码,块大小固定为 16 字节,输入长度不是 16 的倍数时会 panic。Go 标准库不自动补位(比如 PKCS#7),你得手动做;IV(初始向量)也不能复用,否则相同明文会生成相同密文,破坏安全性。

  • 补位推荐用 PKCS#7:明文末尾填充 n 个字节,每个值都是 n,其中 n = 16 - len(plaintext)%16
  • IV 必须每次加密都随机生成,长度 16 字节,且要和密文一起传输(通常前置拼接)
  • 密钥只能是 16、24 或 32 字节(对应 AES-128/192/256),别用字符串直接转 []byte——中文或 emoji 会导致长度不可控
func pkcs7Pad(data []byte) []byte {
    padding := 16 - len(data)%16
    padtext := make([]byte, padding)
    for i := range padtext {
        padtex

t[i] = byte(padding) } return append(data, padtext...) }

func encryptAES(key, plaintext []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } plaintext = pkcs7Pad(plaintext) ciphertext := make([]byte, aes.BlockSize+len(plaintext)) iv := ciphertext[:aes.BlockSize] if _, err := io.ReadFull(rand.Reader, iv); err != nil { return nil, err } mode := cipher.NewCBCEncrypter(block, iv) mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext) return ciphertext, nil }

crypto/cipherNewCBCEncrypter 不校验输入长度是否对齐

它只检查输入切片长度是否为块大小的整数倍,但不会帮你补位。如果传入未补位的明文,CryptBlocks 会静默截断,导致解密后数据丢失——而且没错误提示,非常难排查。

  • 务必在调用 CryptBlocks 前确认 len(plaintext)%16 == 0
  • 不要依赖 len(plaintext) 等于原始字符串长度:UTF-8 编码下中文字符占多个字节
  • 解密端也要做 PKCS#7 去除填充,不能简单 ciphertext[16:] 就完事

golang.org/x/crypto/chacha20poly1305 替代 AES-CBC 更省心

AES-CBC 容易误用(比如 IV 复用、缺少认证),而 ChaCha20-Poly1305 是 AEAD(带关联数据的认证加密),一次调用完成加密+认证,失败时直接返回错误,不用自己拼 IV、算 MAC。

  • 密钥固定 32 字节,Nonce(类似 IV)必须唯一,推荐 12 字节(标准要求)
  • 加密输出 = 密文 + 16 字节认证标签,解密时必须完整传入,少一个字节就报 crypto/cipher: message authentication failed
  • 性能在非 AES 指令集 CPU 上通常优于 AES-GCM
package main

import ( "crypto/rand" "fmt" "golang.org/x/crypto/chacha20poly1305" )

func main() { key := make([]byte, chacha20poly1305.KeySize) rand.Read(key) aead, _ := chacha20poly1305.New(key)

nonce := make([]byte, aead.NonceSize())
rand.Read(nonce)

plaintext := []byte("hello world")
ciphertext := aead.Seal(nil, nonce, plaintext, nil)
fmt.Printf("ciphertext: %x\n", ciphertext)

decrypted, err := aead.Open(nil, nonce, ciphertext, nil)
if err != nil {
    panic(err)
}
fmt.Printf("decrypted: %s\n", decrypted)

}

别把 crypto/md5crypto/sha1 当加密用

MD5 和 SHA1 是哈希函数,不可逆,不能“解密”。有人误用它们做“密码加密”,结果被彩虹表秒破。真要存密码,请用 golang.org/x/crypto/bcryptscrypt;要做密钥派生(比如从口令生成 AES 密钥),用 crypto/scryptcrypto/argon2

  • bcrypt.GenerateFromPassword 自动加盐,且计算慢,抗暴力破解
  • scrypt.Key 生成密钥时,N 参数至少设 115(32768),别用默认值
  • 哈希结果是定长字节数组,转 hex 存数据库时记得用 hex.EncodeToString,别直接 string()

实际写加密逻辑时,最容易漏的是:补位/去填充的一致性、IV/Nonce 的唯一性、认证标签的完整性校验。这三个点任一出错,要么解密失败,要么安全模型崩塌。