在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,它们可以与加密库集成以实现日志加密。