debian

Debian环境下Golang日志如何加密存储

小樊
41
2025-06-27 08:27:12
栏目: 云计算

在Debian环境下,你可以使用Golang的加密库来实现日志的加密存储。以下是一个简单的示例,展示了如何使用AES加密算法对日志进行加密和解密。

首先,确保你已经安装了Go语言环境。然后,创建一个新的Go文件,例如main.go,并添加以下代码:

package main

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

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

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

	decrypted, err := decrypt(encrypted, key)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Decrypted log: %s\n", 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 := io.ReadFull(rand.Reader, iv); err != nil {
		return "", err
	}

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

	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:]

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

	return string(ciphertextBytes), nil
}

在这个示例中,我们使用了AES加密算法和CFB模式。encrypt函数接受一个明文字符串和一个密钥,返回加密后的Base64编码字符串。decrypt函数接受一个加密后的Base64编码字符串和一个密钥,返回解密后的明文字符串。

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

go run main.go

请注意,这个示例仅用于演示目的。在实际应用中,你需要根据自己的需求进行调整,例如将加密后的日志写入文件,以及处理可能出现的错误。

另外,为了确保安全性,你应该使用一个安全的密钥管理策略,例如将密钥存储在环境变量或配置文件中,并确保只有授权的用户可以访问。

0
看了该问题的人还看了