溫馨提示×

Golang如何在Linux下實現數據加密解密

小樊
40
2025-10-07 20:37:10
欄目: 編程語言

在Golang中,可以使用標準庫"crypto"來實現數據的加密和解密。以下是一個使用AES加密算法的示例:

首先,確保你的系統已經安裝了Go語言環境。然后,創建一個名為main.go的文件,并將以下代碼粘貼到文件中:

package main

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

func main() {
	key := []byte("your-secret-key-123") // 用于加密和解密的密鑰,長度必須是16、24或32字節
	plaintext := "Hello, World!"           // 需要加密的數據

	encryptedData, err := encrypt(plaintext, key)
	if err != nil {
		fmt.Println("加密失敗:", err)
		return
	}
	fmt.Println("加密后的數據:", encryptedData)

	decryptedData, err := decrypt(encryptedData, key)
	if err != nil {
		fmt.Println("解密失敗:", err)
		return
	}
	fmt.Println("解密后的數據:", decryptedData)
}

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

	plaintextBytes := []byte(plaintext)
	padding := aes.BlockSize - len(plaintextBytes)%aes.BlockSize
	padText := bytes.Repeat([]byte{byte(padding)}, padding)

	plaintextBytes = append(plaintextBytes, padText...)

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

	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(ciphertext, plaintextBytes)

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

	mode := cipher.NewCBCDecrypter(block, iv)
	mode.CryptBlocks(ciphertextBytes, ciphertextBytes)

	padding := int(ciphertextBytes[len(ciphertextBytes)-1])
	ciphertextBytes = ciphertextBytes[:len(ciphertextBytes)-padding]

	return string(ciphertextBytes), nil
}

在上面的代碼中,我們使用了AES加密算法,并采用了CBC模式。請確保你的密鑰長度是16、24或32字節。在這個示例中,我們使用了一個固定的密鑰,但在實際應用中,你應該使用一個安全的密鑰管理方法。

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

go run main.go

這將輸出加密后的數據和解密后的數據。請注意,這個示例僅用于演示目的,實際應用中可能需要更多的錯誤處理和安全性檢查。

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