0.调用
string test= Sm3Crypto.SM3("123");
需要引用动态库BouncyCastle.Crypto,可以从vs NuGet自行下载
代码正常能用,哪位大佬的原帖忘记了,感谢分享,遂再次分享出来;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Utilities.Encoders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tjhis.Obilling.Station.OtherInterface.ENCRYPTION
{
/// <summary>
/// Sm3算法(10进制的ASCII)
/// 在SHA-256基础上改进实现的一种算法
/// 对标国际MD5算法和SHA算法
/// </summary>
public static class Sm3Crypto
{
/// <summary>
/// sm3加密(使用自定义密钥)
/// </summary>
/// <param name="data"></param>
/// <returns></returns>byte[]
public static string ToSM3byte(string data, string key)
{
byte[] msg1 = Encoding.Default.GetBytes(data);
byte[] key1 = Encoding.Default.GetBytes(key);
KeyParameter keyParameter = new KeyParameter(key1);
SM3Digest sm3 = new SM3Digest();
HMac mac = new HMac(sm3);//带密钥的杂凑算法
mac.Init(keyParameter);
mac.BlockUpdate(msg1, 0, msg1.Length);
byte[] result = new byte[mac.GetMacSize()];
mac.DoFinal(result, 0); //Hex.ToHexString();
//return Hex.Encode(result);
return Hex.ToHexString(result);
}
/// <summary>
/// sm3加密
/// </summary>
/// <param name="data"></param>
/// <returns></returns>byte[]
public static string ToSM3byte(this string data)
{
var msg = ToHexByte(data);//把字符串转成16进制的ASCII码
SM3Digest sm3 = new SM3Digest();
sm3.BlockUpdate(msg, 0, msg.Length);
byte[] md = new byte[sm3.GetDigestSize()];//SM3算法产生的哈希值大小
sm3.DoFinal(md, 0);
//return Hex.Encode(md);
return Hex.ToHexString(md);
}
public static string SM3(string data)
{
byte[] md = new byte[32];
byte[] msg1 = Encoding.Default.GetBytes(data);
SM3Digest sm3 = new SM3Digest();
sm3.BlockUpdate(msg1, 0, msg1.Length);
sm3.DoFinal(md, 0);
System.String s = new UTF8Encoding().GetString(Hex.Encode(md));
return s.ToUpper();
}
/// <summary>
/// 字符串转16进制字节数组
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static byte[] ToHexByte(string data)
{
byte[] msg1 = Encoding.Default.GetBytes(data);
string hexString = BytesToHexString(msg1);
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 10);
return returnBytes;
}
/// <summary>
/// byte[]数组转16进制字符串
/// </summary>
/// <param name="input">byte[]数组</param>
/// <returns>16进制字符串</returns>
public static string BytesToHexString(byte[] input)
{
StringBuilder hexString = new StringBuilder(64);
for (int i = 0; i < input.Length; i++)
{
hexString.Append(String.Format("{0:X2}", input[i]));
}
return hexString.ToString();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tjhis.Obilling.Station.OtherInterface.ENCRYPTION
{