summary refs log tree commit diff
path: root/crypto/src/crypto/signers/SM2Signer.cs
blob: 10244a7f3e637423cd9d2ef017c0c4a06d2b03b4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
using System;

using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Math.EC.Multiplier;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Encoders;

namespace Org.BouncyCastle.Crypto.Signers
{
    /// <summary>The SM2 Digital Signature algorithm.</summary>
    public class SM2Signer
        : ISigner
    {
        private enum State
        {
            Uninitialized = 0,
            Init          = 1,
            Data          = 2,
        }

        private readonly IDsaKCalculator kCalculator = new RandomDsaKCalculator();
        private readonly IDigest digest;
        private readonly IDsaEncoding encoding;

        private State m_state = State.Uninitialized;
        private ECDomainParameters ecParams;
        private ECPoint pubPoint;
        private ECKeyParameters ecKey;
        private byte[] z;

        public SM2Signer()
            : this(StandardDsaEncoding.Instance, new SM3Digest())
        {
        }

        public SM2Signer(IDigest digest)
            : this(StandardDsaEncoding.Instance, digest)
        {
        }

        public SM2Signer(IDsaEncoding encoding)
            : this(encoding, new SM3Digest())
        {
        }

        public SM2Signer(IDsaEncoding encoding, IDigest digest)
        {
            this.encoding = encoding;
            this.digest = digest;
        }

        public virtual string AlgorithmName
        {
            get { return "SM2Sign"; }
        }

        public virtual void Init(bool forSigning, ICipherParameters parameters)
        {
            ICipherParameters baseParam;
            byte[] userID;

            if (parameters is ParametersWithID withID)
            {
                baseParam = withID.Parameters;
                userID = withID.GetID();

                if (userID.Length >= 8192)
                    throw new ArgumentException("SM2 user ID must be less than 2^16 bits long");
            }
            else
            {
                baseParam = parameters;
                // the default value, string value is "1234567812345678"
                userID = Hex.DecodeStrict("31323334353637383132333435363738");
            }

            if (forSigning)
            {
                SecureRandom random = null;
                if (baseParam is ParametersWithRandom rParam)
                {
                    ecKey = (ECKeyParameters)rParam.Parameters;
                    ecParams = ecKey.Parameters;
                    random = rParam.Random;
                }
                else
                {
                    ecKey = (ECKeyParameters)baseParam;
                    ecParams = ecKey.Parameters;
                }
                if (!kCalculator.IsDeterministic)
                {
                    random = CryptoServicesRegistrar.GetSecureRandom(random);
                }
                kCalculator.Init(ecParams.N, random);
                pubPoint = CreateBasePointMultiplier().Multiply(ecParams.G, ((ECPrivateKeyParameters)ecKey).D).Normalize();
            }
            else
            {
                ecKey = (ECKeyParameters)baseParam;
                ecParams = ecKey.Parameters;
                pubPoint = ((ECPublicKeyParameters)ecKey).Q;
            }

            digest.Reset();
            z = GetZ(userID);
            m_state = State.Init;
        }

        public virtual void Update(byte b)
        {
            CheckData();

            digest.Update(b);
        }

        public virtual void BlockUpdate(byte[] input, int inOff, int inLen)
        {
            CheckData();

            digest.BlockUpdate(input, inOff, inLen);
        }

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
        public virtual void BlockUpdate(ReadOnlySpan<byte> input)
        {
            CheckData();

            digest.BlockUpdate(input);
        }
#endif

        public virtual int GetMaxSignatureSize() => encoding.GetMaxEncodingSize(ecParams.N);

        public virtual byte[] GenerateSignature()
        {
            CheckData();

            byte[] eHash = DigestUtilities.DoFinal(digest);

            BigInteger n = ecParams.N;
            BigInteger e = CalculateE(n, eHash);
            BigInteger d = ((ECPrivateKeyParameters)ecKey).D;

            BigInteger r, s;

            ECMultiplier basePointMultiplier = CreateBasePointMultiplier();

            // 5.2.1 Draft RFC:  SM2 Public Key Algorithms
            do // generate s
            {
                BigInteger k;
                do // generate r
                {
                    // A3
                    k = kCalculator.NextK();

                    // A4
                    ECPoint p = basePointMultiplier.Multiply(ecParams.G, k).Normalize();

                    // A5
                    r = e.Add(p.AffineXCoord.ToBigInteger()).Mod(n);
                }
                while (r.SignValue == 0 || r.Add(k).Equals(n));

                // A6
                BigInteger dPlus1ModN = BigIntegers.ModOddInverse(n, d.Add(BigIntegers.One));

                s = k.Subtract(r.Multiply(d)).Mod(n);
                s = dPlus1ModN.Multiply(s).Mod(n);
            }
            while (s.SignValue == 0);

            // A7
            try
            {
                return encoding.Encode(ecParams.N, r, s);
            }
            catch (Exception ex)
            {
                throw new CryptoException("unable to encode signature: " + ex.Message, ex);
            }
            finally
            {
                Reset();
            }
        }

        public virtual bool VerifySignature(byte[] signature)
        {
            CheckData();

            try
            {
                BigInteger[] rs = encoding.Decode(ecParams.N, signature);

                return VerifySignature(rs[0], rs[1]);
            }
            catch (Exception)
            {
            }
            finally
            {
                Reset();
            }

            return false;
        }

        public virtual void Reset()
        {
            switch (m_state)
            {
            case State.Init:
                return;
            case State.Data:
                break;
            default:
                throw new InvalidOperationException(AlgorithmName + " needs to be initialized");
            }

            digest.Reset();
            m_state = State.Init;
        }

        private bool VerifySignature(BigInteger r, BigInteger s)
        {
            BigInteger n = ecParams.N;

            // 5.3.1 Draft RFC:  SM2 Public Key Algorithms
            // B1
            if (r.CompareTo(BigInteger.One) < 0 || r.CompareTo(n) >= 0)
                return false;

            // B2
            if (s.CompareTo(BigInteger.One) < 0 || s.CompareTo(n) >= 0)
                return false;

            // B3
            byte[] eHash = DigestUtilities.DoFinal(digest);

            // B4
            BigInteger e = CalculateE(n, eHash);

            // B5
            BigInteger t = r.Add(s).Mod(n);
            if (t.SignValue == 0)
                return false;

            // B6
            ECPoint q = ((ECPublicKeyParameters)ecKey).Q;
            ECPoint x1y1 = ECAlgorithms.SumOfTwoMultiplies(ecParams.G, s, q, t).Normalize();
            if (x1y1.IsInfinity)
                return false;

            // B7
            BigInteger expectedR = e.Add(x1y1.AffineXCoord.ToBigInteger()).Mod(n);

            return expectedR.Equals(r);
        }

        private void CheckData()
        {
            switch (m_state)
            {
            case State.Init:
                break;
            case State.Data:
                return;
            default:
                throw new InvalidOperationException(AlgorithmName + " needs to be initialized");
            }

            digest.BlockUpdate(z, 0, z.Length);
            m_state = State.Data;
        }

        private byte[] GetZ(byte[] userID)
        {
            AddUserID(digest, userID);

            AddFieldElement(digest, ecParams.Curve.A);
            AddFieldElement(digest, ecParams.Curve.B);
            AddFieldElement(digest, ecParams.G.AffineXCoord);
            AddFieldElement(digest, ecParams.G.AffineYCoord);
            AddFieldElement(digest, pubPoint.AffineXCoord);
            AddFieldElement(digest, pubPoint.AffineYCoord);

            return DigestUtilities.DoFinal(digest);
        }

        private void AddUserID(IDigest digest, byte[] userID)
        {
            int len = userID.Length * 8;
            digest.Update((byte)(len >> 8));
            digest.Update((byte)len);
            digest.BlockUpdate(userID, 0, userID.Length);
        }

        private void AddFieldElement(IDigest digest, ECFieldElement v)
        {
            byte[] p = v.GetEncoded();
            digest.BlockUpdate(p, 0, p.Length);
        }

        protected virtual BigInteger CalculateE(BigInteger n, byte[] message)
        {
            // TODO Should hashes larger than the order be truncated as with ECDSA?
            return new BigInteger(1, message);
        }

        protected virtual ECMultiplier CreateBasePointMultiplier()
        {
            return new FixedPointCombMultiplier();
        }
    }
}