C#.net和java实现国密SM3算法
作者:互联网
最近单位要对接浙江省智慧医保,2022年2月15日要上线,时间紧。
接口调用时,要在Header加入签名健值,其中签名算法是:国密SM3算法,所以笔记一下。
/// <summary> /// C#.net,SM3算法(使用自定义Hex密钥) /// </summary> /// <param name="data"></param> /// <param name="key"></param> /// <returns></returns> public static string ToSM3HexStr(string data, string key) { byte[] msg1 = Encoding.UTF8.GetBytes(data); byte[] key1 = Encoding.UTF8.GetBytes(key); Org.BouncyCastle.Crypto.Parameters.KeyParameter keyParameter = new Org.BouncyCastle.Crypto.Parameters.KeyParameter(key1); Org.BouncyCastle.Crypto.Digests.SM3Digest sm3 = new Org.BouncyCastle.Crypto.Digests.SM3Digest(); Org.BouncyCastle.Crypto.Macs.HMac mac = new Org.BouncyCastle.Crypto.Macs.HMac(sm3);//带密钥的杂凑算法 mac.Init(keyParameter); mac.BlockUpdate(msg1, 0, msg1.Length); byte[] result = new byte[mac.GetMacSize()]; mac.DoFinal(result, 0); return new UTF8Encoding().GetString(Org.BouncyCastle.Utilities.Encoders.Hex.Encode(result)); }
java国密SM3算法:
private final static String SECRET = "密匙XXXX"; public static String encrytSHA256(String content, String secret) { try { Security.addProvider(new BouncyCastleProvider()); SecretKey secretKey = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSm3"); Mac mac = Mac.getInstance(secretKey.getAlgorithm()); mac.init(secretKey); byte[] digest = mac.doFinal(content.getBytes("UTF-8")); return new HexBinaryAdapter().marshal(digest).toUpperCase(); } catch (Exception e) { throw new RuntimeCryptoException("加密异常"); } }
标签:java,C#,SM3,Crypto,mac,new,BouncyCastle,Org,byte 来源: https://www.cnblogs.com/yisheng163/p/15881785.html