在Go語言中,有多種方法可以實現文件加密。這里,我將向您介紹兩種常用的加密方法:AES加密和使用Go內置的crypto/aes包進行加密。
AES(Advanced Encryption Standard)是一種對稱加密算法,它使用相同的密鑰進行加密和解密。在Go語言中,可以使用crypto/aes
和crypto/cipher
包來實現AES加密。
以下是一個簡單的AES加密示例:
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
"os"
)
func main() {
key := []byte("0123456789abcdef") // 16字節的密鑰,對應AES-128
plaintext := []byte("Hello, World!")
ciphertext, err := encryptAES(key, plaintext)
if err != nil {
fmt.Println("Error encrypting:", err)
return
}
fmt.Printf("Encrypted text: %s\n", base64.StdEncoding.EncodeToString(ciphertext))
}
func encryptAES(key, plaintext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
nonce := make([]byte, aes.BlockSize)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
ciphertext := aesGCM.Seal(nil, nonce, plaintext, nil)
return append(nonce, ciphertext...), nil
}
Go 1.16版本引入了crypto/aes
包,它提供了一種更簡單的方法來實現AES加密。以下是一個使用crypto/aes
包進行加密的示例:
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
"os"
)
func main() {
key := []byte("0123456789abcdef") // 16字節的密鑰,對應AES-128
plaintext := []byte("Hello, World!")
ciphertext, err := encrypt(key, plaintext)
if err != nil {
fmt.Println("Error encrypting:", err)
return
}
fmt.Printf("Encrypted text: %s\n", base64.StdEncoding.EncodeToString(ciphertext))
}
func encrypt(key, plaintext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, aesGCM.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
ciphertext := aesGCM.Seal(nil, nonce, plaintext, nil)
return append(nonce, ciphertext...), nil
}
這兩種方法都可以實現AES加密,您可以根據自己的需求選擇合適的方法。注意,為了確保加密后的數據安全,請妥善保管密鑰。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。