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语言实现一个二维码生成器

    二维码作为信息传递的载体,已经广泛应用在支付、营销、门票、WiFi 分享等场景中,Go 标准库虽然没有直接支持二维码,但通过第三方库我们可以非常方便地实现一个二维码生成器工具,这一篇我们就来带你一步一步完成一个二维码生成器,需要的朋友可以参考下
    2025-09-09
  • Go语言map元素的删除和清空

    Go语言map元素的删除和清空

    本文主要介绍了Go语言map元素的删除和清空,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-04-04
  • Go如何优雅的使用字节池示例详解

    Go如何优雅的使用字节池示例详解

    在编程开发中,我们经常会需要频繁创建和销毁同类对象的情形,这样的操作很可能会对性能造成影响,这时常用的优化手段就是使用对象池(object pool),这篇文章主要给大家介绍了关于Go如何优雅的使用字节池的相关资料,需要的朋友可以参考下
    2022-08-08
  • Golang 高效排序数据详情

    Golang 高效排序数据详情

    本文我们介绍了怎么使用 Golang 语言标准库 sort 包排序数据,需要注意的是,除了本文使用的类型之外,其它任意类型只要实现 sort.Interface 的三个方法,都可以调用 sort.Sort() 函数排序数据。
    2021-11-11
  • golang实现各种情况的get请求操作

    golang实现各种情况的get请求操作

    这篇文章主要介绍了golang实现各种情况的get请求操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-12-12
  • Go语言为什么不支持前缀自增运算符原理解析

    Go语言为什么不支持前缀自增运算符原理解析

    这篇文章主要为大家介绍了Go语言为什么不支持前缀自增运算符原理解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-08-08
  • Golang中优秀的消息队列NSQ基础安装及使用详解

    Golang中优秀的消息队列NSQ基础安装及使用详解

    这篇文章主要介绍了Golang中优秀的消息队列NSQ基础安装及使用详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-12-12
  • Go语言学习之函数的定义与使用详解

    Go语言学习之函数的定义与使用详解

    这篇文章主要为大家详细介绍Go语言中函数的定义与使用,文中的示例代码讲解详细,对我们学习Go语言有一定帮助,需要的可以参考一下
    2022-04-04
  • 五步让你成为GO 语言高手

    五步让你成为GO 语言高手

    本文给大家介绍的这里是GO程序员的五个进化阶段,从最开始的菜逼到最终的布道者,附上各种示例,一步步走向大神之路,推荐给小伙伴们,有需要的朋友可以参考下
    2015-03-03
  • 详解Go语言如何实现并发安全的map

    详解Go语言如何实现并发安全的map

    go语言提供的数据类型中,只有channel是并发安全的,基础map并不是并发安全的,本文为大家整理了三种实现了并发安全的map的方案,有需要的可以参考下
    2023-12-12

最新评论