Add CKeyPair basic implementation & test
[NovacoinLibrary.git] / Novacoin / CKeyPair.cs
1 \feffusing System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6
7 using Org.BouncyCastle.Math;
8 using Org.BouncyCastle.Math.EC;
9
10 using Org.BouncyCastle.Crypto;
11 using Org.BouncyCastle.Crypto.Generators;
12 using Org.BouncyCastle.Crypto.Parameters;
13
14 using Org.BouncyCastle.Asn1.X9;
15 using Org.BouncyCastle.Security;
16 using Org.BouncyCastle.Asn1.Sec;
17
18 namespace Novacoin
19 {
20     public class CKeyPair
21     {
22         private BigInteger D;
23         private ECPoint Q;
24
25         private static X9ECParameters curve = SecNamedCurves.GetByName("secp256k1");
26         private static ECDomainParameters domain = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed());
27
28         /// <summary>
29         /// Initialize new CKeyPair instance with random secret.
30         /// </summary>
31         public CKeyPair()
32         {
33             ECKeyGenerationParameters genParams = new ECKeyGenerationParameters(domain, new SecureRandom());
34
35             ECKeyPairGenerator generator = new ECKeyPairGenerator("ECDSA");
36             generator.Init(genParams);
37             AsymmetricCipherKeyPair ecKeyPair = generator.GenerateKeyPair();
38
39             Q = ((ECPublicKeyParameters)ecKeyPair.Public).Q;
40             D = ((ECPrivateKeyParameters)ecKeyPair.Private).D;
41         }
42
43         /// <summary>
44         /// Init key pair using secret sequence of bytes
45         /// </summary>
46         /// <param name="secretBytes">Byte sequence</param>
47         public CKeyPair(IEnumerable<byte> secretBytes)
48         {
49             D = new BigInteger(secretBytes.ToArray());
50             Q = curve.G.Multiply(D);
51         }
52
53         /// <summary>
54         /// Secret part of key pair
55         /// </summary>
56         public IEnumerable<byte> Secret
57         {
58             get { return D.ToByteArray(); }
59         }
60
61         /// <summary>
62         /// Public part of key pair
63         /// </summary>
64         public IEnumerable<byte> Public
65         {
66             get { return Q.GetEncoded(); }
67         }
68
69         public override string ToString()
70         {
71             StringBuilder sb = new StringBuilder();
72
73             sb.AppendFormat("CKeyPair(Secret={0}, Public={1})", Interop.ToHex(Secret), Interop.ToHex(Public));
74
75             return sb.ToString();
76         }
77     }
78 }