在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)的安全存储。此外,密钥应该是随机生成的,并且安全地存储或传输,以确保加密的安全性。