温馨提示×

Linux 上 Golang 日志如何加密

小樊
48
2025-09-09 12:47:36
栏目: 编程语言

在 Linux 上,你可以使用 Golang 的 crypto 包来实现日志文件的加密。以下是一个简单的示例,展示了如何使用 AES 加密算法对日志文件进行加密和解密。

首先,确保你已经安装了 Go 语言环境。然后,创建一个名为 main.go 的文件,并将以下代码粘贴到其中:

package main

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

func main() {
	key := []byte("your-secret-key-123") // 用于加密和解密的密钥,长度必须是 16、24 或 32 字节
	plaintext := "This is a sample log message."

	encrypted, err := encrypt(plaintext, key)
	if err != nil {
		fmt.Println("Error encrypting:", err)
		return
	}
	fmt.Println("Encrypted:", encrypted)

	decrypted, err := decrypt(encrypted, key)
	if err != nil {
		fmt.Println("Error decrypting:", err)
		return
	}
	fmt.Println("Decrypted:", decrypted)
}

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

	ciphertext := make([]byte, aes.BlockSize+len(plaintext))
	iv := ciphertext[:aes.BlockSize]
	if _, err := rand.Read(iv); err != nil {
		return "", err
	}

	stream := cipher.NewCFBEncrypter(block, iv)
	stream.XORKeyStream(ciphertext[aes.BlockSize:], []byte(plaintext))

	return hex.EncodeToString(ciphertext), nil
}

func decrypt(ciphertext string, key []byte) (string, error) {
	ciphertextBytes, err := hex.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:]

	stream := cipher.NewCFBDecrypter(block, iv)
	stream.XORKeyStream(ciphertextBytes, ciphertextBytes)

	return string(ciphertextBytes), nil
}

在代码中,我们使用了 AES 加密算法,并使用了一个简单的密钥。在实际应用中,你应该使用一个更安全的密钥,并将其存储在一个安全的地方。

要运行此示例,请在终端中执行以下命令:

go run main.go

这将输出加密后的日志消息和解密后的原始消息。

要将此示例应用于实际的日志文件,你可以使用 Go 的 log 包记录日志,然后使用上述加密和解密函数对日志文件进行加密和解密。

0