推荐使用AES对称加密算法实现Golang文件加解密,核心步骤包括:生成随机IV,用AES-CBC模式加密文件内容,并将IV与密文一同存储;解密时读取前16字节IV,结合密钥还原数据。代码示例包含encryptFile和decryptFile函数,支持指定密钥、输入输出路径进行加解密操作。注意事项:密钥长度需为16/24/32字节,建议通过PBKDF2等安全方式派生,避免硬编码;大文件应分块处理防止内存溢出;添加MAC验证完整性;实际应用中可扩展为流式加密支持超大文件。完整实现需注意填充处理与IV管理细节。

在Golang中实现文件加密与解密,推荐使用对称加密算法(如AES),因为它效率高且适合大文件处理。核心思路是:用一个密钥对文件内容进行加密,保存或传输后,再用相同密钥解密还原内容。以下是具体实现步骤和代码示例。
使用AES算法配合CBC(Cipher Block Chaining)模式可以有效保护文件数据。需要生成随机的初始化向量(IV)并将其与密文一起存储,以便后续解密。
说明:
示例代码:
立即学习“go语言免费学习笔记(深入)”;
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"io"
"os"
)
func encryptFile(key, inFilePath, outFilePath string) error {
plaintext, err := os.ReadFile(inFilePath)
if err != nil {
return err
}
block, err := aes.NewCipher([]byte(key))
if err != nil {
return err
}
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return err
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
return os.WriteFile(outFilePath, ciphertext, 0644)
}
解密时从文件读取前16字节作为IV,然后使用相同密钥还原数据。注意验证密钥正确性和数据完整性应在应用层处理。
示例代码:
立即学习“go语言免费学习笔记(深入)”;
func decryptFile(key, inFilePath, outFilePath string) error {
ciphertext, err := os.ReadFile(inFilePath)
if err != nil {
return err
}
block, err := aes.NewCipher([]byte(key))
if err != nil {
return err
}
if len(ciphertext) < aes.BlockSize {
return io.ErrUnexpectedEOF
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
stream.XORKeyStream(ciphertext, ciphertext)
return os.WriteFile(outFilePath, ciphertext, 0644)
}
调用上面函数进行加解密操作,密钥必须为16/24/32字节长度字符串。
简单调用示例:
func main() {
key := "1234567890123456" // 16字节密钥
encryptFile(key, "plain.txt", "encrypted.dat")
decryptFile(key, "encrypted.dat", "decrypted.txt")
}
关键点提醒:
以上就是如何在Golang中实现文件加密与解密的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号