在Linux環境下,使用Golang進行數據加密和解密可以通過標準庫中的"crypto"包來實現。以下是一個簡單的示例,展示了如何使用AES(高級加密標準)算法進行數據的加密和解密。
首先,確保你的系統中已經安裝了Go語言環境。然后,你可以創建一個Go文件,比如叫做aes_example.go
,并寫入以下代碼:
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
)
// 加密函數
func encrypt(plainText string, key []byte) (cipherText string, err error) {
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
plainTextBytes := []byte(plainText)
plainTextBytes = pkcs5Padding(plainTextBytes, aes.BlockSize)
cipherTextBytes := 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(cipherTextBytes, plainTextBytes)
cipherTextBytes = append(iv, cipherTextBytes...)
cipherText = base64.StdEncoding.EncodeToString(cipherTextBytes)
return cipherText, nil
}
// 解密函數
func decrypt(cipherText string, key []byte) (plainText string, err 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)
plainTextBytes, err := pkcs5UnPadding(cipherTextBytes)
if err != nil {
return "", err
}
plainText = string(plainTextBytes)
return plainText, nil
}
// PKCS5填充
func pkcs5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
// PKCS5去填充
func pkcs5UnPadding(origData []byte) ([]byte, error) {
length := len(origData)
unpadding := int(origData[length-1])
if unpadding > length {
return nil, errors.New("unpadding error")
}
return origData[:(length - unpadding)], nil
}
func main() {
key := []byte("1234567890123456") // AES密鑰長度必須是16, 24, 32字節
plainText := "Hello, World!"
// 加密
encrypted, err := encrypt(plainText, key)
if err != nil {
fmt.Println("Encryption error:", err)
return
}
fmt.Println("Encrypted:", encrypted)
// 解密
decrypted, err := decrypt(encrypted, key)
if err != nil {
fmt.Println("Decryption error:", err)
return
}
fmt.Println("Decrypted:", decrypted)
}
在上面的代碼中,我們定義了encrypt
和decrypt
函數來分別進行加密和解密操作。我們還定義了pkcs5Padding
和pkcs5UnPadding
函數來處理PKCS5填充和去填充,這是因為AES算法要求數據長度必須是塊大小的整數倍。
要運行這個程序,你可以在終端中使用以下命令:
go run aes_example.go
這將輸出加密后的字符串和解密后的原始字符串。
請注意,這個例子使用了CBC模式(密碼塊鏈接模式),它是一種常見的加密模式。在實際應用中,你還需要考慮更多的安全措施,比如密鑰管理和初始化向量(IV)的安全存儲。此外,密鑰應該是隨機生成的,并且安全地存儲或傳輸,以確保加密的安全性。