Linux下Golang实现数据加密方法

作者:技术拾光

时间:2026-07-06

浏览:78

Linux下,Golang标准库crypto包支持AES等主流对称加密算法。以AES-128为例,采用CBC模式、PKCS5填充、随机初始化向量演示完整加解密流程。实际生产需注意密钥安全存储与轮换、错误处理,并确保初始化向量唯一性与完整性校验,防范攻击,保障数据安全,适用于文件加密与网络传输。

文章目录

在Linux环境下使用Golang进行数据加密时,Go标准库的crypto包提供了完善的工具集,涵盖AES、DES、RSA等主流算法。下面以AES为例,说明CBC模式、填充和初始化向量的处理方式。

Linux下Golang实现数据加密方法

AES加密示例代码

package main

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "encoding/hex"
    "fmt"
    "io"
)

func main() {
    key := []byte("this is a 16 byte key") // AES-128需要16字节的密钥
    plaintext := []byte("Hello, World!")

    // 加密
    ciphertext, err := encrypt(key, plaintext)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Ciphertext: %s\n", hex.EncodeToString(ciphertext))

    // 解密
    decrypted, err := decrypt(key, ciphertext)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Decrypted: %s\n", decrypted)
}

func encrypt(key, plaintext []byte) ([]byte, error) {
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }

    plaintext = pkcs5Padding(plaintext, aes.BlockSize)
    ciphertext := make([]byte, len(plaintext))
    iv := make([]byte, aes.BlockSize)
    if _, err := io.ReadFull(rand.Reader, iv); err != nil {
        return nil, err
    }

    mode := cipher.NewCBCEncrypter(block, iv)
    mode.CryptBlocks(ciphertext, plaintext)

    return append(iv, ciphertext...), nil
}

func decrypt(key, ciphertext []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)
    plaintext := make([]byte, len(ciphertext))
    mode.CryptBlocks(plaintext, ciphertext)

    plaintext = pkcs5UnPadding(plaintext)
    return plaintext, nil
}

func pkcs5Padding(src []byte, blockSize int) []byte {
    padding := blockSize - len(src)%blockSize
    padtext := bytes.Repeat([]byte{byte(padding)}, padding)
    return append(src, padtext...)
}

func pkcs5UnPadding(src []byte) []byte {
    length := len(src)
    unpadding := int(src[length-1])
    return src[:(length - unpadding)]
}

加密与解密流程详解

这段代码展示了完整的加密到解密流程。首先使用AES-128生成密码块,然后对明文进行PKCS5填充。填充的原因是AES的块大小为16字节,原始数据长度不一定恰好是16的整数倍。填充完成后,生成一个随机的初始化向量(IV),并采用CBC模式将明文转换为密文。最后将IV附加在密文的最前端,便于解密时提取。

解密过程与此相反:从密文头部截取出IV,使用相同的密钥和CBC模式对剩余部分进行解密,最后移除PKCS5填充,恢复原始明文。

生产环境注意事项

必须强调一点:此示例仅用于演示逻辑,关键的密钥管理和错误处理未作深入讨论。在实际生产环境中,密钥的生成、存储、轮换以及异常捕获均需严谨设计,直接使用此示例上线是不行的。不过,理解这套流程之后,迁移至生产环境便水到渠成。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›