golang中使用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(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加密的文章就介绍到这了,更多相关go aes加密内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客! 您可能感兴趣的文章: GO语言实现AES-CFB加密的操作方法 Go语言使用AES加密解密的示例代码 golang实现aes-cbc-256加密解密功能 Golang实现AES对称加密算法实例详解 通过Golang编写一个AES加密解密工具 Golang实现AES加密和解密的示例代码 golang常用加密解密算法总结(AES、DES、RSA、Sha1、MD5) Golang实现AES对称加密的过程详解
  • 目录
    • AES 加密基础
    • 生成密钥
    • 加密数据
    • 解密数据
    • 使用 GCM 模式(推荐)
    • 注意事项

    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(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加密的文章就介绍到这了,更多相关go aes加密内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!

    您可能感兴趣的文章:

    • GO语言实现AES-CFB加密的操作方法
    • Go语言使用AES加密解密的示例代码
    • golang实现aes-cbc-256加密解密功能
    • Golang实现AES对称加密算法实例详解
    • 通过Golang编写一个AES加密解密工具
    • Golang实现AES加密和解密的示例代码
    • golang常用加密解密算法总结(AES、DES、RSA、Sha1、MD5)
    • Golang实现AES对称加密的过程详解

    站内搜索