溫馨提示×

CentOS上Golang日志如何加密

小樊
47
2025-05-29 06:05:05
欄目: 編程語言

在CentOS上,您可以使用Golang的加密庫來實現日志加密。以下是一個簡單的示例,使用AES加密算法對日志進行加密和解密。

首先,確保已經安裝了Golang。然后,創建一個名為main.go的文件,并添加以下代碼:

package main

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

func main() {
	key := []byte("your-secret-key") // 用于加密和解密的密鑰
	plaintext := "Hello, World! This is a log message."

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

	decrypted, err := decrypt(encrypted, key)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Decrypted: %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模式。請注意,您需要使用一個安全的密鑰,例如16、24或32字節長。在這個例子中,我們使用了一個簡單的字符串作為密鑰,但在實際應用中,您應該使用一個更安全的方法來生成和存儲密鑰。

要運行此示例,請在終端中執行以下命令:

go run main.go

這將輸出加密后的日志和解密后的原始日志。

在實際應用中,您可能需要將加密后的日志寫入文件,并在需要時讀取和解密它們。您還可以考慮使用現有的日志庫,如logrus或zap,它們可以與加密庫集成以實現日志加密。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女