在Debian系统中,Go语言可以使用标准库中的"crypto"包来进行数据加密。以下是一个简单的示例,展示了如何使用Go语言进行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 := []byte("Hello, World!") // 需要加密的数据
// 加密
ciphertext, err := encrypt(key, plaintext)
if err != nil {
panic(err)
}
fmt.Printf("Encrypted data: %s\n", base64.StdEncoding.EncodeToString(ciphertext))
// 解密
decryptedText, err := decrypt(key, ciphertext)
if err != nil {
panic(err)
}
fmt.Printf("Decrypted data: %s\n", decryptedText)
}
func encrypt(key, plaintext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
return ciphertext, nil
}
func decrypt(key, ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if len(ciphertext) < aes.BlockSize {
return nil, fmt.Errorf("ciphertext too short")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
stream.XORKeyStream(ciphertext, ciphertext)
return ciphertext, nil
}
在这个示例中,我们使用了AES加密算法,它是一种对称加密算法。你需要提供一个密钥(key),用于加密和解密数据。请确保密钥的长度是16、24或32字节,以匹配AES-128、AES-192或AES-256加密。
运行此程序,你将看到加密后的数据以及解密后的原始数据。
$ go run main.go
Encrypted data: 7sJyZkKjvGxYmEzRZgXzqg==
Decrypted data: Hello, World!
请注意,这个示例仅用于演示目的。在实际应用中,你需要考虑更多的安全措施,例如使用安全的密钥管理方法和加密模式。