在Debian上使用Golang實現數據加密,你可以使用Go標準庫中的"crypto"包。這個包提供了多種加密算法,如AES、RSA、DES等。以下是一個使用AES加密和解密的簡單示例:
首先,確保你已經安裝了Go。如果沒有,請訪問https://golang.org/dl/ 下載并安裝適用于Debian的Go版本。
創建一個新的Go文件,例如main.go
,并添加以下代碼:
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
)
func main() {
key := []byte("your-secret-key-123") // 用于加密和解密的密鑰
plaintext := "Hello, World!" // 要加密的數據
// 加密數據
encryptedData, err := encrypt(plaintext, key)
if err != nil {
panic(err)
}
fmt.Printf("Encrypted data: %s\n", encryptedData)
// 解密數據
decryptedData, err := decrypt(encryptedData, key)
if err != nil {
panic(err)
}
fmt.Printf("Decrypted data: %s\n", 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 := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintextBytes)
return base64.StdEncoding.EncodeToString(ciphertext), nil
}
func decrypt(encryptedData string, key []byte) (string, error) {
ciphertext, err := base64.StdEncoding.DecodeString(encryptedData)
if err != nil {
return "", err
}
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
if len(ciphertext) < aes.BlockSize {
return "", fmt.Errorf("ciphertext too short")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertext, ciphertext)
padding := int(ciphertext[len(ciphertext)-1])
ciphertext = ciphertext[:len(ciphertext)-padding]
return string(ciphertext), nil
}
在key
變量中設置你的密鑰。請確保它至少有16個字節長,因為我們將使用AES-128加密。
運行程序:
go run main.go
程序將輸出加密后的數據和解密后的原始數據。
請注意,這只是一個簡單的示例,實際應用中可能需要更多的安全措施,例如使用更強的加密算法、安全的密鑰管理和存儲等。