private void btnGenerate_Click(object sender, EventArgs e) { ChangeFlag++; try { lblNotSafe.Visible = false; lblWhyNot.Visible = false; SetText(txtMinikey, ""); KeyPair kp = KeyPair.Create(ExtraEntropy.GetEntropy(), compressToolStripMenuItem.Checked); if (txtPassphrase.Text != "") { SetText(txtPrivWIF, new Bip38KeyPair(kp, txtPassphrase.Text).EncryptedPrivateKey); } else { SetText(txtPrivWIF, kp.PrivateKeyBase58); } SetText(txtPrivHex, kp.PrivateKeyHex); SetText(txtPubHex, kp.PublicKeyHex); SetText(txtPubHash, kp.Hash160Hex); SetText(txtBtcAddr, new AddressBase(kp, AddressTypeByte).AddressBase58); } finally { ChangeFlag--; } }
/** * Get the user with a given name * * @param name * @param org * @param mspId * @param privateKeyFile * @param certificateFile * @return user * @throws IOException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws InvalidKeySpecException */ public SampleUser GetMember(string name, string org, string mspId, string privateKeyFile, string certificateFile) { try { // Try to get the SampleUser state from the cache SampleUser sampleUser = members.GetOrNull(SampleUser.ToKeyValStoreName(name, org)); if (null != sampleUser) { return(sampleUser); } // Create the SampleUser and try to restore it's state from the key value store (if found). sampleUser = new SampleUser(name, org, this, cryptoSuite); sampleUser.MspId = mspId; string certificate = File.ReadAllText(certificateFile, Encoding.UTF8); KeyPair pair = KeyPair.Create(File.ReadAllText(privateKeyFile)); sampleUser.Enrollment = new SampleStoreEnrollement(pair.Pem, certificate); sampleUser.SaveState(); return(sampleUser); } catch (IOException e) { logger.ErrorException(e.Message, e); throw; } catch (System.Exception e) { logger.ErrorException(e.Message, e); throw; } }
private void newAddressToolStripMenuItem_Click(object sender, EventArgs e) { KeyPair kp = KeyPair.Create(ExtraEntropy.GetEntropy()); KeyCollectionItem item = new KeyCollectionItem(kp); KeyCollection.AddItem(item); }
private KeyPair FindRightKey() { foreach (X509Certificate2 cert in crypto.Store.Certificates.Select(a => a.X509Certificate2)) { if (cert.HasPrivateKey && cert.FriendlyName == "Hyperledger.Fabric") { byte[] certidata = cert.Export(X509ContentType.Pkcs12, "123"); Pkcs12Store store = new Pkcs12Store(); store.Load(new MemoryStream(certidata), "123".ToCharArray()); AsymmetricKeyEntry parameter = null; List <string> alias = store.Aliases.Cast <string>().ToList(); foreach (string s in alias) { if (store.IsKeyEntry(s)) { parameter = store.GetKey(s); } } if (parameter == null) { return(null); } return(KeyPair.Create(null, parameter.Key)); } } return(null); }
/** * Parse Idemix long-term revocation public key * * @param id * @return idemix long-term revocation public key */ protected KeyPair ReadIdemixRevocationPublicKey(string id) { string path = Path.Combine(mspId, VERIFIER_PATH, id); AsymmetricKeyParameter pub = PublicKeyFactory.CreateKey(KeyPair.PemToDer(File.ReadAllText(path))); return(KeyPair.Create(pub, null)); }
/// <summary> /// Code which is actually run on the generation thread. /// </summary> private void GenerationThreadProcess() { Bip38Intermediate intermediate = null; if (GenChoice == GenChoices.Encrypted) { intermediate = new Bip38Intermediate(UserText, Bip38Intermediate.Interpretation.Passphrase); } int detcount = 1; while (RemainingToGenerate > 0 && StopRequested == false) { KeyCollectionItem newitem = null; switch (GenChoice) { case GenChoices.Minikey: MiniKeyPair mkp = MiniKeyPair.CreateRandom(ExtraEntropy.GetEntropy()); string s = mkp.AddressBase58; // read the property to entice it to compute everything newitem = new KeyCollectionItem(mkp); break; case GenChoices.WIF: KeyPair kp = KeyPair.Create(ExtraEntropy.GetEntropy()); s = kp.AddressBase58; newitem = new KeyCollectionItem(kp); break; case GenChoices.Deterministic: kp = KeyPair.CreateFromString(UserText + detcount); detcount++; s = kp.AddressBase58; newitem = new KeyCollectionItem(kp); break; case GenChoices.Encrypted: Bip38KeyPair ekp = new Bip38KeyPair(intermediate); newitem = new KeyCollectionItem(ekp); break; case GenChoices.TwoFactor: ekp = new Bip38KeyPair(intermediatesForGeneration[intermediateIdx++]); if (intermediateIdx >= intermediatesForGeneration.Length) { intermediateIdx = 0; } newitem = new KeyCollectionItem(ekp); break; } lock (GeneratedItems) { GeneratedItems.Add(newitem); RemainingToGenerate--; } } GeneratingEnded = true; }
public void Handle(GenerateKeyPairCommand cmd) { KeyPair newKeyPair = KeyPair.Create(this.cryptoSvc); if (newKeyPair == null || newKeyPair.Id == Guid.Empty) { throw new Exception("Unable to generate key pair"); } }
/** * Parse Idemix long-term revocation public key from the config file * * @param configPath * @param id * @return the long-term revocation public key */ public static KeyPair ReadIdemixRevocationPublicKey(string configPath, string id) { string path = Path.Combine(configPath, id); byte[] data = KeyPair.PemToDer(File.ReadAllText(path)); AsymmetricKeyParameter pub = PublicKeyFactory.CreateKey(data); return(KeyPair.Create(pub, null)); }
public void TestBytesToPrivateKeyPKCS8() { try { string bytes = File.ReadAllText("Resources/tls-client-pk8.key".Locate()); KeyPair.Create(bytes); } catch (System.Exception e) { Assert.Fail($"failed to parse private key bytes: {e.Message}"); } }
public void TestIdemixMissingMSPID() { HFCAClient client = HFCAClient.Create("client", "http://localhost:99", null); client.CryptoSuite = crypto; var gen = new ECKeyPairGenerator(); var keyGenParam = new KeyGenerationParameters(new SecureRandom(), 256); gen.Init(keyGenParam); KeyPair pair = KeyPair.Create(gen.GenerateKeyPair()); IEnrollment enrollment = new X509Enrollment(pair, ""); client.IdemixEnroll(enrollment, null); }
public void ShouldRaiseFileDecryptedEvent() { MockCryptographyExecutionService cryptoSvc = new MockCryptographyExecutionService(); MockEventDispatcher eventDispatcher = new MockEventDispatcher(); DomainEvents.Dispatcher = eventDispatcher; KeyPair sut = KeyPair.Create(cryptoSvc); sut.Id.Should().NotBeEmpty(); sut.PrivateKey.FileName.Should().Be("TestFile.txt"); sut.PrivateKey.Content.Should().NotBeNull(); sut.PublicKey.FileName.Should().Be("TestFile.txt"); sut.PublicKey.Content.Should().NotBeNull(); sut.PassPhrase.FileName.Should().Be("TestFile.txt"); sut.PassPhrase.Content.Should().NotBeNull(); eventDispatcher.Events.Count.Should().Be(1); eventDispatcher.Events[0].Should().BeOfType <KeyPairGeneratedEvent>(); eventDispatcher.Events[0].AggregateId.Should().NotBeEmpty(); eventDispatcher.Events[0].Created.Should().BeCloseTo(DateTimeOffset.Now, 100, "if you're debugging, then you're delaying the time comparison"); }
public void TestBytesToPrivateKeyNullBytes() { KeyPair.Create((string)null); }
public void TestBytesToPrivateKeyInvalidBytes() { KeyPair.Create(INVALID_PEM_CERT.FromHexString().ToUTF8String()); }
// Creates a new OrgInfo instance from a JSON object private OrgInfo CreateOrg(string orgName, JToken jsonOrg, Dictionary <string, JToken> foundCertificateAuthorities) { string msgPrefix = $"Organization {orgName}"; string mspId = jsonOrg["mspid"]?.Value <string>(); OrgInfo org = new OrgInfo(orgName, mspId); // Peers JArray jsonPeers = jsonOrg["peers"] as JArray; if (jsonPeers != null) { foreach (JToken peer in jsonPeers) { string peerName = peer.Value <string>(); if (!string.IsNullOrEmpty(peerName)) { org.PeerName.Add(peerName); } } } // CAs JArray jsonCertificateAuthorities = jsonOrg["certificateAuthorities"] as JArray; if (jsonCertificateAuthorities != null) { foreach (JToken jsonCA in jsonCertificateAuthorities) { string caName = jsonCA.Value <string>(); if (!string.IsNullOrEmpty(caName)) { JToken jsonObject = foundCertificateAuthorities[caName]; if (jsonObject != null) { org.CertificateAuthorities.Add(CreateCA(caName, jsonObject, org)); } else { throw new NetworkConfigurationException($"{msgPrefix}: Certificate Authority {caName} is not defined"); } } } } string adminPrivateKeyString = ExtractPemString(jsonOrg, "adminPrivateKey", msgPrefix); string signedCert = ExtractPemString(jsonOrg, "signedCert", msgPrefix); if (!string.IsNullOrEmpty(adminPrivateKeyString) && !string.IsNullOrEmpty(signedCert)) { KeyPair privateKey; try { privateKey = KeyPair.Create(adminPrivateKeyString); } catch (IOException ioe) { throw new NetworkConfigurationException($"{msgPrefix}: Invalid private key", ioe); } try { org.PeerAdmin = new UserInfo(Factory.GetCryptoSuite(), mspId, "PeerAdmin_" + mspId + "_" + orgName, null); } catch (Exception e) { throw new NetworkConfigurationException(e.Message, e); } org.PeerAdmin.Enrollment = new X509Enrollment(privateKey, signedCert); } return(org); }
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); }