first commit

This commit is contained in:
Awuqing
2026-03-17 13:29:09 +08:00
commit eadd3f8961
219 changed files with 22394 additions and 0 deletions

View File

@@ -0,0 +1,60 @@
package compress
import (
"compress/gzip"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
func GzipFile(sourcePath string) (string, error) {
source, err := os.Open(sourcePath)
if err != nil {
return "", fmt.Errorf("open source file: %w", err)
}
defer source.Close()
targetPath := sourcePath + ".gz"
target, err := os.Create(targetPath)
if err != nil {
return "", fmt.Errorf("create gzip file: %w", err)
}
defer target.Close()
writer := gzip.NewWriter(target)
writer.Name = filepath.Base(sourcePath)
if _, err := io.Copy(writer, source); err != nil {
writer.Close()
return "", fmt.Errorf("gzip source file: %w", err)
}
if err := writer.Close(); err != nil {
return "", fmt.Errorf("close gzip writer: %w", err)
}
return targetPath, nil
}
func GunzipFile(sourcePath string) (string, error) {
source, err := os.Open(sourcePath)
if err != nil {
return "", fmt.Errorf("open gzip file: %w", err)
}
defer source.Close()
reader, err := gzip.NewReader(source)
if err != nil {
return "", fmt.Errorf("create gzip reader: %w", err)
}
defer reader.Close()
targetPath := strings.TrimSuffix(sourcePath, ".gz")
if targetPath == sourcePath {
targetPath += ".out"
}
target, err := os.Create(targetPath)
if err != nil {
return "", fmt.Errorf("create target file: %w", err)
}
defer target.Close()
if _, err := io.Copy(target, reader); err != nil {
return "", fmt.Errorf("gunzip file: %w", err)
}
return targetPath, nil
}

View File

@@ -0,0 +1,29 @@
package compress
import (
"os"
"path/filepath"
"testing"
)
func TestGzipAndGunzipFile(t *testing.T) {
sourcePath := filepath.Join(t.TempDir(), "payload.txt")
if err := os.WriteFile(sourcePath, []byte("payload"), 0o644); err != nil {
t.Fatalf("WriteFile returned error: %v", err)
}
compressedPath, err := GzipFile(sourcePath)
if err != nil {
t.Fatalf("GzipFile returned error: %v", err)
}
decompressedPath, err := GunzipFile(compressedPath)
if err != nil {
t.Fatalf("GunzipFile returned error: %v", err)
}
content, err := os.ReadFile(decompressedPath)
if err != nil {
t.Fatalf("ReadFile returned error: %v", err)
}
if string(content) != "payload" {
t.Fatalf("unexpected decompressed content: %s", string(content))
}
}

View File

@@ -0,0 +1,128 @@
package backupcrypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/binary"
"fmt"
"io"
"os"
"strings"
)
const (
chunkSize = 1 << 20
fileMagic = "BXENC1"
nonceSizeBytes = 12
)
func EncryptFile(key []byte, sourcePath string) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
return "", fmt.Errorf("create cipher: %w", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", fmt.Errorf("create gcm: %w", err)
}
source, err := os.Open(sourcePath)
if err != nil {
return "", fmt.Errorf("open source file: %w", err)
}
defer source.Close()
targetPath := sourcePath + ".enc"
target, err := os.Create(targetPath)
if err != nil {
return "", fmt.Errorf("create encrypted file: %w", err)
}
defer target.Close()
if _, err := target.WriteString(fileMagic); err != nil {
return "", fmt.Errorf("write encryption header: %w", err)
}
buffer := make([]byte, chunkSize)
for {
readCount, readErr := source.Read(buffer)
if readCount > 0 {
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return "", fmt.Errorf("generate nonce: %w", err)
}
sealed := gcm.Seal(nil, nonce, buffer[:readCount], nil)
if _, err := target.Write(nonce); err != nil {
return "", fmt.Errorf("write nonce: %w", err)
}
if err := binary.Write(target, binary.BigEndian, uint32(len(sealed))); err != nil {
return "", fmt.Errorf("write ciphertext length: %w", err)
}
if _, err := target.Write(sealed); err != nil {
return "", fmt.Errorf("write ciphertext: %w", err)
}
}
if readErr == io.EOF {
break
}
if readErr != nil {
return "", fmt.Errorf("read source file: %w", readErr)
}
}
return targetPath, nil
}
func DecryptFile(key []byte, sourcePath string) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
return "", fmt.Errorf("create cipher: %w", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", fmt.Errorf("create gcm: %w", err)
}
source, err := os.Open(sourcePath)
if err != nil {
return "", fmt.Errorf("open encrypted file: %w", err)
}
defer source.Close()
header := make([]byte, len(fileMagic))
if _, err := io.ReadFull(source, header); err != nil {
return "", fmt.Errorf("read encryption header: %w", err)
}
if string(header) != fileMagic {
return "", fmt.Errorf("invalid encrypted file header")
}
targetPath := strings.TrimSuffix(sourcePath, ".enc")
if targetPath == sourcePath {
targetPath += ".plain"
}
target, err := os.Create(targetPath)
if err != nil {
return "", fmt.Errorf("create decrypted file: %w", err)
}
defer target.Close()
for {
nonce := make([]byte, nonceSizeBytes)
_, err := io.ReadFull(source, nonce)
if err == io.EOF {
break
}
if err != nil {
return "", fmt.Errorf("read nonce: %w", err)
}
var cipherLength uint32
if err := binary.Read(source, binary.BigEndian, &cipherLength); err != nil {
return "", fmt.Errorf("read ciphertext length: %w", err)
}
ciphertext := make([]byte, cipherLength)
if _, err := io.ReadFull(source, ciphertext); err != nil {
return "", fmt.Errorf("read ciphertext payload: %w", err)
}
plain, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return "", fmt.Errorf("decrypt chunk: %w", err)
}
if _, err := target.Write(plain); err != nil {
return "", fmt.Errorf("write decrypted payload: %w", err)
}
}
return targetPath, nil
}

View File

@@ -0,0 +1,31 @@
package backupcrypto
import (
"crypto/sha256"
"os"
"path/filepath"
"testing"
)
func TestEncryptAndDecryptFile(t *testing.T) {
hash := sha256.Sum256([]byte("backup-secret"))
sourcePath := filepath.Join(t.TempDir(), "payload.bin")
if err := os.WriteFile(sourcePath, []byte("backup-payload"), 0o644); err != nil {
t.Fatalf("WriteFile returned error: %v", err)
}
encryptedPath, err := EncryptFile(hash[:], sourcePath)
if err != nil {
t.Fatalf("EncryptFile returned error: %v", err)
}
decryptedPath, err := DecryptFile(hash[:], encryptedPath)
if err != nil {
t.Fatalf("DecryptFile returned error: %v", err)
}
content, err := os.ReadFile(decryptedPath)
if err != nil {
t.Fatalf("ReadFile returned error: %v", err)
}
if string(content) != "backup-payload" {
t.Fatalf("unexpected decrypted content: %s", string(content))
}
}

View File

@@ -0,0 +1,30 @@
package response
import (
"errors"
"fmt"
"net/http"
"backupx/server/internal/apperror"
"github.com/gin-gonic/gin"
)
type Envelope struct {
Code string `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
func Success(c *gin.Context, data any) {
c.JSON(http.StatusOK, Envelope{Code: "OK", Message: "success", Data: data})
}
func Error(c *gin.Context, err error) {
fmt.Printf("HTTP Error: %v\n", err)
var appErr *apperror.AppError
if errors.As(err, &appErr) {
c.JSON(appErr.Status, Envelope{Code: appErr.Code, Message: appErr.Message})
return
}
c.JSON(http.StatusInternalServerError, Envelope{Code: "INTERNAL_ERROR", Message: "服务器内部错误"})
}