golang中使用aes加密的过程

 更新时间:2025年11月11日 10:07:38   作者:WTDhOZM3W  
AES(Advanced Encryption Standard)是一种对称加密算法,适用于加密敏感数据,本文给大家介绍golang中使用aes加密的相关知识,感兴趣的朋友跟随小编一起看看吧

AES 加密基础

AES(Advanced Encryption Standard)是一种对称加密算法,适用于加密敏感数据。Golang 的 crypto/aes 包提供了 AES 加密的实现,通常结合 crypto/cipher 包使用。

生成密钥

AES 密钥长度需为 16(AES-128)、24(AES-192)或 32(AES-256)字节。

key := []byte("32-byte-long-key-here-1234567890") // AES-256 密钥

加密数据

使用 CBC 模式(需填充)和随机 IV(初始化向量):

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "io"
)
func encrypt(plaintext []byte, key []byte) ([]byte, error) {
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }
    // 填充数据到块大小
    plaintext = pkcs7Pad(plaintext, aes.BlockSize)
    // 生成随机 IV
    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
}
// PKCS7 填充
func pkcs7Pad(data []byte, blockSize int) []byte {
    padding := blockSize - len(data)%blockSize
    padText := bytes.Repeat([]byte{byte(padding)}, padding)
    return append(data, padText...)
}

解密数据

解密时需提取 IV 并移除填充:

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, fmt.Errorf("ciphertext too short")
    }
    iv := ciphertext[:aes.BlockSize]
    ciphertext = ciphertext[aes.BlockSize:]
    // 解密
    mode := cipher.NewCBCDecrypter(block, iv)
    mode.CryptBlocks(ciphertext, ciphertext)
    // 移除填充
    ciphertext = pkcs7Unpad(ciphertext)
    return ciphertext, nil
}
// PKCS7 去填充
func pkcs7Unpad(data []byte) []byte {
    length := len(data)
    unpadding := int(data[length-1])
    return data[:(length - unpadding)]
}

使用 GCM 模式(推荐)

GCM(Galois/Counter Mode)提供认证加密,无需手动填充:

func encryptGCM(plaintext []byte, key []byte) ([]byte, error) {
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }
    gcm, err := cipher.NewGCM(block)
    if err != nil {
        return nil, err
    }
    nonce := make([]byte, gcm.NonceSize())
    if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
        return nil, err
    }
    return gcm.Seal(nonce, nonce, plaintext, nil), nil
}
func decryptGCM(ciphertext []byte, key []byte) ([]byte, error) {
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }
    gcm, err := cipher.NewGCM(block)
    if err != nil {
        return nil, err
    }
    nonceSize := gcm.NonceSize()
    if len(ciphertext) < nonceSize {
        return nil, fmt.Errorf("ciphertext too short")
    }
    nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
    return gcm.Open(nil, nonce, ciphertext, nil)
}

注意事项

  • 密钥管理:密钥需安全存储,避免硬编码。
  • IV/Nonce:每次加密需生成随机 IV 或 Nonce,禁止重复使用。
  • 性能:GCM 模式适合高性能场景,CBC 需手动处理填充。

通过上述方法,可在 Golang 中实现 AES 加密/解密功能,根据需求选择 CBC 或 GCM 模式。

到此这篇关于golang中使用aes加密的文章就介绍到这了,更多相关golang使用aes加密内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Go语言的方法接受者类型用值类型还是指针类型?

    Go语言的方法接受者类型用值类型还是指针类型?

    这篇文章主要介绍了Go语言的方法接受者类型用值类型还是指针类型?本文还同时讲解了关于接受者的命名方式,需要的朋友可以参考下
    2014-10-10
  • Go语言中常见的坑以及高性能编程技巧分享

    Go语言中常见的坑以及高性能编程技巧分享

    代码的稳健性、高性能、可读性是我们每一位coder必须去追求的目标,本文结合Go语言的特性做了相关总结,感兴趣的小伙伴可以了解一下
    2023-06-06
  • Golang sync.Pool的源码解析

    Golang sync.Pool的源码解析

    Pool是用于存放临时对象的集合,这些对象是为了后续的使用,以达到复用对象的效果,本文将详解解析sync.Pool 源码,需要的朋友可以参考下
    2023-05-05
  • Go 高效截取字符串的一些思考

    Go 高效截取字符串的一些思考

    这篇文章主要介绍了Go 高效截取字符串的一些思考,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-10-10
  • 浅析Golang切片截取功能与C++的vector区别

    浅析Golang切片截取功能与C++的vector区别

    这篇文章主要介绍了Golang中切片的截取功能与C++中的vector有什么区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧
    2022-10-10
  • Golang 如何解析和生成json

    Golang 如何解析和生成json

    这篇文章主要介绍了Golang 如何解析和生成json,帮助大家更好的理解和学习golang,感兴趣的朋友可以了解下
    2020-09-09
  • Go语言中范围range的使用小结

    Go语言中范围range的使用小结

    range是Go里用于遍历数据结构的语法糖,本文主要介绍了Go语言的范围range的使用小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2025-12-12
  • 浅谈Go Channel 高级实践

    浅谈Go Channel 高级实践

    这篇文章主要介绍了浅谈Go Channel 高级实践,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-08-08
  • Go语言Seeker接口与文件断点续传实战教程

    Go语言Seeker接口与文件断点续传实战教程

    Go语言的io包中Seeker接口为大文件处理或需要随机访问的场景提供了强大的支持,本文通过具体案例详细介绍了Seeker接口的应用,包括随机访问大文件、断点续传等场景,以及如何使用Seeker接口进行有效的文件读写操作
    2024-10-10
  • go mod的使用方法小结

    go mod的使用方法小结

    本文主要介绍了go mod的使用方法小结,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-04-04

最新评论