溫馨提示×

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

小樊
51
2025-08-03 08:18:51
欄目: 編程語言

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

首先,確保已經安裝了Golang。然后,創建一個名為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("Error encrypting data:", err)
		return
	}
	fmt.Println("Encrypted data:", encryptedData)

	decryptedData, err := decrypt(encryptedData, key)
	if err != nil {
		fmt.Println("Error decrypting data:", err)
		return
	}
	fmt.Println("Decrypted data:", 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)

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

	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(ciphertext[padding:], append(plaintextBytes, padtext...))

	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
	}

	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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女