summary refs log tree commit diff
path: root/crypto/test/src/test/GOST3410Test.cs
blob: db232c5a1febe1eee42713a33306b6835bcd06d3 (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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
using System;
using System.IO;

using NUnit.Framework;

using Org.BouncyCastle.Asn1.CryptoPro;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Test;
using Org.BouncyCastle.X509;

namespace Org.BouncyCastle.Tests
{
    [TestFixture]
    public class Gost3410Test
        : SimpleTest
    {
        private void ecGOST3410Test()
        {
            BigInteger r = new BigInteger("29700980915817952874371204983938256990422752107994319651632687982059210933395");
            BigInteger s = new BigInteger("46959264877825372965922731380059061821746083849389763294914877353246631700866");

            byte[] kData = new BigInteger("53854137677348463731403841147996619241504003434302020712960838528893196233395").ToByteArrayUnsigned();

            SecureRandom k = FixedSecureRandom.From(kData);

            BigInteger mod_p = new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564821041"); //p

            ECCurve curve = new FpCurve(
                mod_p, // p
                new BigInteger("7"), // a
                new BigInteger("43308876546767276905765904595650931995942111794451039583252968842033849580414")); // b

            ECDomainParameters spec = new ECDomainParameters(
                curve,
                curve.CreatePoint(
                    new BigInteger("2"),
                    new BigInteger("4018974056539037503335449422937059775635739389905545080690979365213431566280")),
                new BigInteger("57896044618658097711785492504343953927082934583725450622380973592137631069619")); // q

            ECPrivateKeyParameters sKey = new ECPrivateKeyParameters(
                "ECGOST3410",
                new BigInteger("55441196065363246126355624130324183196576709222340016572108097750006097525544"), // d
                spec);

            ECPublicKeyParameters vKey = new ECPublicKeyParameters(
                "ECGOST3410",
                curve.CreatePoint(
                    new BigInteger("57520216126176808443631405023338071176630104906313632182896741342206604859403"),
                    new BigInteger("17614944419213781543809391949654080031942662045363639260709847859438286763994")),
                spec);

            ISigner sgr = SignerUtilities.GetSigner("ECGOST3410");

            sgr.Init(true, new ParametersWithRandom(sKey, k));

            byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };

            sgr.BlockUpdate(message, 0, message.Length);

            byte[] sigBytes = sgr.GenerateSignature();

            sgr.Init(false, vKey);

            sgr.BlockUpdate(message, 0, message.Length);

            if (!sgr.VerifySignature(sigBytes))
            {
                Fail("ECGOST3410 verification failed");
            }

            BigInteger[] sig = decode(sigBytes);

            if (!r.Equals(sig[0]))
            {
                Fail(
                    ": r component wrong." + SimpleTest.NewLine
                    + " expecting: " + r + SimpleTest.NewLine
                    + " got      : " + sig[0]);
            }

            if (!s.Equals(sig[1]))
            {
                Fail(
                    ": s component wrong." + SimpleTest.NewLine
                    + " expecting: " + s + SimpleTest.NewLine
                    + " got      : " + sig[1]);
            }
        }

        private void generationTest()
        {
            byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
            ISigner s = SignerUtilities.GetSigner("GOST3410");

            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("GOST3410");
            g.Init(
                new Gost3410KeyGenerationParameters(
                    new SecureRandom(),
                    CryptoProObjectIdentifiers.GostR3410x94CryptoProA));

            AsymmetricCipherKeyPair p = g.GenerateKeyPair();

            AsymmetricKeyParameter sKey = p.Private;
            AsymmetricKeyParameter vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("GOST3410");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("GOST3410 verification failed");
            }

            //
            // default initialisation test
            //
            s = SignerUtilities.GetSigner("GOST3410");
            g = GeneratorUtilities.GetKeyPairGenerator("GOST3410");

            // TODO This is supposed to be a 'default initialisation' test, but don't have a factory
            // These values are defaults from JCE provider
            g.Init(
                new Gost3410KeyGenerationParameters(
                    new SecureRandom(),
                    CryptoProObjectIdentifiers.GostR3410x94CryptoProA));

            p = g.GenerateKeyPair();

            sKey = p.Private;
            vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("GOST3410");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("GOST3410 verification failed");
            }

            //
            // encoded test
            //
            //KeyFactory f = KeyFactory.getInstance("GOST3410");
            //X509EncodedKeySpec  x509s = new X509EncodedKeySpec(vKey.GetEncoded());
            //Gost3410PublicKeyParameters k1 = (Gost3410PublicKeyParameters)f.generatePublic(x509s);
            byte[] vKeyEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(vKey).GetDerEncoded();
            Gost3410PublicKeyParameters k1 = (Gost3410PublicKeyParameters)
                PublicKeyFactory.CreateKey(vKeyEnc);

            if (!k1.Y.Equals(((Gost3410PublicKeyParameters)vKey).Y))
            {
                Fail("public number not decoded properly");
            }

            //PKCS8EncodedKeySpec  pkcs8 = new PKCS8EncodedKeySpec(sKey.GetEncoded());
            //Gost3410PrivateKeyParameters k2 = (Gost3410PrivateKeyParameters)f.generatePrivate(pkcs8);
            byte[] sKeyEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(sKey).GetDerEncoded();
            Gost3410PrivateKeyParameters k2 = (Gost3410PrivateKeyParameters)
                PrivateKeyFactory.CreateKey(sKeyEnc);

            if (!k2.X.Equals(((Gost3410PrivateKeyParameters)sKey).X))
            {
                Fail("private number not decoded properly");
            }

            //
            // ECGOST3410 generation test
            //
            s = SignerUtilities.GetSigner("ECGOST3410");
            g = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410");

            BigInteger mod_p = new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564821041"); //p

            ECCurve curve = new FpCurve(
                mod_p, // p
                new BigInteger("7"), // a
                new BigInteger("43308876546767276905765904595650931995942111794451039583252968842033849580414")); // b

            ECDomainParameters ecSpec = new ECDomainParameters(
                curve,
                curve.CreatePoint(
                    new BigInteger("2"),
                    new BigInteger("4018974056539037503335449422937059775635739389905545080690979365213431566280")),
                new BigInteger("57896044618658097711785492504343953927082934583725450622380973592137631069619")); // q

            g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));

            p = g.GenerateKeyPair();

            sKey = p.Private;
            vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("ECGOST3410");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("ECGOST3410 verification failed");
            }
        }

        private void keyStoreTest(
            AsymmetricKeyParameter	sKey,
            AsymmetricKeyParameter	vKey)
//	        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, SignatureException, InvalidKeyException, UnrecoverableKeyException
        {
            //
            // keystore test
            //
//			KeyStore ks = KeyStore.GetInstance("JKS");
//			ks.Load(null, null);
            Pkcs12StoreBuilder ksBuilder = new Pkcs12StoreBuilder();
            Pkcs12Store ks = ksBuilder.Build();
    
            //
            // create the certificate - version 3
            //
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    
            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name("CN=Test"));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name("CN=Test"));
            certGen.SetPublicKey(vKey);
            certGen.SetSignatureAlgorithm("GOST3411withGOST3410");
    
            X509Certificate cert = certGen.Generate(sKey);
            X509CertificateEntry certEntry = new X509CertificateEntry(cert);

//	        ks.SetKeyEntry("gost", sKey, "gost".ToCharArray(), new X509Certificate[] { cert });
            ks.SetKeyEntry("gost", new AsymmetricKeyEntry(sKey), new X509CertificateEntry[] { certEntry });
    
            MemoryStream bOut = new MemoryStream();
    
            ks.Save(bOut, "gost".ToCharArray(), new SecureRandom());
    
//	        ks = KeyStore.getInstance("JKS");
            ks = ksBuilder.Build();

            ks.Load(new MemoryStream(bOut.ToArray(), false), "gost".ToCharArray());

//	        AsymmetricKeyParameter gKey = (AsymmetricKeyParameter)ks.GetKey("gost", "gost".ToCharArray());
//	        AsymmetricKeyEntry gKeyEntry = (AsymmetricKeyEntry)
                ks.GetKey("gost");
        }
        
        private void parametersTest()
        {
//	        AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("GOST3410");
//	        a.init(512, random);
//	        AlgorithmParameters params = a.generateParameters();
//
//	        byte[] encodeParams = params.getEncoded();
//
//	        AlgorithmParameters a2 = AlgorithmParameters.getInstance("GOST3410");
//	        a2.init(encodeParams);
//
//	        // a and a2 should be equivalent!
//	        byte[] encodeParams_2 = a2.getEncoded();
//
//	        if (!arrayEquals(encodeParams, encodeParams_2))
//	        {
//	            Fail("encode/decode parameters failed");
//	        }

//			GOST3410ParameterSpec gost3410P = new GOST3410ParameterSpec(
//				CryptoProObjectIdentifiers.gostR3410_94_CryptoPro_B.getId());
//			g.initialize(gost3410P, new SecureRandom());
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("GOST3410");
            g.Init(
                new Gost3410KeyGenerationParameters(
                    new SecureRandom(),
                    CryptoProObjectIdentifiers.GostR3410x94CryptoProB));

            AsymmetricCipherKeyPair p = g.GenerateKeyPair();

            AsymmetricKeyParameter sKey = p.Private;
            AsymmetricKeyParameter vKey = p.Public;

            ISigner s = SignerUtilities.GetSigner("GOST3410");
            byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("GOST3410");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("GOST3410 verification failed");
            }

            keyStoreTest(sKey, vKey);
        }

        private BigInteger[] decode(
            byte[]  encoding)
        {
            byte[] r = new byte[32];
            byte[] s = new byte[32];

            Array.Copy(encoding, 0, s, 0, 32);
            Array.Copy(encoding, 32, r, 0, 32);

            BigInteger[] sig = new BigInteger[2];

            sig[0] = new BigInteger(1, r);
            sig[1] = new BigInteger(1, s);

            return sig;
        }

        public override string Name
        {
            get { return "GOST3410/ECGOST3410"; }
        }

        public override void PerformTest()
        {
            ecGOST3410Test();
            generationTest();
            parametersTest();
        }

        public static void Main(
            string[]	args)
        {
            RunTest(new Gost3410Test());
        }

        [Test]
        public void TestFunction()
        {
            string resultText = Perform().ToString();

            Assert.AreEqual(Name + ": Okay", resultText);
        }
    }
}