C# 国密加密

一、国密

  1.非对称密钥加密(SM2) 

  SM2算法就是ECC椭圆曲线密码机制,包括:
  – 数字签名算法(包括数字签名生成算法和验证算法)。
  – 密钥交换协议
  – 以及公钥加密算法(包括加密算法和解密算法)。
  在签名、密钥交换方面不同于ECDSA、ECDH等国际标准,而是采取了更为安全的机制。
  SM2推荐了一条256位的曲线作为标准曲线。

  2.单向散列算法(SM3)

  SM3算法适用于商用密码应用中的:
  – 数字签名和验证。
  – 消息认证码的生成与验证
  – 以及随机数的生成。
  在SM2,SM9标准中使用。
  此算法对输入长度小于2的64次方的比特消息,经过填充和迭代压缩,生成长度为256比特的杂凑值。
  其中使用了异或,模,模加,移位,与,或,非运算,由填充,迭代过程,消息扩展和压缩函数所构成。

  3.对称秘钥加密(SM4)

  SM4算法主要用于无线局域网产品。该算法的分组长度为128比特,密钥长度为128比特。
  加密算法与密钥扩展算法都采用32轮非线性迭代结构。解密算法与加密算法的结构相同,只是轮密钥的使用顺序相反。
  此算法采用非线性迭代结构,每次迭代由一个轮函数给出,其中轮函数由一个非线性变换和线性变换复合而成,非线性变换由S盒所给出。

二、国密的使用

  1.nuget引用程序集:KYSharp.SM(如果是.net core 或 .net 5以上选择KYSharp.SM.Core)

  

  2.SM2的使用

static void SM2Console()
{
    //公钥
    string publickey = "";
    //私钥
    string privatekey = "";
    //生成公钥和私钥
    SM2Utils.GenerateKeyPair(out publickey, out privatekey);

    Console.Out.WriteLine("加密明文: " + "000000");
    Console.Out.WriteLine("publickey:" + publickey);
    //开始加密
    string cipherText = SM2Utils.Encrypt_Hex(publickey, "000000", Encoding.UTF8);
    Console.Out.WriteLine("密文: " + cipherText);
    Console.Out.WriteLine("privatekey:" + privatekey);
    //解密
    string plainText = SM2Utils.Decrypt_Hex(privatekey, cipherText, Encoding.UTF8);
    Console.Out.WriteLine("明文: " + plainText);
    Console.ReadLine();
}

  3.SM3的使用

static void SM3Console()
{
    SM3 bo = new SM3();
    string str = bo.Encrypt("asdfasde");
    Console.WriteLine("密文:" + str);
    Console.WriteLine("长度:" + str.Length);
    str = bo.Encrypt("asdfasdf");
    Console.WriteLine("密文:" + str);
    Console.WriteLine("长度:" + str.Length);

    Console.ReadLine();

}

  4.SM4的使用

static void SM4Console()
{
    string plainText = "ererfeiisgod";

    SM4Utils sm4 = new SM4Utils();
    sm4.secretKey = "JeF8U9wHFOMfs2Y8";
    sm4.hexString = false;

    Console.Out.WriteLine("ECB模式");
    string cipherText = sm4.Encrypt_ECB(plainText);
    Console.Out.WriteLine("密文: " + cipherText);
    Console.Out.WriteLine("");

    plainText = sm4.Decrypt_ECB(cipherText);
    Console.Out.WriteLine("明文: " + plainText);
    Console.Out.WriteLine("");

    Console.Out.WriteLine("CBC模式");
    sm4.iv = "UISwD9fW6cFh9SNS";
    cipherText = sm4.Encrypt_CBC(plainText);
    Console.Out.WriteLine("密文: " + cipherText);
    Console.Out.WriteLine("");

    plainText = sm4.Decrypt_CBC(cipherText);
    Console.Out.WriteLine("明文: " + plainText);

    Console.ReadLine();
}

  5.运行结果

 

posted @ 2022-04-25 14:31  Zeng。  阅读(3059)  评论(0编辑  收藏  举报