public static bool VerifyPublickey(string pub_x, string pub_y, string curve = "") { pub_x = xTool.ConvertTool.RemoveSpace(pub_x); pub_y = xTool.ConvertTool.RemoveSpace(pub_y); ECDSABase ecdsa = new ECDSABase(new ECCurve(curve)); BigInteger x = BigInteger.Parse("00" + pub_x, System.Globalization.NumberStyles.AllowHexSpecifier); BigInteger y = BigInteger.Parse("00" + pub_y, System.Globalization.NumberStyles.AllowHexSpecifier); ECPoint p = new ECPoint(x, y); if (ECCMath.IsInfinityPoint(p)) { return(false); } if (!ECCMath.RangeBetween(x, BigInteger.One, ECCurve.p - 1)) { return(false); } if (!ECCMath.RangeBetween(y, BigInteger.One, ECCurve.p - 1)) { return(false); } if (!ECCMath.IsOnCurve(p)) { return(false); } ECPoint O = ECCMath.ScalarMult(ECCurve.n, p); if (!ECCMath.IsInfinityPoint(O)) { return(false); } //throw new Exception("O is NOT Infinity Point"); return(true); }
public static string Decrypt(string privateKey, string data) { privateKey = xTool.ConvertTool.RemoveSpace(privateKey); data = xTool.ConvertTool.RemoveSpace(data); if (data.Length % 2 != 0) { throw new Exception("Invalid Cipher"); } if (data.Length < 96 * 2) { throw new Exception("Invalid Cipher"); } ECDSABase ecdsa = new ECDSABase(new ECCurve("SM2")); string c1, c2, c3, t; c1 = data.Substring(0, 128); c3 = data.Substring(128, 64); c2 = data.Substring(128 + 64); t = ""; string x2, y2; x2 = y2 = ""; bool isZero = true; BigInteger x = BigInteger.Parse("00" + c1.Substring(0, 64), System.Globalization.NumberStyles.AllowHexSpecifier); BigInteger y = BigInteger.Parse("00" + c1.Substring(64), System.Globalization.NumberStyles.AllowHexSpecifier); ECPoint C1 = new ECPoint(x, y); if (!ECCMath.IsOnCurve(C1)) { throw new Exception("SM2 Decrypt Failed, C1 Not On Curve"); } ECPoint S = ECCMath.ScalarMult(ECCurve.h, C1); if (ECCMath.IsInfinityPoint(S)) { throw new Exception("S is Infinity Point"); } BigInteger prikey = BigInteger.Parse("00" + privateKey, System.Globalization.NumberStyles.AllowHexSpecifier); ECPoint point2 = ECCMath.ScalarMult(prikey, C1); x2 = Util.ToHexString(point2.X, ECCurve.BitLength); y2 = Util.ToHexString(point2.Y, ECCurve.BitLength); t = KDF(x2 + y2, c2.Length * 4); for (int i = 0; i < t.Length; i++) { if (t.Substring(i, 1) == "0") { continue; } else { isZero = false; break; } } if (isZero) { throw new Exception("t = 0"); } string plaindata = XOR(c2, t); string u = ALG.GuoMi.SM3(x2 + plaindata + y2); if (!u.Equals(c3, StringComparison.OrdinalIgnoreCase)) { throw new Exception("SM2 Decrypt Failed, u != C3"); } return(plaindata); }