AES 加密添加校验位;继续写 Config

This commit is contained in:
龙腾猫跃 committed 2026-06-19 05:56:52 +08:00
1 parent 7bf59d7f74
commit f64685b177
4 files changed
+168 -43

No files matched your search

+36
View File
@@ -0,0 +1,36 @@
namespace MeloongCore.Tests;
public class ConfigTest : TestWithFolder {
[Test]
public async Task JsonConfigProvider_EncryptedReadWrite() {
var filePath = Path.Combine(tempFolder, "config.json");
var provider = new JsonConfigProvider(filePath);
provider.Set("token", "plain token", encrypted: true);
provider.Save();
await Assert.That(FileUtils.ReadAsString(filePath).Contains("plain token")).IsFalse();
await Assert.That(provider.Read("token", encrypted: true)).IsEqualTo("plain token");
await Assert.That(provider.DecryptedContent.TryGetValue("token", out var decrypted) && decrypted == "plain token").IsTrue();
}
[Test]
public async Task JsonConfigProvider_ClearCache() {
var filePath = Path.Combine(tempFolder, "config.json");
var provider = new JsonConfigProvider(filePath);
provider.Set("token", "old token", encrypted: true);
provider.Save();
await Assert.That(provider.Read("token", encrypted: true)).IsEqualTo("old token");
var secondProvider = new JsonConfigProvider(filePath);
secondProvider.Set("token", "new token", encrypted: true);
secondProvider.Save();
provider.ClearCache();
await Assert.That(provider.DecryptedContent.IsEmpty).IsTrue();
await Assert.That(provider.Read("token", encrypted: true)).IsEqualTo("new token");
}
}
+9 -1
View File
@@ -11,7 +11,8 @@ public class CryptographyUtilsTest : TestBase {
[Arguments("中文内容 Test 123 !@#$%^&*()")]
public async Task 对称加密_往返(string sourceString) {
string encryptedString = CryptographyUtils.AesEncrypt(sourceString, "PCL-Key-中文");
await Assert.That(encryptedString != sourceString).IsTrue();
if (!string.IsNullOrEmpty(sourceString))
await Assert.That(encryptedString != sourceString).IsTrue();
await Assert.That(CryptographyUtils.AesDecrypt(encryptedString, "PCL-Key-中文")).IsEqualTo(sourceString);
}
@@ -26,6 +27,13 @@ public class CryptographyUtilsTest : TestBase {
Assert.Throws<CryptographicException>(() => CryptographyUtils.AesDecrypt(Convert.ToBase64String(encryptedBytes), "key"));
}
[Test]
public void AesDecrypt_TamperedIvFails() {
byte[] encryptedBytes = Convert.FromBase64String(CryptographyUtils.AesEncrypt("source", "key"));
encryptedBytes[1] ^= 1;
Assert.Throws<CryptographicException>(() => CryptographyUtils.AesDecrypt(Convert.ToBase64String(encryptedBytes), "key"));
}
[Test]
public void 对称加密_错误密钥失败() {
Assert.Throws<CryptographicException>(() => CryptographyUtils.AesDecrypt(CryptographyUtils.AesEncrypt("source", "key"), "bad key"));