public static ECKeyPair FromPrivateKey(byte[] privateKey) { if (privateKey == null || privateKey.Length != 32) { throw new InvalidPrivateKeyException( $"Private key has to have length of 32. Current length is {privateKey?.Length}."); } try { Lock.AcquireWriterLock(Timeout.Infinite); var secp256K1PubKey = new byte[64]; if (!Secp256K1.PublicKeyCreate(secp256K1PubKey, privateKey)) { throw new InvalidPrivateKeyException("Create public key failed."); } var pubKey = new byte[Secp256k1.SERIALIZED_UNCOMPRESSED_PUBKEY_LENGTH]; if (!Secp256K1.PublicKeySerialize(pubKey, secp256K1PubKey)) { throw new PublicKeyOperationException("Serialize public key failed."); } return(new ECKeyPair(privateKey, pubKey)); } finally { Lock.ReleaseWriterLock(); } }
static void Main(string[] args) { // Create a secp256k1 context (ensure disposal to prevent unmanaged memory leaks). using (var secp256k1 = new Secp256k1()) { // Generate a private key. var privateKey = new byte[32]; var rnd = System.Security.Cryptography.RandomNumberGenerator.Create(); do { rnd.GetBytes(privateKey); }while (!secp256k1.SecretKeyVerify(privateKey)); // Create public key from private key. var publicKey = new byte[64]; Debug.Assert(secp256k1.PublicKeyCreate(publicKey, privateKey)); // Sign a message hash. var messageBytes = Encoding.UTF8.GetBytes("Hello world."); var messageHash = System.Security.Cryptography.SHA256.Create().ComputeHash(messageBytes); var signature = new byte[64]; Debug.Assert(secp256k1.Sign(signature, messageHash, privateKey)); // Serialize a DER signature from ECDSA signature byte[] signatureDer = new byte[Secp256k1.SERIALIZED_DER_SIGNATURE_MAX_SIZE]; int outL = 0; Debug.Assert(secp256k1.SignatureSerializeDer(signatureDer, signature, out outL)); Array.Resize(ref signatureDer, outL); // Verify message hash. Debug.Assert(secp256k1.Verify(signature, messageHash, publicKey)); } }
static void Main(string[] args) { // Create a secp256k1 context (ensure disposal to prevent unmanaged memory leaks). using (var secp256k1 = new Secp256k1()) { // Generate a private key. var privateKey = new byte[32]; var rnd = System.Security.Cryptography.RandomNumberGenerator.Create(); do { rnd.GetBytes(privateKey); }while (!secp256k1.SecretKeyVerify(privateKey)); // Create public key from private key. var publicKey = new byte[64]; Debug.Assert(secp256k1.PublicKeyCreate(publicKey, privateKey)); // Sign a message hash. var messageBytes = Encoding.UTF8.GetBytes("Hello world."); var messageHash = System.Security.Cryptography.SHA256.Create().ComputeHash(messageBytes); var signature = new byte[64]; Debug.Assert(secp256k1.Sign(signature, messageHash, privateKey)); // Verify message hash. Debug.Assert(secp256k1.Verify(signature, messageHash, publicKey)); } }
public void Sign_With_PubKey_From_Commitment() { using (var secp256k1 = new Secp256k1()) using (var pedersen = new Pedersen()) { string ToHex(byte[] data) { return(BitConverter.ToString(data).Replace("-", string.Empty)); } var blinding = secp256k1.GetSecretKey(); var commit = pedersen.Commit(0, blinding); var msg = "Message for signing"; var msgBytes = Encoding.UTF8.GetBytes(msg); var msgHash = System.Security.Cryptography.SHA256.Create().ComputeHash(msgBytes); var sig = secp256k1.Sign(msgHash, blinding); var pubKey = pedersen.ToPublicKey(commit); Assert.True(secp256k1.Verify(sig, msgHash, pubKey)); var actualPubKey = secp256k1.PublicKeyCreate(blinding); Assert.Equal(ToHex(pubKey), ToHex(actualPubKey)); } }
static void TestToPublicKey() { using (var secp256k1 = new Secp256k1()) using (var pedersen = new Pedersen()) { var blinding = secp256k1.GetSecretKey(); var commitPos = pedersen.Commit(0, blinding); var commitNeg = pedersen.Commit(0, blinding); var blindSum = pedersen.BlindSum(new List <byte[]> { blinding, blinding }, new List <byte[]> { }); var commitSum = pedersen.CommitSum(new List <byte[]> { commitPos }, new List <byte[]> { commitNeg }); var msg = "Message for signing"; var msgBytes = Encoding.UTF8.GetBytes(msg); var msgHash = System.Security.Cryptography.SHA256.Create().ComputeHash(msgBytes); var sig = secp256k1.Sign(msgHash, blinding); var pubKey = pedersen.ToPublicKey(commitSum); var verified1 = secp256k1.Verify(sig, msgHash, pubKey); var pub = secp256k1.PublicKeyCreate(blinding); } }
private static byte[] _PrivToPubKey(byte[] privKey) { using (var secp256K1 = new Secp256k1()) { var pubKey = new byte[64]; secp256K1.PublicKeyCreate(pubKey, privKey); return(pubKey); } }
public byte[] ComputePublicKey(byte[] privateKey, bool compress = true) { if (privateKey.Length != 32) { throw new ArgumentException(nameof(privateKey)); } var publicKey = new byte[64]; var result = new byte[33]; if (!Secp256K1.PublicKeyCreate(publicKey, privateKey)) { throw new ArgumentException("Bad private key"); } if (!Secp256K1.PublicKeySerialize(result, publicKey, Flags.SECP256K1_EC_COMPRESSED)) { throw new ArgumentException("Bad public key"); } return(result); }
public static byte[] GetPublicKey(byte[] privateKey) { using (var secp256k1 = new Secp256k1()) { var publicKey = new byte[64]; secp256k1.PublicKeyCreate(publicKey, privateKey); return(publicKey); } }
public void SetupSign() { signature = new byte[64]; SetupGenerateKey(); Span <byte> sk = new byte[64]; sk = privateKey; Span <byte> pk = new byte[64]; secp256k1.PublicKeyCreate(pk, sk); publicKey = pk.ToArray(); Span <byte> m = new byte[32]; Random.NextBytes(m); message = m.ToArray(); }
public static KeyPair GenerateKeyPair(Secp256k1 secp256k1) { var privateKey = GeneratePrivateKey(secp256k1); byte[] publicKey = new byte[64]; if (!secp256k1.PublicKeyCreate(publicKey, privateKey)) { throw new Exception("Public key creation failed"); } return(new KeyPair { PrivateKey = Convert.ToBase64String(privateKey), PublicKey = Convert.ToBase64String(publicKey) }); }
public static ECKeyPair FromPrivateKey(byte[] privateKey) { if (privateKey == null || privateKey.Length != 32) { throw new ArgumentException("Private key has to have length of 32."); } try { Lock.AcquireWriterLock(Timeout.Infinite); var secp256K1PubKey = new byte[64]; Secp256K1.PublicKeyCreate(secp256K1PubKey, privateKey); var pubKey = new byte[Secp256k1.SERIALIZED_UNCOMPRESSED_PUBKEY_LENGTH]; Secp256K1.PublicKeySerialize(pubKey, secp256K1PubKey); return(new ECKeyPair(privateKey, pubKey)); } finally { Lock.ReleaseWriterLock(); } }
//private int SerializedPublicKeyLength => IsCompressed ? Secp256k1.SERIALIZED_COMPRESSED_PUBKEY_LENGTH : Secp256k1.SERIALIZED_UNCOMPRESSED_PUBKEY_LENGTH; public static PublicKey CreatePublicKey(this PrivateKey privateKey) { Trace.Assert(privateKey.IsValid); var pubKeySecp256k1 = new byte[Secp256k1.PUBKEY_LENGTH]; var ok = Library.PublicKeyCreate(pubKeySecp256k1, privateKey.Bytes); Trace.Assert(ok); var pubKey = new PublicKey(privateKey.IsCompressed); LazySecpLibrary.Value.PublicKeySerialize((ByteSpan)pubKey, pubKeySecp256k1, privateKey.IsCompressed ? Flags.SECP256K1_EC_COMPRESSED : Flags.SECP256K1_EC_UNCOMPRESSED); Trace.Assert(pubKey.IsValid); return(pubKey); }
public string GetPublicKey(string privateKey) { var secp256k1 = new Secp256k1(); var publicKey = new byte[64]; if (secp256k1.PublicKeyCreate(publicKey, HexStringToByteArray(privateKey))) { return(ByteArrayToHexString(publicKey)); } else { return(null); } }
public void CalculateSharedSecretWithSelfPubKey() { using (var secp256k1 = new Secp256k1()) { Span <byte> privateKey = "90cc2eb9f4ac1562546c9899b5a68fc98a8add85a606abd506058e75ce583f49".HexToBytes(); Span <byte> publicKey = stackalloc byte[64]; Span <byte> sharedSecret = stackalloc byte[32]; secp256k1.PublicKeyCreate(publicKey, privateKey); secp256k1.CalculateSharedSecret(sharedSecret, publicKey, privateKey); Assert.Equal(32, sharedSecret.Length); Assert.Equal("3e9a315412415ab738658e7f2119c434e7c2112862315d0af756d03d923874ae", sharedSecret.ToHexString()); } }
public void CalculateSharedSecretWithAnotherPubKey() { using (var secp256k1 = new Secp256k1()) { Span <byte> privateKey = "90cc2eb9f4ac1562546c9899b5a68fc98a8add85a606abd506058e75ce583f49".HexToBytes(); Span <byte> privateKey2 = "e815acba8fcf085a0b4141060c13b8017a08da37f2eb1d6a5416adbb621560ef".HexToBytes(); Span <byte> publicKey = stackalloc byte[64]; Span <byte> sharedSecret = stackalloc byte[32]; secp256k1.PublicKeyCreate(publicKey, privateKey2); secp256k1.CalculateSharedSecret(sharedSecret, publicKey, privateKey); Assert.Equal(32, sharedSecret.Length); Assert.Equal("8fd6cc22898c5bddf1b6e596f131cea5f09ef2122f57852a90137959101bace1", sharedSecret.ToHexString()); } }
public void KeyPairGeneration() { var secp256k1 = new Secp256k1(); var rnd = System.Security.Cryptography.RandomNumberGenerator.Create(); Span <byte> privateKey = new byte[32]; do { rnd.GetBytes(privateKey.ToArray()); }while (!secp256k1.SecretKeyVerify(privateKey)); Span <byte> publicKey = new byte[64]; if (!secp256k1.PublicKeyCreate(publicKey, privateKey)) { throw new Exception("Public key creation failed"); } }
public static Dictionary <byte[], byte[]> GenKeyPairs(int count) { var keyPairs = new Dictionary <byte[], byte[]>(); for (var i = 0; i < count; i++) { var privateKey = new byte[32]; var rnd = RandomNumberGenerator.Create(); rnd.GetBytes(privateKey); var publicKey = new byte[64]; // using (var secp256K1 = new Secp256k1()) lock (secp256K1) { Debug.Assert(secp256K1.PublicKeyCreate(publicKey, privateKey)); } keyPairs.Add(publicKey, privateKey); } return(keyPairs); }
public void SignTransaction(string secretKey) { var secp256k1 = new Secp256k1(); Span <byte> publicKey = new byte[64]; secp256k1.PublicKeyCreate(publicKey, secretKey.ToBytes()); //As only wallet owner can sign it's own transactions so //Public key genrated from secretKey must be equal to sender's wallet address (i.e. FromAddress) if (!publicKey.ToHex().Equals(FromAddress)) { throw new Exception("You cannot sign transactions for other wallets."); } var txHash = CalculateHash(); Span <byte> signature = new byte[64]; secp256k1.Sign(signature, txHash, secretKey.ToBytes()); Signature = signature.ToArray(); }
//Ignore this function as this is just to create Public Private key pairs for testing public static void GenerateKeys() { using (var secp256k1 = new Secp256k1()) { // privatekey= "105c301c92f5d956ad577105e71aba4d29cf7af04cd47c648244dd8ad677381f" // publickey = "7a89dec4cc7e0964ed4c5e517f1cfee7e4f145e8500f55fe0317f97e71b7ba5219a4215b1885ac547da87bd0155d02c9bbe0501d0670a4f481df2b42f2130c02" // Generate a private key. var privateKey = new byte[32]; var rnd = System.Security.Cryptography.RandomNumberGenerator.Create(); do { rnd.GetBytes(privateKey); }while (!secp256k1.SecretKeyVerify(privateKey)); var prk = ToHex(privateKey); // Create public key from private key. var publicKey = new byte[64]; Debug.Assert(secp256k1.PublicKeyCreate(publicKey, privateKey)); var pbk = ToHex(publicKey); // Sign a message hash. var messageBytes = Encoding.UTF8.GetBytes("Hello world."); var messageHash = System.Security.Cryptography.SHA256.Create().ComputeHash(messageBytes); var signature = new byte[64]; Debug.Assert(secp256k1.Sign(signature, messageHash, privateKey)); // Serialize a DER signature from ECDSA signature byte[] signatureDer = new byte[Secp256k1.SERIALIZED_DER_SIGNATURE_MAX_SIZE]; int outL = 0; Debug.Assert(secp256k1.SignatureSerializeDer(signatureDer, signature, out outL)); Array.Resize(ref signatureDer, outL); // Verify message hash. Debug.Assert(secp256k1.Verify(signature, messageHash, publicKey)); } }
public static void CloudKeygen(int n, int f, IEnumerable <string> ips, ushort basePort, ushort target, ulong chainId, ulong cycleDuration, ulong validatorsCount, string networkName, string feedAddress, string feedBalance, string stakeAmount, IEnumerable <ulong> hardforks) { if (n <= 3 * f) { throw new Exception("N must be >= 3 * F + 1"); } var tpkeKeyGen = new Crypto.TPKE.TrustedKeyGen(n, f); var tpkePubKey = tpkeKeyGen.GetPubKey(); var sigKeyGen = new Crypto.ThresholdSignature.TrustedKeyGen(n, f); var privShares = sigKeyGen.GetPrivateShares().ToArray(); var pubShares = sigKeyGen.GetPrivateShares() .Select(s => s.GetPublicKeyShare()) .Select(s => s.ToHex()) .ToArray(); var ecdsaPrivateKeys = new string[n]; var ecdsaPublicKeys = new string[n]; var addresses = new string[n]; var crypto = CryptoProvider.GetCrypto(); for (var i = 0; i < n; ++i) { ecdsaPrivateKeys[i] = crypto.GenerateRandomBytes(32).ToHex(false); ecdsaPublicKeys[i] = crypto.ComputePublicKey(ecdsaPrivateKeys[i].HexToBytes(), true).ToHex(false); addresses[i] = ecdsaPrivateKeys[i].HexToBytes().ToPrivateKey().GetPublicKey().GetAddress().ToHex(); } var hubPublicKeys = new string[n]; var serializedHubPrivateKeys = new string[n]; for (var i = 0; i < n; ++i) { (serializedHubPrivateKeys[i], hubPublicKeys[i]) = PrivateWallet.GenerateHubKey(); } var bootstraps = ips .Zip(hubPublicKeys, (ip, id) => $"{id}@{ip}") .Select((x, i) => $"{x}:{41011 + i}") .ToArray(); var peers = ecdsaPublicKeys.ToArray(); for (var i = 0; i < n; ++i) { var net = new NetworkConfig { Peers = peers, MaxPeers = 100, ForceIPv6 = false, BootstrapAddresses = bootstraps, HubLogLevel = "Trace", HubMetricsPort = basePort + 2, NetworkName = networkName, ChainId = (int)chainId, CycleDuration = cycleDuration, ValidatorsCount = validatorsCount, }; var genesis = new GenesisConfig(tpkePubKey.ToHex(), "5.000000000000000000", "0.000000100000000000") { Balances = new Dictionary <string, string> { { feedAddress, feedBalance } }, Validators = Enumerable.Range(0, n).Select(j => new ValidatorInfo( ecdsaPublicKeys[j], pubShares[j], feedAddress, stakeAmount )).ToList() }; for (var j = 0; j < n; ++j) { genesis.Balances[addresses[j]] = "100"; } var secp256K1 = new Secp256k1(); var privateKey = new byte[32]; var rnd = System.Security.Cryptography.RandomNumberGenerator.Create(); do { rnd.GetBytes(privateKey); }while (!secp256K1.SecretKeyVerify(privateKey)); var privateKeyHex = privateKey.ToHex(); var publicKey = new byte[64]; Debug.Assert(secp256K1.PublicKeyCreate(publicKey, privateKey)); var publicKeyHex = publicKey.ToHex(); System.Console.WriteLine($"Loop {i + 1:D2}: private key [{privateKeyHex}] associated with public key [{publicKeyHex}]"); var rpc = new RpcConfig { Hosts = new[] { "+" }, Port = basePort, MetricsPort = (ushort)(basePort + 1), // ApiKey = "0x2e917846fe7487a4ea3a765473a3fc9b2d9227a4d312bc77fb9de357cf73d7e52b771d537394336e9eb2cb4838138f668f4bd7d8cf7e04d9242a42c71b99f166", ApiKey = publicKeyHex }; var walletPath = "wallet.json"; var vault = new VaultConfig { Path = walletPath, Password = getRandomPassword() }; var storage = new StorageConfig { Path = "ChainLachain", Provider = "RocksDB", }; var blockchain = new BlockchainConfig { TargetBlockTime = target, }; List <ulong> hardforkHeights = hardforks.ToList(); var hardfork = new HardforkConfig { Hardfork_1 = hardforkHeights[0], Hardfork_2 = hardforkHeights[1], Hardfork_3 = hardforkHeights[2], Hardfork_4 = hardforkHeights[3], }; var version = new VersionConfig { Version = 2 }; var blockHeight = new CacheOptions { SizeLimit = 100 }; var cache = new CacheConfig { BlockHeight = blockHeight }; var config = new Config(net, genesis, rpc, vault, storage, blockchain, hardfork, version, cache); File.WriteAllText($"config{i + 1:D2}.json", JsonConvert.SerializeObject(config, Formatting.Indented)); GenWallet( $"wallet{i + 1:D2}.json", ecdsaPrivateKeys[i], serializedHubPrivateKeys[i], tpkeKeyGen.GetPrivKey(i).ToHex(), privShares[i].ToHex(), vault.Password ); } var tpkePrivKeys = string.Join( ", ", Enumerable.Range(0, n) .Select(idx => tpkeKeyGen.GetPrivKey(idx)) .Select(x => $"\"{x.ToHex()}\"")); var tsKeys = string.Join( ", ", sigKeyGen.GetPrivateShares() .Select(x => $"(\"{x.GetPublicKeyShare().ToHex()}\", \"{x.ToHex()}\")") ); System.Console.WriteLine( $"{n}: " + "{" + " \"tpke\": (" + $" \"{tpkePubKey.ToHex()}\"," + $" [{tpkePrivKeys}]" + " )," + $" \"ts\": [{tsKeys}]," + "}"); System.Console.WriteLine( string.Join(", ", ecdsaPrivateKeys.Zip(ecdsaPublicKeys).Zip(addresses) .Select(t => $"(\"{t.First.Second}\", \"{t.First.First}\", \"{t.Second}\")")) ); }
public static PublicKey FromPrivateKey(byte[] secretKey) { return(new PublicKey(Secp256k1.PublicKeyCreate(secretKey))); }