登录
首页 >  Golang >  Go教程

Golang加密解密项目实战教程

时间:2025-10-01 18:45:53 159浏览 收藏

本文详细介绍了如何使用Go语言(Golang)的`crypto`包实现基础的AES加密解密功能,并重点讲解了AES-CBC加密模式的应用。文章深入浅出地阐述了加密过程中的密钥处理、随机初始化向量(IV)的生成与使用,以及PKCS7填充的必要性。通过具体的代码示例,展示了如何进行数据加密、解密以及去除填充,确保数据的完整性和安全性。最后,提供了一个完整的示例,演示了如何将这些函数整合到一起,实现数据的加密和解密,并以Base64编码格式输出密文,成功还原明文,为开发者提供了一个清晰、实用的Golang加密解密方案,帮助快速构建安全的数据加解密模块。

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

Golang实现基础加密解密功能项目

在Go语言(Golang)中实现基础的加密解密功能并不复杂。借助标准库中的 crypto 包,比如 crypto/aescrypto/ciphercrypto/rand 等,我们可以轻松构建安全的数据加解密模块。下面是一个基于AES对称加密算法(CBC模式)的简单项目示例,包含密钥生成、数据加密和解密功能。

1. 使用AES-CBC进行加密

AES(Advanced Encryption Standard)是一种广泛使用的对称加密算法。CBC(Cipher Block Chaining)模式能提高安全性,防止相同明文块生成相同密文。

加密过程需要:

  • 一个固定长度的密钥(如16字节对应AES-128)
  • 一个随机初始化向量(IV)
  • 待加密的明文数据

以下是加密函数的实现:

func encrypt(plaintext []byte, key []byte) ([]byte, error) {
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }
<pre class="brush:php;toolbar:false;">// 对明文进行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
    }
<pre class="brush:php;toolbar:false;">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加密解密示例!")
<pre class="brush:php;toolbar:false;">ciphertext, err := encrypt(plaintext, key)
if err != nil {
    log.Fatal("加密失败:", err)
}
fmt.Printf("密文(Base64): %s\n", base64.StdEncoding.EncodeToString(ciphertext))

decrypted, err := decrypt(ciphertext, key)
if err != nil {
    log.Fatal("解密失败:", err)
}
fmt.Printf("解密结果: %s\n", string(decrypted))

}

输出类似:

密文(Base64): wEvX...
解密结果: Hello, Golang加密解密示例!

基本上就这些。这个项目展示了如何用Golang实现安全的基础加解密功能。你可以将其封装为独立包,支持更多模式(如GCM)或密钥派生(如PBKDF2),以适应实际应用需求。不复杂但容易忽略细节,比如IV的随机性和填充处理。

好了,本文到此结束,带大家了解了《Golang加密解密项目实战教程》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>