在 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
包記錄日志,然后使用上述加密和解密函數對日志文件進行加密和解密。