123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- package aes
- import (
- "crypto/aes"
- "crypto/cipher"
- "crypto/hmac"
- "crypto/rand"
- "crypto/sha256"
- "io"
- "os"
- )
- // 加密密钥和签名密钥
- var AesKey = []byte("AESKey1234567890")
- var hmacKey = []byte("HMACKey1234567890")
- func EncryptFile(filePath string, aesKey []byte, hmacKey []byte) ([]byte, []byte, error) {
- // 读取文件内容
- fileContent, err := os.ReadFile(filePath)
- if err != nil {
- return nil, nil, err
- }
- // 创建 AES 加密块
- block, err := aes.NewCipher(AesKey)
- if err != nil {
- return nil, nil, err
- }
- // 创建 AES 加密模式
- gcm, err := cipher.NewGCM(block)
- if err != nil {
- return nil, nil, err
- }
- // 生成随机 nonce
- nonce := make([]byte, gcm.NonceSize())
- if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
- return nil, nil, err
- }
- // 加密文件内容
- encryptedFileContent := gcm.Seal(nil, nonce, fileContent, nil)
- // 计算 HMAC 签名
- h := hmac.New(sha256.New, hmacKey)
- _, err = h.Write(encryptedFileContent)
- if err != nil {
- return nil, nil, err
- }
- signature := h.Sum(nil)
- return encryptedFileContent, signature, nil
- }
|