借助网络配置,控制Modbus工具的日志显示,避免卡死界面
智能大石头 authored at 2021-12-11 22:09:19
13.17 KiB
XCoder
using System;
using System.ComponentModel;
using System.Linq;
using NewLife.Data;
using NewLife.XCoder.Tools.Crypto;

namespace XCoder.App.Tests;

/// <summary>摘要与编解码测试</summary>
public class CryptoServiceTests
{
    [Fact]
    [DisplayName("MD5 摘要结果正确")]
    public void Md5_Matches_KnownValue()
        => Assert.Equal("900150983cd24fb0d6963f7d28e17f72", CryptoService.Run("abc", CryptoOperation.Md5));

    [Fact]
    [DisplayName("SHA256 摘要结果正确")]
    public void Sha256_Matches_KnownValue()
        => Assert.Equal("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", CryptoService.Run("abc", CryptoOperation.Sha256));

    [Fact]
    [DisplayName("Base64 编解码往返")]
    public void Base64_RoundTrip()
    {
        const String text = "码神工具 NewLife.XCoder";
        var encoded = CryptoService.Run(text, CryptoOperation.Base64Encode);

        Assert.Equal(text, CryptoService.Run(encoded, CryptoOperation.Base64Decode));
    }

    [Fact]
    [DisplayName("十六进制编解码往返")]
    public void Hex_RoundTrip()
    {
        const String text = "Hello 码神";
        var encoded = CryptoService.Run(text, CryptoOperation.HexEncode);

        Assert.Equal(text, CryptoService.Run(encoded, CryptoOperation.HexDecode));
        Assert.Matches("^[0-9A-F]+$", encoded);
    }

    [Fact]
    [DisplayName("URL 编解码往返")]
    public void Url_RoundTrip()
    {
        const String text = "a=1&b=中文 空格/路径";
        var encoded = CryptoService.Run(text, CryptoOperation.UrlEncode);

        Assert.NotEqual(text, encoded);
        Assert.Equal(text, CryptoService.Run(encoded, CryptoOperation.UrlDecode));
    }

    [Fact]
    [DisplayName("非法 Base64 输入抛异常")]
    public void Invalid_Base64_Throws()
        => Assert.ThrowsAny<Exception>(() => CryptoService.Run("***", CryptoOperation.Base64Decode));

    [Fact]
    [DisplayName("奇数长度十六进制抛 FormatException")]
    public void Odd_Hex_Throws()
        => Assert.Throws<FormatException>(() => CryptoService.Run("ABC", CryptoOperation.HexDecode));

    [Fact]
    [DisplayName("MD5-16 输出 16 位十六进制")]
    public void Md5_16_Returns_16_Chars()
    {
        var result = CryptoService.Execute(CryptoCommand.Md5_16, "abc", new CryptoOptions { HexOutput = true, Base64Output = false });

        Assert.Equal("900150983CD24FB0", result.Text.Split('\n')[0].Trim());
    }

    [Fact]
    [DisplayName("CRC-32 与 CRC-16 校验值符合标准向量")]
    public void Crc_Matches_KnownValues()
    {
        var crc32 = CryptoService.Execute(CryptoCommand.Crc32, "123456789");
        var crc16 = CryptoService.Execute(CryptoCommand.Crc16, "123456789");

        Assert.Contains("0xCBF43926", crc32.Text);
        Assert.Contains("CRC16/CCITT:31C3", crc16.Text);
        Assert.Contains("CRC16/Modbus:4B37", crc16.Text);
        Assert.Contains("Modbus 报文顺序:37 4B", crc16.Text);
    }

    [Fact]
    [DisplayName("HEX 编码输出四种形式且可反向解码")]
    public void Hex_Encode_Formats_RoundTrip()
    {
        const String text = "Hello 码神";
        var encoded = CryptoService.Execute(CryptoCommand.HexEncode, text);
        var lines = encoded.Text.Split("\r\n");

        Assert.Equal(4, lines.Length);
        Assert.Equal("48656C6C6F20E7A081E7A59E", lines[0]);
        Assert.Equal("48-65-6C-6C-6F-20-E7-A0-81-E7-A5-9E", lines[2]);
        Assert.Equal("48 65 6C 6C 6F 20 E7 A0 81 E7 A5 9E", lines[3]);

        var decoded = CryptoService.Execute(CryptoCommand.HexDecode, lines[2]);
        Assert.Equal(text, decoded.Text);
    }

    [Fact]
    [DisplayName("Base64URL 编解码往返")]
    public void Base64Url_RoundTrip()
    {
        const String text = "码神工具/测试+值";
        var encoded = CryptoService.Execute(CryptoCommand.Base64UrlEncode, text);

        Assert.DoesNotContain("=", encoded.Text);
        Assert.DoesNotContain("+", encoded.Text);
        Assert.DoesNotContain("/", encoded.Text);

        var decoded = CryptoService.Execute(CryptoCommand.Base64UrlDecode, encoded.Text);
        Assert.Equal(text, decoded.Text);
    }

    [Fact]
    [DisplayName("Unicode 转义与还原往返")]
    public void Unicode_RoundTrip()
    {
        const String text = "中文 A\r\n";
        var encoded = CryptoService.Execute(CryptoCommand.UnicodeEncode, text);

        Assert.Contains("\\u4E2D\\u6587", encoded.Text);
        Assert.Contains("\\u000D\\u000A", encoded.Text);

        var decoded = CryptoService.Execute(CryptoCommand.UnicodeDecode, encoded.Text);
        Assert.Equal(text, decoded.Text);
    }

    [Fact]
    [DisplayName("HTML 编码与解码往返")]
    public void Html_RoundTrip()
    {
        const String text = "<a href=\"x\">A&B</a>";
        var encoded = CryptoService.Execute(CryptoCommand.HtmlEncode, text);

        Assert.DoesNotContain("<a", encoded.Text);
        Assert.Equal(text, CryptoService.Execute(CryptoCommand.HtmlDecode, encoded.Text).Text);
    }

    [Fact]
    [DisplayName("时间戳互转同时给出秒与毫秒")]
    public void Timestamp_Converts_SecondsAndMilliseconds()
    {
        var result = CryptoService.Execute(CryptoCommand.Timestamp, "1762872431");

        Assert.Contains("Unix 秒:1762872431", result.Text);
        Assert.Contains("Unix 毫秒:1762872431000", result.Text);
        Assert.Contains("ISO 8601:", result.Text);
    }

    [Fact]
    [DisplayName("JWT 解码输出 Header、Payload 与过期时间")]
    public void Jwt_Decodes_HeaderAndPayload()
    {
        const String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0IiwiZXhwIjo0MTAyNDQ0ODAwfQ.abc";
        var result = CryptoService.Execute(CryptoCommand.JwtDecode, token);

        Assert.Contains("\"alg\": \"HS256\"", result.Text);
        Assert.Contains("\"sub\": \"test\"", result.Text);
        Assert.Contains("过期时间 (exp):", result.Text);
        Assert.Contains("未校验", result.Text);
    }

    [Fact]
    [DisplayName("GUID 输出五种格式")]
    public void Guid_Returns_FiveFormats()
    {
        var result = CryptoService.Execute(CryptoCommand.NewGuid, "");
        var lines = result.Text.Split("\r\n");

        Assert.Equal(5, lines.Length);
        Assert.StartsWith("N:", lines[0]);
        Assert.StartsWith("D:", lines[1]);
        Assert.StartsWith("B:", lines[2]);
        Assert.StartsWith("P:", lines[3]);
        Assert.StartsWith("X:", lines[4]);
        Assert.Equal(32, lines[0][2..].Length);
    }

    [Fact]
    [DisplayName("随机密码按指定长度生成 5 条")]
    public void RandomPassword_Uses_Length()
    {
        var result = CryptoService.Execute(CryptoCommand.RandomPassword, "", new CryptoOptions { Parameter = "24" });
        var lines = result.Text.Split("\r\n");

        Assert.Equal(5, lines.Length);
        Assert.All(lines, e => Assert.Equal(24, e.Length));
        Assert.True(lines.Distinct().Count() > 1, "随机密码不应重复");
    }

    [Fact]
    [DisplayName("雪花 Id 可解析出时间、节点与序号")]
    public void Snowflake_Parses_GeneratedId()
    {
        var id = new Snowflake().NewId();
        var result = CryptoService.Execute(CryptoCommand.Snowflake, id.ToString());

        Assert.Contains($"Id:{id}", result.Text);
        Assert.Contains("时间:", result.Text);
        Assert.Contains("节点:", result.Text);
        Assert.Contains("序号:", result.Text);
    }

    [Fact]
    [DisplayName("RSA 加解密与签名验签全链路")]
    public void Rsa_EncryptDecrypt_And_SignVerify()
    {
        var keys = CryptoService.GenerateRsaKeyPair(1024);
        const String text = "RSA 往返测试";

        var encrypted = CryptoService.Execute(CryptoCommand.RsaEncrypt, text, new CryptoOptions
        {
            Key = keys.PublicKey,
            HexOutput = false,
            Base64Output = true,
        });
        var cipher = encrypted.Text.Split("\r\n")[0];

        var decrypted = CryptoService.Execute(CryptoCommand.RsaDecrypt, cipher, new CryptoOptions
        {
            Key = keys.PrivateKey,
            InputFormat = CryptoInputFormat.Base64,
            TextOutput = true,
            HexOutput = false,
            Base64Output = false,
        });
        Assert.Equal(text, decrypted.Text);

        var signature = CryptoService.Execute(CryptoCommand.RsaSign, text, new CryptoOptions
        {
            Key = keys.PrivateKey,
            HexOutput = true,
            Base64Output = false,
        }).Text.Split("\r\n")[0];

        var verified = CryptoService.Execute(CryptoCommand.RsaVerify, text, new CryptoOptions
        {
            Key = keys.PublicKey,
            Signature = signature,
        });
        Assert.Equal("验证通过 ✔", verified.Text);
        Assert.False(verified.IsError);
    }

    [Fact]
    [DisplayName("HMAC-SHA256 符合标准向量")]
    public void HmacSha256_Matches_KnownValue()
    {
        var result = CryptoService.Execute(CryptoCommand.HmacSha256, "The quick brown fox jumps over the lazy dog", new CryptoOptions
        {
            Parameter = "key",
            HexOutput = true,
            Base64Output = false,
        });

        Assert.Equal("F7BC83F430538424B13298E6AA6FB143EF4D59A14946175997479DBC2D1A3CD8", result.Text.Split("\r\n")[0]);
    }

    [Fact]
    [DisplayName("密码支持字符串、HEX 与 Base64 三种格式且结果一致")]
    public void Hmac_Key_Format_Equivalence()
    {
        var text = CryptoService.Execute(CryptoCommand.HmacSha256, "abc", new CryptoOptions
        {
            Parameter = "key",
            ParameterFormat = CryptoInputFormat.Text,
            HexOutput = true,
            Base64Output = false,
        });
        var hex = CryptoService.Execute(CryptoCommand.HmacSha256, "abc", new CryptoOptions
        {
            Parameter = "6B6579",
            ParameterFormat = CryptoInputFormat.Hex,
            HexOutput = true,
            Base64Output = false,
        });
        var base64 = CryptoService.Execute(CryptoCommand.HmacSha256, "abc", new CryptoOptions
        {
            Parameter = "a2V5",
            ParameterFormat = CryptoInputFormat.Base64,
            HexOutput = true,
            Base64Output = false,
        });

        Assert.Equal(text.Text, hex.Text);
        Assert.Equal(text.Text, base64.Text);
    }

    [Fact]
    [DisplayName("结果按字符串、HEX、Base64 分组并带变体")]
    public void Result_Outputs_Are_Grouped_And_Varianted()
    {
        var result = CryptoService.Execute(CryptoCommand.Md5_32, "abc", new CryptoOptions
        {
            TextOutput = true,
            HexOutput = true,
            Base64Output = true,
        });

        Assert.Equal(3, result.Outputs.Count);
        Assert.Equal(["字符串", "HEX", "Base64"], result.Outputs.Select(e => e.Label));
        Assert.Equal(CryptoInputFormat.Hex, result.Outputs[1].Format);
        Assert.Equal(4, result.Outputs[1].Variants.Count);
        Assert.Equal("小写", result.Outputs[1].Variants[1].Label);
        Assert.Equal(2, result.Outputs[2].Variants.Count);
        Assert.Equal("URL 安全", result.Outputs[2].Variants[1].Label);
    }

    [Fact]
    [DisplayName("输入解析器支持 HEX 与 Base64")]
    public void ParseInput_Supports_Hex_And_Base64()
    {
        var hex = CryptoService.ParseInput("48 65 6C 6C 6F", CryptoInputFormat.Hex);
        var base64 = CryptoService.ParseInput("SGVsbG8=", CryptoInputFormat.Base64);

        Assert.Equal("Hello", System.Text.Encoding.UTF8.GetString(hex));
        Assert.Equal(hex, base64);
    }

    [Fact]
    [DisplayName("Base64 编码结果可直接作为 CRC-32 的 Base64 输入")]
    public void Chain_Base64_Then_Crc32()
    {
        var encoded = CryptoService.Execute(CryptoCommand.Base64Encode, "123456");
        var base64 = encoded.Outputs.Single(e => e.Label == "Base64").Value;

        var chained = CryptoService.Execute(CryptoCommand.Crc32, base64, new CryptoOptions { InputFormat = CryptoInputFormat.Base64 });
        var direct = CryptoService.Execute(CryptoCommand.Crc32, "123456");

        Assert.Equal(direct.Text, chained.Text);
    }

    [Fact]
    [DisplayName("MD5 的 Base64 结果可作为 RSA 的 Base64 输入并还原")]
    public void Chain_Md5_Then_Rsa()
    {
        var md5 = CryptoService.Execute(CryptoCommand.Md5_32, "abc", new CryptoOptions { HexOutput = true, Base64Output = true });
        var base64 = md5.Outputs.Single(e => e.Label == "Base64").Value;
        var expectedHex = md5.Outputs.Single(e => e.Label == "HEX").Value;

        var keys = CryptoService.GenerateRsaKeyPair(1024);
        var encrypted = CryptoService.Execute(CryptoCommand.RsaEncrypt, base64, new CryptoOptions
        {
            InputFormat = CryptoInputFormat.Base64,
            Key = keys.PublicKey,
            HexOutput = false,
            Base64Output = true,
        });
        var cipher = encrypted.Outputs.Single(e => e.Label == "Base64").Value;

        var decrypted = CryptoService.Execute(CryptoCommand.RsaDecrypt, cipher, new CryptoOptions
        {
            InputFormat = CryptoInputFormat.Base64,
            Key = keys.PrivateKey,
            TextOutput = false,
            HexOutput = true,
            Base64Output = true,
        });

        Assert.Equal(expectedHex, decrypted.Outputs.Single(e => e.Label == "HEX").Value);
    }
}