温馨提示×

Golang在Linux中如何进行数据加密

小樊
36
2025-10-24 19:47:12
栏目: 编程语言

在Golang中,可以使用标准库"crypto"和"hash"来实现数据加密。以下是一个使用AES加密算法的示例:

首先,确保已经安装了Golang。然后,创建一个名为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 := []byte("Hello, World!") // 要加密的数据

	ciphertext, err := encrypt(plaintext, key)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Encrypted data: %s\n", base64.StdEncoding.EncodeToString(ciphertext))

	decryptedData, err := decrypt(ciphertext, key)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Decrypted data: %s\n", string(decryptedData))
}

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

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

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

	return ciphertext, nil
}

func decrypt(ciphertext, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	if len(ciphertext) < aes.BlockSize {
		return nil, fmt.Errorf("ciphertext too short")
	}

	iv := ciphertext[:aes.BlockSize]
	ciphertext = ciphertext[aes.BlockSize:]

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

	return ciphertext, nil
}

在这个示例中,我们使用了AES加密算法的CFB模式。你可以根据需要选择其他模式,如CBC、GCM等。请注意,密钥长度必须是16、24或32字节。

要运行此示例,请在终端中导航到包含main.go文件的目录,并运行以下命令:

go run main.go

这将输出加密后的数据和解密后的原始数据。请确保在实际应用中使用安全的密钥管理和错误处理。

0