public void DecodeWifTest() { //https://en.bitcoin.it/wiki/Wallet_import_format Org.BouncyCastle.Math.BigInteger actual = BitcoinHelper.DecodeWif("5HueCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbTLvyTJ"); //Assert.IsTrue(actual.ToString() == "0C28FCA386C7A227600B2FE50B7CAE11EC86D3BF1FBE471BE89827E19D72AA1D"); Assert.IsTrue(actual.ToString() == "5500171714335001507730457227127633683517613019341760098818554179534751705629"); }
public String SendBitcoins(String encryptedPrivateKey, String password, String destinationAddress, Decimal amount) { if (!String.IsNullOrEmpty(encryptedPrivateKey) && !String.IsNullOrEmpty(password)) { Byte[] privateKeyAsBytes = Convert.FromBase64String(encryptedPrivateKey); Byte[] passwordAsBytes = Convert.FromBase64String(password); String decryptedWIFPrivateKey = DC.Common.Security.DecryptStringFromBytes_Aes(privateKeyAsBytes, passwordAsBytes); Org.BouncyCastle.Math.BigInteger key = DC.Common.BitcoinHelper.DecodeWif(decryptedWIFPrivateKey); return(SignAndTransfer(key.ToString(), destinationAddress, amount)); } else { throw new ArgumentException("Private Key or password cannot be null"); } }
/// <summary> /// Returns the public based on the passed private key and password /// </summary> /// <param name="privateKey"></param> /// <param name="password"></param> /// <returns>Empty string if unresolvable, otherwise public key</returns> public string ResolvePrivateKey(string encryptedPrivateKey, string password) { if (!String.IsNullOrEmpty(encryptedPrivateKey) && !String.IsNullOrEmpty(password)) { Byte[] privateKeyAsBytes = Convert.FromBase64String(encryptedPrivateKey.Trim()); Byte[] passwordAsBytes = Convert.FromBase64String(password.Trim()); String decryptedWIFPrivateKey = DC.Common.Security.DecryptStringFromBytes_Aes(privateKeyAsBytes, passwordAsBytes); Org.BouncyCastle.Math.BigInteger key = DC.Common.BitcoinHelper.DecodeWif(decryptedWIFPrivateKey); var sourceAddress = new Common.Models.Address(key.ToString()); return(sourceAddress.BTCAddress); } else { throw new ArgumentException("Private Key or password cannot be null"); } }
/// <summary> /// Check is the key is valid see RFC 2631, Section 2.1.5, http://www.ietf.org/rfc/rfc2631.txt /// </summary> public static bool IsValidPublicKey(Org.BouncyCastle.Math.BigInteger y, Org.BouncyCastle.Math.BigInteger p, Org.BouncyCastle.Math.BigInteger q) { Org.BouncyCastle.Math.BigInteger bn; // y must lie in [2,p-1] // check y < 2 then failed bn = new Org.BouncyCastle.Math.BigInteger("2"); if (y.CompareTo(bn) < 0) { LibRTMPLogger.Log(LibRTMPLogLevel.Warning, "[CDR.LibRTMP.RTMPHelper.IsValidPublicKey] DH public key must be at least 2"); return(false); } // y must lie in [2,p-1] bn = new Org.BouncyCastle.Math.BigInteger(p.ToString()); bn = bn.Subtract(new Org.BouncyCastle.Math.BigInteger("1")); if (y.CompareTo(bn) > 0) { LibRTMPLogger.Log(LibRTMPLogLevel.Warning, "[CDR.LibRTMP.RTMPHelper.IsValidPublicKey] DH public key must be at most p-2"); return(false); } // Verify with Sophie-Germain prime // // This is a nice test to make sure the public key position is calculated // correctly. This test will fail in about 50% of the cases if applied to // random data. bn = y.ModPow(q, p); if (bn.CompareTo(new Org.BouncyCastle.Math.BigInteger("1")) != 0) { LibRTMPLogger.Log(LibRTMPLogLevel.Warning, "[CDR.LibRTMP.RTMPHelper.IsValidPublicKey] DH public key does not fulfill y^q mod p = 1"); return(false); } return(true); }
public System.Numerics.BigInteger[] Merge(Part[][] parts, int threshold) { Org.BouncyCastle.Math.BigInteger p1 = new Org.BouncyCastle.Math.BigInteger(p.ToString()); int secretSize = parts[0].Length; System.Numerics.BigInteger[] results = new System.Numerics.BigInteger[secretSize]; string[] secret = new string[secretSize]; byte[] byteArray; string str; int count = 0; // loop through each secret partition for (int i = 0; i < secretSize; i++) { Sum = System.Numerics.BigInteger.Zero; //doing lagrange interpolation for (int j = 0; j < threshold; j++) { mult = System.Numerics.BigInteger.One; for (int k = 0; k < threshold; k++) { if (j != k) { System.Numerics.BigInteger numerator = parts[k][i].GetX(); System.Numerics.BigInteger denominator = System.Numerics.BigInteger.Subtract(numerator, parts[j][i].GetX()); // take mod of negative number while (System.Numerics.BigInteger.Compare(denominator, System.Numerics.BigInteger.Zero) < 0) { denominator = System.Numerics.BigInteger.Add(denominator, p); } //convert to bouncycastle biginteger to calculate modInverse Org.BouncyCastle.Math.BigInteger denominator1 = new Org.BouncyCastle.Math.BigInteger(denominator.ToString()); Org.BouncyCastle.Math.BigInteger invDenominator1 = denominator1.ModInverse(p1); System.Numerics.BigInteger invDenominator = System.Numerics.BigInteger.Parse(invDenominator1.ToString()); mult = System.Numerics.BigInteger.Multiply(mult, System.Numerics.BigInteger.Multiply(numerator, invDenominator)); mult = System.Numerics.BigInteger.Remainder(mult, p); } } mult = System.Numerics.BigInteger.Multiply(mult, parts[j][i].GetY()); mult = System.Numerics.BigInteger.Remainder(mult, p); Sum = System.Numerics.BigInteger.Add(Sum, mult); Sum = System.Numerics.BigInteger.Remainder(Sum, p); } results[i] = Sum; } foreach (System.Numerics.BigInteger r in results) { byteArray = r.ToByteArray(); str = Encoding.UTF8.GetString(byteArray); secret[count++] = str; } return(results); }
public void DecodeToIntTest2() { Org.BouncyCastle.Math.BigInteger actual = Base58.DecodeToBigInteger("6e31iZ"); Assert.IsTrue(actual.ToString() == "3700886826"); }
public void DecodeToIntTest() { Org.BouncyCastle.Math.BigInteger actual = Base58.DecodeToBigInteger("h"); Assert.IsTrue(actual.ToString() == "40"); }
public static BigInteger ToNetBi(this Org.BouncyCastle.Math.BigInteger num) { return(BigInteger.Parse(num.ToString())); }
static void Main(string[] args) { string server = "127.0.0.1"; Int32 port = 13000; TcpClient client = new TcpClient(server, port); NetworkStream stream = client.GetStream(); g = new Org.BouncyCastle.Math.BigInteger(2.ToString()); p = new Org.BouncyCastle.Math.BigInteger(31.ToString()); q = new Org.BouncyCastle.Math.BigInteger(5.ToString()); int n = Int32.Parse(args[0]); gen_keys(); Org.BouncyCastle.Math.BigInteger[] P = req_keys(n - 1); int[] V = gen_v(n - 1); //Start time DateTime now = DateTime.Now; Console.WriteLine("Strat Second: {0}", now.Millisecond); Random random = new Random(); int s = 4; //int s = 29; Org.BouncyCastle.Math.BigInteger U = (g.Pow(s)).Mod(p); for (int i = 0; i < n - 1; ++i) { U = U.Multiply((P[i].Pow(V[i])).Mod(p)).Mod(p); } byte[] bytes; bytes = new byte[204800]; bytes = Encoding.UTF8.GetBytes(U.ToString()); stream.Write(bytes); stream.Flush(); bytes = new byte[64]; stream.Read(bytes, 0, bytes.Length); int c = Int32.Parse(Encoding.UTF8.GetString(bytes)); int v_p = c; for (int i = 0; i < n - 1; ++i) { v_p = v_p ^ V[i]; } string V_str = v_p + "|"; for (int i = 0; i < n - 1; ++i) { V_str += V[i] + "|"; } string P_str = A_p.ToString() + "|"; for (int i = 0; i < n - 1; ++i) { P_str += P[i] + "|"; } Org.BouncyCastle.Math.BigInteger a_p_big = new Org.BouncyCastle.Math.BigInteger(a_p.ToString()); Org.BouncyCastle.Math.BigInteger v_p_big = new Org.BouncyCastle.Math.BigInteger(v_p.ToString()); Org.BouncyCastle.Math.BigInteger s_big = new Org.BouncyCastle.Math.BigInteger(s.ToString()); Org.BouncyCastle.Math.BigInteger r_big = (s_big.Add((a_p_big.Multiply(v_p_big)).Negate())).Mod(q); //int r = (s - ((a_p * v_p) % 31)); //int r = Int32.Parse(r_big.ToString()); string r_str = r_big.ToString(); string msg = V_str + P_str + r_str; bytes = new byte[204800]; bytes = Encoding.UTF8.GetBytes(msg); stream.Write(bytes); stream.Flush(); }
private void Mine() { MinerInfo.minerStillRunning = true; var fromBiginteger = new Org.BouncyCastle.Math.BigInteger(Helper.ConvertBigintegerHexToDecimal(from, hex)); var untilBiginteger = new Org.BouncyCastle.Math.BigInteger(Helper.ConvertBigintegerHexToDecimal(until, hex)); var difference = fromBiginteger.Subtract(untilBiginteger).Abs(); if (Helper.CompareNumbers(difference.ToString(), long.MaxValue.ToString()) > 0) { System.Windows.Forms.MessageBox.Show($"The length of job cant be more than {long.MaxValue}! Please use a smaller job length!"); MinerInfo.minerStillRunning = false; return; } MinerInfo.lengthOfJob = Math.Abs(untilBiginteger.LongValue - fromBiginteger.LongValue); Task.Factory.StartNew(() => { MinerInfo.minerThreadInfo = "Lookup size determine,generating hashset..."; lookupSet = new HashSet <string>(10000); using (StreamReader sr = new StreamReader(path)) { while (sr.Peek() != -1) { lookupSet.Add(sr.ReadLine()); } } stopwatch.Start(); MinerInfo.minerThreadInfo = ""; MinerInfo.minerThreadInfo = "Lookup size determine, generating hashset done, mining..."; while (fromBiginteger.CompareTo(untilBiginteger) < 0 && increment || fromBiginteger.CompareTo(untilBiginteger) > 0 && !increment) { if (cancellationToken.IsCancellationRequested) { break; } var key = KeyPair.Create(fromBiginteger, compressed); if (lookupSet.Contains(key.AddressBase58)) { MinerInfo.minerThreadInfo = $"Found key!!!! Number: {fromBiginteger.ToString()}, address: {key.AddressBase58}"; foundKeyCount++; if (form.InvokeRequired) { form.Invoke((MethodInvoker) delegate { textBox.Text += $"{Environment.NewLine}Found key!!!! Number: {fromBiginteger.ToString()}, address: {key.AddressBase58}, privatekey: {key.PrivateKey}{Environment.NewLine}"; }); } else { } StreamWriter streamWriter = new StreamWriter("keys.txt", true); string keyline = $"Found key!!!! Number: {fromBiginteger.ToString()}, address: {key.AddressBase58}, privatekey: {key.PrivateKey}"; streamWriter.WriteLine(keyline); streamWriter.Flush(); streamWriter.Close(); } if (increment) { fromBiginteger = fromBiginteger.Add(new Org.BouncyCastle.Math.BigInteger("1")); } else { fromBiginteger = fromBiginteger.Add(new Org.BouncyCastle.Math.BigInteger("-1")); } MinerInfo.currentlyProcessed++; MinerInfo.countOfTriedKeys++; if (MinerInfo.currentlyProcessed % 1000 == 0) { MinerInfo.minerThreadInfo = $"Currently Processed number: {fromBiginteger.ToString()}"; } } //int lengthOfOneJob = 0; //if (MinerInfo.lengthOfJob > 10000) //{ // lengthOfOneJob = 10000; //} //else //{ // lengthOfOneJob = (int)MinerInfo.lengthOfJob; //} //StringBuilder stringBuilder = new StringBuilder(chars.Length); //for (int i = 0; i < chars.Length; i++) //{ // stringBuilder.Append(chars[0]); //} //List<string> sequenceList = new List<string>(lengthOfOneJob); //var list = GetAllMatches(chars.ToCharArray(), lengthOfString); //foreach (var item in list) //{ // if (cancellationToken.IsCancellationRequested) // { // break; // } // sequenceList.Add(item); // if (sequenceList.Count == lengthOfOneJob) // { // LookupKeys(sequenceList); // sequenceList.Clear(); // } // MinerInfo.currentlyProcessed++; // if (MinerInfo.currentlyProcessed >= MinerInfo.lengthOfJob && MinerInfo.lengthOfJob > 10000) // { // LookupKeys(sequenceList); // break; // } //} //int count = list.Count(); MinerInfo.minerThreadResults = $"{Environment.NewLine}Found keys: {foundKeyCount}, ckecked numbers: {MinerInfo.countOfTriedKeys} {Environment.NewLine}Additional data: - Combinations: {MinerInfo.lengthOfJob}, elapsed time: {stopwatch.Elapsed}, keys/second: {MinerInfo.countOfTriedKeys / stopwatch.Elapsed.TotalSeconds}"; Dispose(); MinerInfo.minerStillRunning = false; }, TaskCreationOptions.LongRunning); }
static void Main(string[] args) { int n = Int32.Parse(args[0]); g = new Org.BouncyCastle.Math.BigInteger(2.ToString()); p = new Org.BouncyCastle.Math.BigInteger(31.ToString()); q = new Org.BouncyCastle.Math.BigInteger(5.ToString()); TcpListener server = null; Int32 port = 13000; IPAddress localAddr = IPAddress.Parse("127.0.0.1"); // TcpListener server = new TcpListener(port); server = new TcpListener(localAddr, port); // Start listening for client requests. server.Start(); // Buffer for reading data TcpClient client = server.AcceptTcpClient(); NetworkStream stream = client.GetStream(); byte[] bytes; bytes = new byte[204800]; stream.Read(bytes, 0, bytes.Length); string U = Encoding.UTF8.GetString(bytes); Random random = new Random(); int c = random.Next(1, 4); bytes = new byte[64]; bytes = Encoding.UTF8.GetBytes(c.ToString()); stream.Write(bytes); stream.Flush(); bytes = new byte[204800]; stream.Read(bytes, 0, bytes.Length); string msg = Encoding.UTF8.GetString(bytes); string[] temp_split = msg.Split("|"); int[] V = new int[n]; int c0 = 0; for (int i = 0; i < n; ++i) { V[i] = Int32.Parse(temp_split[i]); c0 = c0 ^ V[i]; } Org.BouncyCastle.Math.BigInteger[] P = new Org.BouncyCastle.Math.BigInteger[n]; for (int i = 0; i < n; ++i) { P[i] = new Org.BouncyCastle.Math.BigInteger(temp_split[n + i]); } int r = Int32.Parse(temp_split[2 * n]); if (c0 == c) { Console.WriteLine("1st verification PASS"); } else { Console.WriteLine("1st verification FAIL"); } Org.BouncyCastle.Math.BigInteger U0 = (g.Pow(r)).Mod(p); for (int i = 0; i < n; ++i) { U0 = U0.Multiply((P[i].Pow(V[i])).Mod(p)).Mod(p); } Console.WriteLine(U); Console.WriteLine(U0); string U1 = U0.ToString(); bool flag = true; for (int i = 0; i < U1.Length; ++i) { if (U1[i] != U[i]) { Console.WriteLine("2nd verification FAIL"); flag = false; break; } } if (flag) { Console.WriteLine("2nd verification PASS"); } //End time DateTime now = DateTime.Now; Console.WriteLine("Strat Second: {0}", now.Millisecond); }