基于BS的辅助类库


公私钥生成

SMCrypto.GenerateSm2KeyHex(out string publicKey, out string privateKey);
Console.WriteLine(publicKey);
Console.WriteLine(privateKey);

解密

[TestMethod]
public async Task Sm2Decrypt()
{
    var sourceData = "cee2b41e1013cce3823b464e1b8e2290fcfe9c75298cd53057799de1c2ce58538b5a2fc7a7d391d66d10506c64e3a6bb4110ca52d7f33434e0254e951ec6c71edf7f198b3d7b016bb712cffe52a356ba61df30fcb9428848d0bd1d4633719a08d5c4db6594de";
    if (!sourceData.StartsWith("04")) {
        sourceData = "04" + sourceData;
    }
    var msgData = SMCrypto.Sm2Decrypt(sourceData, privateKey);
    var msg = Encoding.UTF8.GetString(msgData);
    Console.WriteLine(msg);
    Assert.AreEqual("123456", msg);
}

签名与验签

[TestMethod]
public async Task SignAndVerifySign()
{
    Sign("123456", privateKey, "test", out string sign);

    var isSuccess = VerifySign("123456", publicKey, sign, "test");

    Console.WriteLine(sign);
    Assert.IsTrue(isSuccess);
}


/// <summary>
/// 签名,国密SM2
/// </summary>
/// <param name="body">参数内容</param>
/// <param name="privateKey">私钥</param>
/// <param name="sign">签名值</param>
/// <param name="timestamp">时间戳</param>
public void Sign(string body, string privateKey,string userId, out string sign)
{
    if (string.IsNullOrWhiteSpace(body)) throw new ArgumentNullException(nameof(body));
    if (string.IsNullOrWhiteSpace(privateKey)) throw new ArgumentNullException(nameof(privateKey));
    if (string.IsNullOrWhiteSpace(userId)) throw new ArgumentNullException(nameof(userId));


    // 加密算法采用SM2加密算法
    sign = SMCrypto.HexString(SMCrypto.Sign(Encoding.UTF8.GetBytes(body), SMCrypto.Decode(privateKey), Encoding.UTF8.GetBytes(userId)));
}

/// <summary>
/// 验签,国密SM2
/// </summary>
/// <param name="body">参数内容</param>
/// <param name="publicKey">公约</param>
/// <param name="sign">签名值</param>
/// <param name="timestamp">时间戳</param>
/// <returns>成功与否</returns>
public bool VerifySign(string body, string publicKey, string sign, string userId)
{
    if (string.IsNullOrWhiteSpace(body)) throw new ArgumentNullException(nameof(body));
    if (string.IsNullOrWhiteSpace(publicKey)) throw new ArgumentNullException(nameof(publicKey));
    if (string.IsNullOrWhiteSpace(sign)) throw new ArgumentNullException(nameof(sign));
    if (string.IsNullOrWhiteSpace(userId)) throw new ArgumentNullException(nameof(userId));

    return SMCrypto.VerifySign(Encoding.UTF8.GetBytes(body), SMCrypto.Decode(publicKey), SMCrypto.Decode(sign),
            Encoding.UTF8.GetBytes(userId));
}