public virtual void Encrypt(byte[] data) { sm3c3.BlockUpdate(data, 0, data.Length); for (int i = 0; i < data.Length; i++) { if (keyOff == key.Length) { NextKey(); } data[i] ^= key[keyOff++]; } }
private void Reset() { sm3keybase = new SM3Digest(); //实例化一个SM3Digest的对象sm3keybase sm3c3 = new SM3Digest(); //实例化一个SM3Digest的对象sm3c3 byte[] p; p = p2.X.ToBigInteger().ToByteArray(); //数据类型转化为比特串。 sm3keybase.BlockUpdate(p, 0, p.Length); //调用密码杂凑BlockUpdate方法 sm3c3.BlockUpdate(p, 0, p.Length); //调用密码杂凑BlockUpdate方法 p = p2.Y.ToBigInteger().ToByteArray(); //数据类型转化为比特串 sm3keybase.BlockUpdate(p, 0, p.Length); //调用密码杂凑BlockUpdate方法 ct = 1; NextKey();//调用NextKey方法 }
//[STAThread] #region ²âÊÔ²¢´òÓ¡¸÷¸ö²ÎÊý public static void Main() { byte[] msg1 = Encoding.Default.GetBytes("abc"); byte[] msg2 = Encoding.Default.GetBytes("abcd"); byte[] md = new byte[32]; SM3Digest sm3 = new SM3Digest(); // abcBlockUpdate sm3.BlockUpdate(msg1, 0, msg1.Length); sm3.DoFinal(md, 0); System.String s = new UTF8Encoding().GetString(Hex.Encode(md)); System.Console.Out.WriteLine(s); // abc*16 for (int i = 0; i < 16; i++) { sm3.BlockUpdate(msg2, 0, msg2.Length); } sm3.DoFinal(md, 0); System.String s1 = new UTF8Encoding().GetString(Hex.Encode(md)); System.Console.Out.WriteLine(s1); // abc + abc*15 SM3Digest sm3_ = new SM3Digest(); sm3_.BlockUpdate(msg2, 0, msg2.Length); sm3 = new SM3Digest(sm3_); for (int i = 1; i < 16; i++) { sm3.BlockUpdate(msg2, 0, msg2.Length); } sm3.DoFinal(md, 0); System.String s2 = new UTF8Encoding().GetString(Hex.Encode(md)); System.Console.Out.WriteLine(s2); Console.ReadLine(); /* * 66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0 * debe9ff92275b8a138604889c18e5a4d6fdb70e5387e5765293dcba39c0c5732 * debe9ff92275b8a138604889c18e5a4d6fdb70e5387e5765293dcba39c0c5732 */ }
/*M2签名同样也是需要先摘要原文数据,即先使用SM3密码杂凑算法计算出32byte摘要。SM3需要摘要签名方ID(默认1234567812345678)、 * 曲线参数a,b,Gx,Gy、共钥坐标(x,y)计算出Z值,然后再杂凑原文得出摘要数据。这个地方要注意曲线参数和坐标点都是32byte, * 在转换为BigInteger大数计算转成字节流时要去掉空补位,否则可能会出现摘要计算不正确的问题:*/ /// <summary> /// 计算Z值 /// </summary> /// <param name="userId">签名方ID</param> /// <param name="userKey">曲线的各个参数</param> /// <returns></returns> public virtual byte[] Sm2GetZ(byte[] userId, ECPoint userKey) { SM3Digest sm3 = new SM3Digest(); byte[] p; // userId length int len = userId.Length * 8;//求userId的长度 sm3.Update((byte)(len >> 8 & 0x00ff)); sm3.Update((byte)(len & 0x00ff)); // userId sm3.BlockUpdate(userId, 0, userId.Length); // a,b p = ecc_a.ToByteArray(); sm3.BlockUpdate(p, 0, p.Length); p = ecc_b.ToByteArray(); sm3.BlockUpdate(p, 0, p.Length); // gx,gy p = ecc_gx.ToByteArray(); sm3.BlockUpdate(p, 0, p.Length); p = ecc_gy.ToByteArray(); sm3.BlockUpdate(p, 0, p.Length); // x,y p = userKey.X.ToBigInteger().ToByteArray(); sm3.BlockUpdate(p, 0, p.Length); p = userKey.Y.ToBigInteger().ToByteArray(); sm3.BlockUpdate(p, 0, p.Length); // Z byte[] md = new byte[sm3.GetDigestSize()]; sm3.DoFinal(md, 0); return(md); }