62 lines
2.0 KiB
C#
62 lines
2.0 KiB
C#
using System.Security.Cryptography;
|
|
using VolcanicCore.Persistence.Encryption;
|
|
|
|
namespace VolcanicCore.Tests;
|
|
|
|
public class EncryptionServiceTests
|
|
{
|
|
private static byte[] NewKey() { var k = new byte[32]; RandomNumberGenerator.Fill(k); return k; }
|
|
|
|
[Fact]
|
|
public void Round_trip()
|
|
{
|
|
var svc = new EncryptionService(NewKey());
|
|
var wire = svc.Encrypt("hunter2");
|
|
Assert.NotEqual("hunter2", wire);
|
|
Assert.Equal("hunter2", svc.Decrypt(wire));
|
|
}
|
|
|
|
[Fact]
|
|
public void Different_ciphertexts_for_same_plaintext()
|
|
{
|
|
var svc = new EncryptionService(NewKey());
|
|
Assert.NotEqual(svc.Encrypt("a"), svc.Encrypt("a"));
|
|
}
|
|
|
|
[Fact]
|
|
public void Tamper_fails()
|
|
{
|
|
var svc = new EncryptionService(NewKey());
|
|
var wire = svc.Encrypt("hello");
|
|
var bytes = Convert.FromBase64String(wire);
|
|
bytes[^1] ^= 0x01; // flip a bit in the tag
|
|
var tampered = Convert.ToBase64String(bytes);
|
|
Assert.ThrowsAny<CryptographicException>(() => svc.Decrypt(tampered));
|
|
}
|
|
|
|
[Fact]
|
|
public void KeyLoader_generates_and_persists_a_key_when_env_and_file_missing()
|
|
{
|
|
var dir = Path.Combine(Path.GetTempPath(), $"vc-{Guid.NewGuid():N}");
|
|
Directory.CreateDirectory(dir);
|
|
var path = Path.Combine(dir, ".enc-key");
|
|
|
|
var k1 = EncryptionKeyLoader.Load(envBase64: null, keyFilePath: path);
|
|
Assert.Equal(32, k1.Length);
|
|
Assert.True(File.Exists(path));
|
|
|
|
var k2 = EncryptionKeyLoader.Load(envBase64: null, keyFilePath: path);
|
|
Assert.Equal(k1, k2); // stable across calls
|
|
}
|
|
|
|
[Fact]
|
|
public void KeyLoader_prefers_env_over_file()
|
|
{
|
|
var envKey = new byte[32]; RandomNumberGenerator.Fill(envKey);
|
|
var loaded = EncryptionKeyLoader.Load(
|
|
envBase64: Convert.ToBase64String(envKey),
|
|
keyFilePath: Path.Combine(Path.GetTempPath(), "does-not-matter"));
|
|
Assert.Equal(envKey, loaded);
|
|
}
|
|
}
|