using System;
using System.ComponentModel;
using System.Text;
using NewLife.XCoder.Services;
using Xunit;
namespace XCoder.App.Tests;
/// <summary>Windows DPAPI 加解密与凭据存储的算法前缀</summary>
public class DpapiProtectorTests
{
[Fact]
[DisplayName("Windows 上 DPAPI 往返一致,两次密文不同")]
public void Protect_Unprotect_RoundTrip()
{
if (!DpapiProtector.IsSupported) return;
var data = Encoding.UTF8.GetBytes("Data Source=db;Password=123456");
var cipher1 = DpapiProtector.Protect(data);
var cipher2 = DpapiProtector.Protect(data);
Assert.NotNull(cipher1);
Assert.NotNull(cipher2);
Assert.NotEqual(Convert.ToBase64String(cipher1!), Convert.ToBase64String(cipher2!));
Assert.Equal(data, DpapiProtector.Unprotect(cipher1));
Assert.Equal(data, DpapiProtector.Unprotect(cipher2));
}
[Fact]
[DisplayName("DPAPI 密文被篡改后解密失败而不抛异常")]
public void Unprotect_Tampered_ReturnsNull()
{
if (!DpapiProtector.IsSupported) return;
var cipher = DpapiProtector.Protect(Encoding.UTF8.GetBytes("secret"));
Assert.NotNull(cipher);
var broken = (Byte[])cipher!.Clone();
broken[broken.Length / 2] ^= 0xFF;
Assert.Null(DpapiProtector.Unprotect(broken));
}
[Fact]
[DisplayName("空数据与空引用不抛异常")]
public void Protect_Empty_ReturnsNull()
{
if (!DpapiProtector.IsSupported) return;
Assert.Null(DpapiProtector.Protect(null));
Assert.Null(DpapiProtector.Protect([]));
Assert.Null(DpapiProtector.Unprotect(null));
Assert.Null(DpapiProtector.Unprotect([]));
}
[Fact]
[DisplayName("Windows 上凭据落盘使用 dpapi 前缀,其它平台使用 aes 前缀")]
public void Credential_Encrypt_UsesPrefixedCipher()
{
var cipher = CredentialStore.Encrypt("P@ssw0rd!");
if (DpapiProtector.IsSupported)
Assert.StartsWith("dpapi:", cipher);
else
Assert.StartsWith("aes:", cipher);
Assert.Equal("P@ssw0rd!", CredentialStore.Decrypt(cipher));
}
[Fact]
[DisplayName("旧版无前缀 AES 密文仍能解密(向后兼容)")]
public void Credential_Decrypt_LegacyAesCipher()
{
// 手工构造旧格式:Base64(iv + cipher)
var legacy = CredentialStore.EncryptAes(Encoding.UTF8.GetBytes("old-secret"));
Assert.Equal("old-secret", CredentialStore.Decrypt(legacy));
Assert.Equal("old-secret", CredentialStore.Decrypt("aes:" + legacy));
}
[Fact]
[DisplayName("dpapi 前缀但非 Base64 时返回 null 而不是抛异常")]
public void Credential_Decrypt_BrokenDpapi_ReturnsNull()
{
Assert.Null(CredentialStore.Decrypt("dpapi:not-base64"));
}
}
|