使用crypto/aes需手动处理IV和PKCS#7填充,密钥长度须为16/24/32字节;推荐crypto/cipher.AEAD(如GCM)自动处理IV与认证;禁用MD5/SHA1派生密钥,应使用PBKDF2等KDF;文件加密须分块流式处理并正确填充。
crypto/aes 做 AES 加密必须手动处理 IV 和填充Go 标准库不提供开箱即用的「加密字符串→密文」函数,aes.NewCipher 只返回底层加解密器,你需要自己管理 IV(初始化向量)和 PKCS#7 填充。漏掉任一环节都会导致解密失败或 panic。
n 个值为 n 的字节[]byte("my-key") 很可能只有 6 字节,直接 panicfunc encryptAES(plaintext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if len(plaintext)%block.BlockSize() != 0 {
padding := block.BlockSize() - len(plaintext)%block.BlockSize()
plaintext = append(plaintext, bytes.Repeat([]byte{byte(padding)}, padding)...)
}
ciphertext := make([]byte, block.BlockSize()+len(plaintext))
iv := ciphertext[:block.BlockSize()]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
stream := cipher.NewCBCEncrypter(block, iv)
stream.CryptBlocks(ciphertext[block.BlockSize:], plaintext)
return ciphertext, nil
}crypto/cipher.AEAD 是更安全的选择,但接口更绕相比裸 AES-CBC,cipher.NewGCM 返回的 AEAD 实例自动处理 IV、认证标签(auth tag),还能防篡改——但它的 Seal 和 Open 方法参数顺序容易搞反,且要求 nonce(即 IV)不能重复。
GCM 要求 12 字节,ChaCha20-Poly1305 要求 24 字节Seal(dst, nonce, plaintext, additionalData) 中 additionalData 是可选的未加密元数据(如时间戳),但不能为空切片,得传 nil
Open 直接返回 nil, cipher.ErrDecrypt,不会泄露错误类型细节func encryptGCM(plaintext []byte, key []byte) ([]byte, error) {
block, _ := aes.NewCipher(key)
aead, _ := cipher.NewGCM(block)
nonce := make([]byte, aead.NonceSize())
if _, err := rand.Read(nonce); err != nil {
return nil, err
}
return aead.Seal(nonce, nonce, plaintext, nil), nil
}
func decryptGCM(ciphertext []byte, key []byte) ([]byte, error) {
block, := aes.NewCipher(key)
aead, := cipher.NewGCM(block)
nonceSize := aead.NonceSize()
if len(ciphertext) < nonceSize {
return nil, errors.New("ciphertext too short")
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
return aead.Open(nil, nonce, ciphertext, nil)
}
crypto/md5 和 crypto/sha1 做密钥派生MD5/SHA1 已被证明不安全,且它们是哈希不是密钥派生函数(KDF)。用它们对密码做一次哈希当密钥,等于把弱密码直接暴露给暴力破解。
golang.org/x/crypto/pbkdf2 或 scrypt,指定足够高的迭代次数(PBKDF2 至少 10^6)func deriveKey(password, salt []byte) []byte {
return pbkdf2.Key(password, salt, 1000000, 32, sha256.New)
}
// 使用示例:
salt := make([]byte, 16)
rand.Read(salt)
key := deriveKey([]byte("user-password"), salt)
// 注意:salt 必须和密文一起保存/传输
直接对整个文件内容调用 encryptAES 再写入,看似简单,但大文件会吃光内存;流式加密又容易在边界处填充满错,导致解密后末尾多出乱码字节。
bufio.Reader 分块读取,每块单独填充、加密、写入string() 强转,否则 UTF-8 解码失败加密逻辑本身不复杂,真正卡住人的是 IV 管理、填充一致性、密钥来源这三处。随便一个没对齐,解密就返回空或 panic,还查不出哪行错了。