Golang如何在Linux上进行数据加密解密
作者:水悠悠予安
时间:2026-07-18
浏览:5
在Linux环境下,利用Golang标准库crypto和crypto/cipher可简便实现AES加密解密。示例采用CBC模式,密钥长度需为16、24或32字节,对应AES-128、192或256。加密结果输出base64字符串,解密还原原文。实际应用需加强密钥管理与安全防护,并注意随机IV与数据填充,推荐采用AES-256。
本文目录
在Golang中实现数据加密解密,其实远比想象中简单。尤其是在Linux环境下,标准库crypto和crypto/cipher已经提供了足够完善的工具。下面这个示例,就展示了如何用AES加密算法对数据进行加解密——整个过程清晰、直接,适合作为入门参考。

先确保你已经安装了Go语言环境。然后创建一个main.go文件,把下面的代码粘贴进去:
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
)
func main() {
key := []byte("your-secret-key-123") // 密钥长度必须为16、24或32字节
plaintext := "Hello, World!"
encryptedData, err := encrypt(plaintext, key)
if err != nil {
panic(err)
}
fmt.Printf("Encrypted data: %s\n", encryptedData)
decryptedData, err := decrypt(encryptedData, key)
if err != nil {
panic(err)
}
fmt.Printf("Decrypted data: %s\n", decryptedData)
}
func encrypt(plaintext string, key []byte) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
plaintextBytes := []byte(plaintext)
padding := aes.BlockSize - len(plaintextBytes)%aes.BlockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
ciphertext := make([]byte, len(plaintextBytes)+padding)
iv := make([]byte, aes.BlockSize)
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext, append(iv, plaintextBytes...))
return base64.StdEncoding.EncodeToString(ciphertext), nil
}
func decrypt(ciphertext string, key []byte) (string, error) {
ciphertextBytes, err := base64.StdEncoding.DecodeString(ciphertext)
if err != nil {
return "", err
}
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
if len(ciphertextBytes) < aes.BlockSize {
return "", fmt.Errorf("ciphertext too short")
}
iv := ciphertextBytes[:aes.BlockSize]
ciphertextBytes = ciphertextBytes[aes.BlockSize:]
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertextBytes, ciphertextBytes)
padding := int(ciphertextBytes[len(ciphertextBytes)-1])
ciphertextBytes = ciphertextBytes[:len(ciphertextBytes)-padding]
return string(ciphertextBytes), nil
}
这段代码使用了AES的CBC模式。密钥部分需要替换成你自己的密钥——注意长度必须是16、24或32字节,分别对应AES-128、AES-192和AES-256。如果你选择了“your-secret-key-123”这个示例密钥,它刚好是16字节,属于AES-128。
运行起来很简单,在终端执行:
go run main.go
你会看到加密后的base64字符串和解密后的原文。当然,这只是一个演示示例,实际生产环境中还需要考虑更完善的错误处理、密钥管理以及安全性检查。不过作为入门,它已经足够帮你理解Golang加密解密的基本流程了。
作者最新文章
立刻MV如何查看立刻MV官方操作指引文档
2026-11-02 14:05
抖音创作平台官网登录入口
2026-11-02 10:38
Xshell连接SSH失败怎么办?5步排查网络、代理与认证问题
2026-10-30 14:30
樱花动漫官方正版官网入口在哪_樱花动漫网址2027最新分享
2026-10-28 19:21
AO3永久可用网址分享 ao3实时访问入口
2026-10-28 13:16
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多
























