商城首页欢迎来到中国正版软件门户

您的位置: 首页 > 文章列表 > 编程开发 > Golang如何在Linux上进行数据加密解密

Golang如何在Linux上进行数据加密解密

  发布于2026-07-18 阅读(0)

扫一扫,手机访问

在Golang中实现数据加密解密,其实远比想象中简单。尤其是在Linux环境下,标准库cryptocrypto/cipher已经提供了足够完善的工具。下面这个示例,就展示了如何用AES加密算法对数据进行加解密——整个过程清晰、直接,适合作为入门参考。

Golang如何在Linux上进行数据加密解密

先确保你已经安装了Go语言环境。然后创建一个main.go文件,把下面的代码粘贴进去:

package main

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

func main() {
    key := []byte("your-secret-key-123") // 密钥长度必须为16、24或32字节
    plaintext := "Hello, World!"

    encryptedData, err := encrypt(plaintext, key)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Encrypted data: %s\n", encryptedData)

    decryptedData, err := decrypt(encryptedData, key)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Decrypted data: %s\n", decryptedData)
}

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

    plaintextBytes := []byte(plaintext)
    padding := aes.BlockSize - len(plaintextBytes)%aes.BlockSize
    padtext := bytes.Repeat([]byte{byte(padding)}, padding)

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

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

    return base64.StdEncoding.EncodeToString(ciphertext), nil
}

func decrypt(ciphertext string, key []byte) (string, error) {
    ciphertextBytes, err := base64.StdEncoding.DecodeString(ciphertext)
    if err != nil {
        return "", err
    }

    block, err := aes.NewCipher(key)
    if err != nil {
        return "", err
    }

    if len(ciphertextBytes) < aes.BlockSize {
        return "", fmt.Errorf("ciphertext too short")
    }

    iv := ciphertextBytes[:aes.BlockSize]
    ciphertextBytes = ciphertextBytes[aes.BlockSize:]

    mode := cipher.NewCBCDecrypter(block, iv)
    mode.CryptBlocks(ciphertextBytes, ciphertextBytes)

    padding := int(ciphertextBytes[len(ciphertextBytes)-1])
    ciphertextBytes = ciphertextBytes[:len(ciphertextBytes)-padding]

    return string(ciphertextBytes), nil
}

这段代码使用了AES的CBC模式。密钥部分需要替换成你自己的密钥——注意长度必须是16、24或32字节,分别对应AES-128、AES-192和AES-256。如果你选择了“your-secret-key-123”这个示例密钥,它刚好是16字节,属于AES-128。

运行起来很简单,在终端执行:

go run main.go

你会看到加密后的base64字符串和解密后的原文。当然,这只是一个演示示例,实际生产环境中还需要考虑更完善的错误处理、密钥管理以及安全性检查。不过作为入门,它已经足够帮你理解Golang加密解密的基本流程了。

本文转载于:https://www.yisu.com/ask/79892807.html 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注