使用Go语言crypto包实现AES-CBC加密,需密钥、随机IV和PKCS7填充;2. 加密时生成随机IV并前置密文,解密时提取IV并去除填充;3. 完整示例展示加密解密流程,输出Base64编码密文并成功还原明文。

在Go语言(Golang)中实现基础的加密解密功能并不复杂。借助标准库中的 crypto 包,比如 crypto/aes、crypto/cipher、crypto/rand 等,我们可以轻松构建安全的数据加解密模块。下面是一个基于AES对称加密算法(CBC模式)的简单项目示例,包含密钥生成、数据加密和解密功能。
1. 使用AES-CBC进行加密
AES(Advanced Encryption Standard)是一种广泛使用的对称加密算法。CBC(Cipher Block Chaining)模式能提高安全性,防止相同明文块生成相同密文。
加密过程需要:
一个固定长度的密钥(如16字节对应AES-128)一个随机初始化向量(IV)待加密的明文数据
以下是加密函数的实现:
立即学习“go语言免费学习笔记(深入)”;
func encrypt(plaintext []byte, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err }// 对明文进行PKCS7填充plaintext = pkcs7Padding(plaintext, block.BlockSize())// 初始化CBC加密器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
}
2. 实现PKCS7填充
AES是分组加密算法,要求明文长度是块大小的整数倍(如16字节)。当数据不足时,需进行填充。
func pkcs7Padding(data []byte, blockSize int) []byte { padding := blockSize - len(data)%blockSize padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(data, padtext...)}
3. 解密数据
解密过程与加密相反:使用相同的密钥和IV(存储在密文前部),进行CBC解密,然后去除PKCS7填充。
func decrypt(ciphertext []byte, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err }if len(ciphertext) < aes.BlockSize { return nil, errors.New("密文过短")}iv := ciphertext[:aes.BlockSize]ciphertext = ciphertext[aes.BlockSize:]if len(ciphertext)%aes.BlockSize != 0 { return nil, errors.New("密文长度不是块大小的整数倍")}mode := cipher.NewCBCDecrypter(block, iv)mode.CryptBlocks(ciphertext, ciphertext)// 去除PKCS7填充return pkcs7Unpadding(ciphertext)
}
对应的去填充函数:
func pkcs7Unpadding(data []byte) ([]byte, error) { length := len(data) if length == 0 { return nil, errors.New("空数据") } unpadding := int(data[length-1]) if unpadding > length { return nil, errors.New("无效填充") } return data[:length-unpadding], nil}
4. 完整使用示例
将上述函数整合到 main 函数中测试:
func main() { key := []byte("1234567890123456") // 16字节密钥(AES-128) plaintext := []byte("Hello, Golang加密解密示例!")ciphertext, err := encrypt(plaintext, key)if err != nil { log.Fatal("加密失败:", err)}fmt.Printf("密文(Base64): %sn", base64.StdEncoding.EncodeToString(ciphertext))decrypted, err := decrypt(ciphertext, key)if err != nil { log.Fatal("解密失败:", err)}fmt.Printf("解密结果: %sn", string(decrypted))
}
输出类似:
密文(Base64): wEvX...
解密结果: Hello, Golang加密解密示例!
基本上就这些。这个项目展示了如何用Golang实现安全的基础加解密功能。你可以将其封装为独立包,支持更多模式(如GCM)或密钥派生(如PBKDF2),以适应实际应用需求。不复杂但容易忽略细节,比如IV的随机性和填充处理。
以上就是Golang实现基础加密解密功能项目的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1404727.html
微信扫一扫
支付宝扫一扫