public void HashSet3() { var hashes = new Hashes { A = new HashSet<short> { 1, 2, 3 }, B = new HashSet<int> { 1, 2, 3 }, C = new HashSet<long> { 1, 2, 3 }, D = new HashSet<string> { "a", "b", "c" }, E = new HashSet<float> { 1.1f, 2.2f, 3.3f }, F = new HashSet<Double> { 1.1d, 2.2d, 3.3d } }; var json = new JsonSerializer().Serialize(hashes); Assert.True((json["A"] as XSet<short>).IsSet); Assert.Equal(@"{ ""A"": [ 1, 2, 3 ], ""B"": [ 1, 2, 3 ], ""C"": [ 1, 2, 3 ], ""D"": [ ""a"", ""b"", ""c"" ], ""E"": [ 1.1, 2.2, 3.3 ], ""F"": [ 1.1, 2.2, 3.3 ] }", json.ToString()); }
public static Hashes CalculateHashes(string strPath, OnHashProgress onHashProgress) { if (UseDll()) { byte[] hash = new byte[56]; Hashes rhash = new Hashes(); if (CalculateHashes_dll(strPath, ref hash, onHashProgress)) { rhash.ed2k = HashToString(hash, 0, 16); rhash.crc32 = HashToString(hash, 16, 4); rhash.md5 = HashToString(hash, 20, 16); rhash.sha1 = HashToString(hash, 36, 20); } else { rhash.ed2k = string.Empty; rhash.crc32 = string.Empty; rhash.md5 = string.Empty; rhash.sha1 = string.Empty; } return rhash; } return CalculateHashes_here(strPath, onHashProgress); }
public static Hashes ToHashes(this object value) { Hashes array = new Hashes(); var objectArray = value as Object[]; foreach (Object current in objectArray) { array.Add(current as Hash); } return array; }
public async Task <IActionResult> PostInputsAsync([FromBody, Required] InputsRequest request) { // Validate request. if (request.RoundId < 0 || !ModelState.IsValid) { return(BadRequest("Invalid request.")); } if (request.Inputs.Count() > 7) { return(BadRequest("Maximum 7 inputs can be registered.")); } using (await InputsLock.LockAsync()) { CcjRound round = Coordinator.TryGetRound(request.RoundId); if (round is null || round.Phase != CcjRoundPhase.InputRegistration) { return(NotFound("No such running round in InputRegistration. Try another round.")); } // Do more checks. try { uint256[] blindedOutputs = request.BlindedOutputScripts.ToArray(); int blindedOutputCount = blindedOutputs.Length; int maxBlindedOutputCount = round.MixingLevels.Count(); if (blindedOutputCount > maxBlindedOutputCount) { return(BadRequest($"Too many blinded output was provided: {blindedOutputCount}, maximum: {maxBlindedOutputCount}.")); } if (blindedOutputs.Distinct().Count() < blindedOutputs.Length) { return(BadRequest("Duplicate blinded output found.")); } if (round.ContainsAnyBlindedOutputScript(blindedOutputs)) { return(BadRequest("Blinded output has already been registered.")); } if (request.ChangeOutputAddress.Network != Network) { // RegTest and TestNet address formats are sometimes the same. if (Network == Network.Main) { return(BadRequest($"Invalid ChangeOutputAddress Network.")); } } var uniqueInputs = new HashSet <TxoRef>(); foreach (InputProofModel inputProof in request.Inputs) { if (uniqueInputs.Contains(inputProof.Input)) { return(BadRequest("Cannot register an input twice.")); } uniqueInputs.Add(inputProof.Input); } var alicesToRemove = new HashSet <Guid>(); var getTxOutResponses = new List <(InputProofModel inputModel, Task <GetTxOutResponse> getTxOutTask)>(); var batch = RpcClient.PrepareBatch(); foreach (InputProofModel inputProof in request.Inputs) { if (round.ContainsInput(inputProof.Input.ToOutPoint(), out List <Alice> tr)) { alicesToRemove.UnionWith(tr.Select(x => x.UniqueId)); // Input is already registered by this alice, remove it later if all the checks are completed fine. } if (Coordinator.AnyRunningRoundContainsInput(inputProof.Input.ToOutPoint(), out List <Alice> tnr)) { if (tr.Union(tnr).Count() > tr.Count) { return(BadRequest("Input is already registered in another round.")); } } OutPoint outpoint = inputProof.Input.ToOutPoint(); var bannedElem = await Coordinator.UtxoReferee.TryGetBannedAsync(outpoint, notedToo : false); if (bannedElem != null) { return(BadRequest($"Input is banned from participation for {(int)bannedElem.BannedRemaining.TotalMinutes} minutes: {inputProof.Input.Index}:{inputProof.Input.TransactionId}.")); } var txOutResponseTask = batch.GetTxOutAsync(inputProof.Input.TransactionId, (int)inputProof.Input.Index, includeMempool: true); getTxOutResponses.Add((inputProof, txOutResponseTask)); } // Perform all RPC request at once var waiting = Task.WhenAll(getTxOutResponses.Select(x => x.getTxOutTask)); await batch.SendBatchAsync(); await waiting; byte[] blindedOutputScriptHashesByte = ByteHelpers.Combine(blindedOutputs.Select(x => x.ToBytes())); uint256 blindedOutputScriptsHash = new uint256(Hashes.SHA256(blindedOutputScriptHashesByte)); var inputs = new HashSet <Coin>(); foreach (var responses in getTxOutResponses) { var(inputProof, getTxOutResponseTask) = responses; var getTxOutResponse = await getTxOutResponseTask; // Check if inputs are unspent. if (getTxOutResponse is null) { return(BadRequest($"Provided input is not unspent: {inputProof.Input.Index}:{inputProof.Input.TransactionId}.")); } // Check if unconfirmed. if (getTxOutResponse.Confirmations <= 0) { // If it spends a CJ then it may be acceptable to register. if (!await Coordinator.ContainsCoinJoinAsync(inputProof.Input.TransactionId)) { return(BadRequest("Provided input is neither confirmed, nor is from an unconfirmed coinjoin.")); } // Check if mempool would accept a fake transaction created with the registered inputs. // This will catch ascendant/descendant count and size limits for example. var result = await RpcClient.TestMempoolAcceptAsync(new[] { new Coin(inputProof.Input.ToOutPoint(), getTxOutResponse.TxOut) }); if (!result.accept) { return(BadRequest($"Provided input is from an unconfirmed coinjoin, but a limit is reached: {result.rejectReason}")); } } // Check if immature. if (getTxOutResponse.Confirmations <= 100) { if (getTxOutResponse.IsCoinBase) { return(BadRequest("Provided input is immature.")); } } // Check if inputs are native segwit. if (getTxOutResponse.ScriptPubKeyType != "witness_v0_keyhash") { return(BadRequest("Provided input must be witness_v0_keyhash.")); } TxOut txOut = getTxOutResponse.TxOut; var address = (BitcoinWitPubKeyAddress)txOut.ScriptPubKey.GetDestinationAddress(Network); // Check if proofs are valid. if (!address.VerifyMessage(blindedOutputScriptsHash, inputProof.Proof)) { return(BadRequest("Provided proof is invalid.")); } inputs.Add(new Coin(inputProof.Input.ToOutPoint(), txOut)); } var acceptedBlindedOutputScripts = new List <uint256>(); // Calculate expected networkfee to pay after base denomination. int inputCount = inputs.Count; Money networkFeeToPayAfterBaseDenomination = (inputCount * round.FeePerInputs) + (2 * round.FeePerOutputs); // Check if inputs have enough coins. Money inputSum = inputs.Sum(x => x.Amount); Money changeAmount = (inputSum - (round.MixingLevels.GetBaseDenomination() + networkFeeToPayAfterBaseDenomination)); if (changeAmount < Money.Zero) { return(BadRequest($"Not enough inputs are provided. Fee to pay: {networkFeeToPayAfterBaseDenomination.ToString(false, true)} BTC. Round denomination: {round.MixingLevels.GetBaseDenomination().ToString(false, true)} BTC. Only provided: {inputSum.ToString(false, true)} BTC.")); } acceptedBlindedOutputScripts.Add(blindedOutputs.First()); Money networkFeeToPay = networkFeeToPayAfterBaseDenomination; // Make sure we sign the proper number of additional blinded outputs. var moneySoFar = Money.Zero; for (int i = 1; i < blindedOutputCount; i++) { if (!round.MixingLevels.TryGetDenomination(i, out Money denomination)) { break; } Money coordinatorFee = denomination.Percentage(round.CoordinatorFeePercent * round.AnonymitySet); // It should be the number of bobs, but we must make sure they'd have money to pay all. changeAmount -= (denomination + round.FeePerOutputs + coordinatorFee); networkFeeToPay += round.FeePerOutputs; if (changeAmount < Money.Zero) { break; } acceptedBlindedOutputScripts.Add(blindedOutputs[i]); } // Make sure Alice checks work. var alice = new Alice(inputs, networkFeeToPayAfterBaseDenomination, request.ChangeOutputAddress, acceptedBlindedOutputScripts); foreach (Guid aliceToRemove in alicesToRemove) { round.RemoveAlicesBy(aliceToRemove); } round.AddAlice(alice); // All checks are good. Sign. var blindSignatures = new List <uint256>(); for (int i = 0; i < acceptedBlindedOutputScripts.Count; i++) { var blindedOutput = acceptedBlindedOutputScripts[i]; var signer = round.MixingLevels.GetLevel(i).Signer; uint256 blindSignature = signer.Sign(blindedOutput); blindSignatures.Add(blindSignature); } alice.BlindedOutputSignatures = blindSignatures.ToArray(); // Check if phase changed since. if (round.Status != CcjRoundStatus.Running || round.Phase != CcjRoundPhase.InputRegistration) { return(StatusCode(StatusCodes.Status503ServiceUnavailable, "The state of the round changed while handling the request. Try again.")); } // Progress round if needed. if (round.CountAlices() >= round.AnonymitySet) { await round.RemoveAlicesIfAnInputRefusedByMempoolAsync(); if (round.CountAlices() >= round.AnonymitySet) { await round.ExecuteNextPhaseAsync(CcjRoundPhase.ConnectionConfirmation); } } var resp = new InputsResponse { UniqueId = alice.UniqueId, RoundId = round.RoundId }; return(Ok(resp)); } catch (Exception ex) { Logger.LogDebug <ChaumianCoinJoinController>(ex); return(BadRequest(ex.Message)); } } }
private void WorkerIntegrityScanner_DoWork(object sender, DoWorkEventArgs e) { if (RunScan != null && RunScan.GetScanStatus() != ScanStatus.Finish) { bool paused = ShokoService.CmdProcessorHasher.Paused; ShokoService.CmdProcessorHasher.Paused = true; SVR_Scan s = RunScan; s.Status = (int)ScanStatus.Running; RepoFactory.Scan.Save(s); Refresh(); List <ScanFile> files = RepoFactory.ScanFile.GetWaiting(s.ScanID); int cnt = 0; foreach (ScanFile sf in files) { try { if (!File.Exists(sf.FullName)) { sf.Status = (int)ScanFileStatus.ErrorFileNotFound; } else { FileInfo f = new FileInfo(sf.FullName); if (sf.FileSize != f.Length) { sf.Status = (int)ScanFileStatus.ErrorInvalidSize; } else { ShokoService.CmdProcessorHasher.QueueState = new QueueStateStruct { queueState = QueueStateEnum.HashingFile, extraParams = new[] { sf.FullName } }; Hashes hashes = FileHashHelper.GetHashInfo(sf.FullName, true, OnHashProgress, false, false, false); if (string.IsNullOrEmpty(hashes.ED2K)) { sf.Status = (int)ScanFileStatus.ErrorMissingHash; } else { sf.HashResult = hashes.ED2K; if (!sf.Hash.Equals(sf.HashResult, StringComparison.InvariantCultureIgnoreCase)) { sf.Status = (int)ScanFileStatus.ErrorInvalidHash; } else { sf.Status = (int)ScanFileStatus.ProcessedOK; } } } } } catch (Exception) { sf.Status = (int)ScanFileStatus.ErrorIOError; } cnt++; sf.CheckDate = DateTime.Now; RepoFactory.ScanFile.Save(sf); if (sf.Status > (int)ScanFileStatus.ProcessedOK) { Instance.AddErrorScan(sf); } Refresh(); if (cancelIntegrityCheck) { break; } } if (files.Any(a => a.GetScanFileStatus() == ScanFileStatus.Waiting)) { s.Status = (int)ScanStatus.Standby; } else { s.Status = (int)ScanStatus.Finish; } RepoFactory.Scan.Save(s); Refresh(); RunScan = null; ShokoService.CmdProcessorHasher.Paused = paused; } }
public ExecutedFingerprintCommand(Hashes result) { this.result = result; }
public WitScriptId(Script script) : this(Hashes.SHA256(script._Script)) { }
public ExtKey GetParentExtKey(ExtPubKey parent) { if (parent is null) { throw new ArgumentNullException(nameof(parent)); } if (Depth == 0) { throw new InvalidOperationException("This ExtKey is the root key of the HD tree"); } if (IsHardened) { throw new InvalidOperationException("This private key is hardened, so you can't get its parent"); } var expectedFingerPrint = parent.PubKey.GetHDFingerPrint(); if (parent.Depth != this.Depth - 1 || expectedFingerPrint != parentFingerprint) { throw new ArgumentException("The parent ExtPubKey is not the immediate parent of this ExtKey", "parent"); } #if HAS_SPAN Span <byte> pubkey = stackalloc byte[33]; Span <byte> l = stackalloc byte[64]; parent.PubKey.ToBytes(pubkey, out _); Hashes.BIP32Hash(parent.vchChainCode, nChild, pubkey[0], pubkey.Slice(1), l); var parse256LL = new Secp256k1.Scalar(l.Slice(0, 32), out int overflow); if (overflow != 0 || parse256LL.IsZero) { throw new InvalidOperationException("Invalid extkey (this should never happen)"); } if (!l.Slice(32, 32).SequenceEqual(vchChainCode)) { throw new InvalidOperationException("The derived chain code of the parent is not equal to this child chain code"); } var kPar = this.PrivateKey._ECKey.sec + parse256LL.Negate(); return(new ExtKey(new Key(new Secp256k1.ECPrivKey(kPar, this.PrivateKey._ECKey.ctx, true), true), parent.vchChainCode, parent.Depth, parent.ParentFingerprint, parent.nChild)); #else byte[] ll = new byte[32]; byte[] lr = new byte[32]; var pubKey = parent.PubKey.ToBytes(); byte[] l = Hashes.BIP32Hash(parent.vchChainCode, nChild, pubKey[0], pubKey.SafeSubarray(1)); Array.Copy(l, ll, 32); Array.Copy(l, 32, lr, 0, 32); var ccChild = lr; BigInteger parse256LL = new BigInteger(1, ll); BigInteger N = ECKey.CURVE.N; if (!ccChild.SequenceEqual(vchChainCode)) { throw new InvalidOperationException("The derived chain code of the parent is not equal to this child chain code"); } var keyBytes = PrivateKey.ToBytes(); var key = new BigInteger(1, keyBytes); BigInteger kPar = key.Add(parse256LL.Negate()).Mod(N); var keyParentBytes = kPar.ToByteArrayUnsigned(); if (keyParentBytes.Length < 32) { keyParentBytes = new byte[32 - keyParentBytes.Length].Concat(keyParentBytes).ToArray(); } var parentExtKey = new ExtKey(new Key(keyParentBytes), parent.vchChainCode, parent.Depth, parent.ParentFingerprint, parent.nChild); return(parentExtKey); #endif }
public bool CheckSignature(PubKey key) { return(key.Verify(Hashes.Hash256(payload.GetString()), signature.GetString())); }
/// <summary> /// Computes the cryptographic hash of an input string over a specified number of /// iterations and returns a Base64-encoded result /// </summary> /// <param name="hash">The cryptographic hash algorithm to use, specified by one of /// the <see cref="Hashes"/> enumeration values.</param> /// <param name="encoding">The text encoding of the input text</param> /// <param name="text">The input string to hash.</param> /// <param name="count">An iteration count. The hash will be applied to the string /// this many times. This must be a positive integer.</param> /// <returns>A Base64-encoded string representing the hash of the input string</returns> /// <exception cref="HashEngineException">Thrown whenever anything bad happens when the /// hash is computed</exception> public static string HashString(Hashes hash, Encoding encoding, string text, int count) { // If the iteration count is less than zero, throw an exception. We could use // an unsigned integer here, but that's overkill since we should never want to // perform the hash over two billion times! if (count <= 0) throw new HashEngineException("The number of interations must " + "be a positive integer."); // Asbestos underpants: try { // Get the hash algorithm: HashAlgorithm hasher = GetHashAlgorithm(hash); // Convert the input string to raw bytes using the default system encoding. // We could let the user specify the encoding here, but for now we'll let // that slide. byte[] theHash = encoding.GetBytes(text); // Iterate the hash so many times. Note this implies the hash will be done // at least once. for (int i = 0; i < count; i++) { // Compute the hash of the current value of the byte array. For the // first pass, this is the value of the input string; for every subsequent // pass, it's the previous hash value. hasher.TransformFinalBlock(theHash, 0, theHash.Length); theHash = hasher.Hash; hasher.Initialize(); } // Build the output. Note that for our purposes, we'll always be returning // Base64 here, since that gives us a strong pseudo-random password. return Convert.ToBase64String(theHash); } // If anything blows up, rewrap the error in a HashEngineException and send it // back to the caller: catch (Exception ex) { throw new HashEngineException(ex.Message); } }
internal static uint160 GetHash(this DerivationStrategyBase derivation) { var data = Encoding.UTF8.GetBytes(derivation.ToString()); return(new uint160(Hashes.RIPEMD160(data, data.Length))); }
/// <summary> /// Populates the index with data stored in the database.</summary> public async Task LoadDataAsync() { foreach (var ex in await Database.GetExclusionsAsync()) { await AddFileExclusionAsync(ex, false); } foreach (var hash in await Database.GetFileHashAsync()) { AddFileHash(hash); } var loadedArchives = await Database.GetArchiveAsync(); // Prepare loaded sets before adding them to the index foreach (var archive in loadedArchives) { archive.Index = this; archive.Volume = (await Database.GetLogicalVolumeAsync(archive.Guid.ToString())).FirstOrDefault(); archive.Volume.RefreshStatus(); archive.Volume = await AddLogicalVolume(archive.Volume, false); // rebuild the directory tree of the archive // load all nodes of the archive var loadedNodes = await Database.GetFileNodeAsync(archive.Guid.ToString()); loadedNodes.Sort(); // create a lookup collection by grouping each node by their respective directory name var groupedNodes = loadedNodes.GroupBy(x => x.DirectoryName); foreach (var node in loadedNodes) { node.Archive = archive; if (node is FileNode) { // don't look for further subdirectories if the current item is a file node // instead link it with it's file hash var hash = Hashes.FirstOrDefault(x => x.Checksum.Equals(((FileNode)node).Checksum)); if (hash != null) { hash.AddNode((FileNode)node); ((FileNode)node).Hash = hash; } } else { // find all child items from the lookup collection var childNodes = groupedNodes.FirstOrDefault(x => x.Key == (Path.Combine(node.DirectoryName, node.Name))); if (childNodes is null || childNodes.Count() == 0) { continue; } foreach (var childNode in childNodes) { // if the name of directory is "\", it's automatically the root directory // it's not possible for these directories to have a parent, so skipt them if (childNode.DirectoryName == @"\" && childNode.Name == @"\") { continue; } childNode.Parent = node; if (childNode is FileNode) { node.FileNodes.Add((FileNode)childNode); } else { node.SubDirectories.Add(childNode); } } } } // The only directory left without a parent is the root directory archive.RootDirectory = loadedNodes .OfType <FileDirectory>() .FirstOrDefault(x => x.Parent == null && x.GetType() == typeof(FileDirectory)); } foreach (var archive in loadedArchives) { Archives.Add(archive); } }
// select a block from the candidate blocks in vSortedByTimestamp, excluding // already selected blocks in vSelectedBlocks, and with timestamp up to // nSelectionIntervalStop. private static bool SelectBlockFromCandidates(ChainedBlock chainIndex, SortedDictionary <uint, uint256> sortedByTimestamp, Dictionary <uint256, ChainedBlock> mapSelectedBlocks, long nSelectionIntervalStop, ulong nStakeModifierPrev, out ChainedBlock pindexSelected) { bool fSelected = false; uint256 hashBest = 0; pindexSelected = null; foreach (var item in sortedByTimestamp) { var pindex = chainIndex.FindAncestorOrSelf(item.Value); if (pindex == null) { return(false); // error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString()); } if (fSelected && pindex.Header.Time > nSelectionIntervalStop) { break; } if (mapSelectedBlocks.Keys.Any(key => key == pindex.HashBlock)) { continue; } // compute the selection hash by hashing its proof-hash and the // previous proof-of-stake modifier uint256 hashSelection; using (var ms = new MemoryStream()) { var serializer = new BitcoinStream(ms, true); serializer.ReadWrite(pindex.Header.PosParameters.HashProof); serializer.ReadWrite(nStakeModifierPrev); hashSelection = Hashes.Hash256(ms.ToArray()); } // the selection hash is divided by 2**32 so that proof-of-stake block // is always favored over proof-of-work block. this is to preserve // the energy efficiency property if (pindex.Header.PosParameters.IsProofOfStake()) { hashSelection >>= 32; } if (fSelected && hashSelection < hashBest) { hashBest = hashSelection; pindexSelected = pindex; } else if (!fSelected) { fSelected = true; hashBest = hashSelection; pindexSelected = pindex; } } //LogPrint("stakemodifier", "SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString()); return(fSelected); }
// Stratis kernel protocol // coinstake must meet hash target according to the protocol: // kernel (input 0) must meet the formula // hash(nStakeModifier + txPrev.block.nTime + txPrev.nTime + txPrev.vout.hash + txPrev.vout.n + nTime) < bnTarget * nWeight // this ensures that the chance of getting a coinstake is proportional to the // amount of coins one owns. // The reason this hash is chosen is the following: // nStakeModifier: scrambles computation to make it very difficult to precompute // future proof-of-stake // txPrev.block.nTime: prevent nodes from guessing a good timestamp to // generate transaction for future advantage, // obsolete since v3 // txPrev.nTime: slightly scrambles computation // txPrev.vout.hash: hash of txPrev, to reduce the chance of nodes // generating coinstake at the same time // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes // generating coinstake at the same time // nTime: current timestamp // block/tx hash should not be used here as they can be generated in vast // quantities so as to generate blocks faster, degrading the system back into // a proof-of-work situation. // private static bool CheckStakeKernelHashV2(ChainedBlock pindexPrev, uint nBits, uint nTimeBlockFrom, Transaction txPrev, OutPoint prevout, uint nTimeTx, out uint256 hashProofOfStake, out uint256 targetProofOfStake, bool fPrintProofOfStake) { targetProofOfStake = null; hashProofOfStake = null; if (nTimeTx < txPrev.Time) // Transaction timestamp violation { return(false); //error("CheckStakeKernelHash() : nTime violation"); } // Base target var bnTarget = new Target(nBits).ToBigInteger(); // Weighted target var nValueIn = txPrev.Outputs[prevout.N].Value.Satoshi; var bnWeight = BigInteger.ValueOf(nValueIn); bnTarget = bnTarget.Multiply(bnWeight); // todo: investigate this issue, is the convertion to uint256 similar to the c++ implementation //targetProofOfStake = Target.ToUInt256(bnTarget); var nStakeModifier = pindexPrev.Header.PosParameters.StakeModifier; uint256 bnStakeModifierV2 = pindexPrev.Header.PosParameters.StakeModifierV2; int nStakeModifierHeight = pindexPrev.Height; var nStakeModifierTime = pindexPrev.Header.Time; // Calculate hash using (var ms = new MemoryStream()) { var serializer = new BitcoinStream(ms, true); if (IsProtocolV3((int)nTimeTx)) { serializer.ReadWrite(bnStakeModifierV2); } else { serializer.ReadWrite(nStakeModifier); serializer.ReadWrite(nTimeBlockFrom); } serializer.ReadWrite(txPrev.Time); serializer.ReadWrite(prevout.Hash); serializer.ReadWrite(prevout.N); serializer.ReadWrite(nTimeTx); hashProofOfStake = Hashes.Hash256(ms.ToArray()); } if (fPrintProofOfStake) { //LogPrintf("CheckStakeKernelHash() : using modifier 0x%016x at height=%d timestamp=%s for block from timestamp=%s\n", // nStakeModifier, nStakeModifierHeight, // DateTimeStrFormat(nStakeModifierTime), // DateTimeStrFormat(nTimeBlockFrom)); //LogPrintf("CheckStakeKernelHash() : check modifier=0x%016x nTimeBlockFrom=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n", // nStakeModifier, // nTimeBlockFrom, txPrev.nTime, prevout.n, nTimeTx, // hashProofOfStake.ToString()); } // Now check if proof-of-stake hash meets target protocol var hashProofOfStakeTarget = new BigInteger(hashProofOfStake.ToBytes(false)); if (hashProofOfStakeTarget.CompareTo(bnTarget) > 0) { return(false); } // if (fDebug && !fPrintProofOfStake) // { // LogPrintf("CheckStakeKernelHash() : using modifier 0x%016x at height=%d timestamp=%s for block from timestamp=%s\n", // nStakeModifier, nStakeModifierHeight, // DateTimeStrFormat(nStakeModifierTime), // DateTimeStrFormat(nTimeBlockFrom)); // LogPrintf("CheckStakeKernelHash() : pass modifier=0x%016x nTimeBlockFrom=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n", // nStakeModifier, // nTimeBlockFrom, txPrev.nTime, prevout.n, nTimeTx, // hashProofOfStake.ToString()); // } return(true); }
/// <summary> /// Constructs a progress dialog box with the given file path string and the /// specified hashing algorithm. The dialog by default is centered in the parent window. /// </summary> /// <param name="filename">A string containing the path to the file to be hashed</param> /// <param name="hashAlgorithm">The hashing algorithm to use</param> public ProgressDialog(string filename, Hashes hashAlgorithm) : this(filename, hashAlgorithm, false, HashEngine.DefaultOutputType) { }
/// <summary> /// Constructs a progress dialog box with the given file path string and the /// specified hashing algorithm /// </summary> /// <param name="filename">A string containing the path to the file to be hashed</param> /// <param name="hashAlgorithm">The hashing algorithm to use</param> /// <param name="centerInScreen">True to center in the middle of the screen, false to /// center around the parent window</param> public ProgressDialog(string filename, Hashes hashAlgorithm, bool centerInScreen) : this(filename, hashAlgorithm, centerInScreen, HashEngine.DefaultOutputType) { }
public Key Derivate(byte[] cc, uint nChild, out byte[] ccChild) { AssertNotDisposed(); #if HAS_SPAN if (!IsCompressed) { throw new InvalidOperationException("The key must be compressed"); } Span <byte> vout = stackalloc byte[64]; vout.Clear(); if ((nChild >> 31) == 0) { Span <byte> pubkey = stackalloc byte[33]; this.PubKey.ToBytes(pubkey, out _); Hashes.BIP32Hash(cc, nChild, pubkey[0], pubkey.Slice(1), vout); } else { Span <byte> privkey = stackalloc byte[32]; this._ECKey.WriteToSpan(privkey); Hashes.BIP32Hash(cc, nChild, 0, privkey, vout); privkey.Fill(0); } ccChild = new byte[32]; vout.Slice(32, 32).CopyTo(ccChild); Secp256k1.ECPrivKey keyChild = _ECKey.TweakAdd(vout.Slice(0, 32)); vout.Clear(); return(new Key(keyChild, true)); #else byte[]? l = null; if ((nChild >> 31) == 0) { var pubKey = PubKey.ToBytes(); l = Hashes.BIP32Hash(cc, nChild, pubKey[0], pubKey.SafeSubarray(1)); } else { l = Hashes.BIP32Hash(cc, nChild, 0, this.ToBytes()); } var ll = l.SafeSubarray(0, 32); var lr = l.SafeSubarray(32, 32); ccChild = lr; var parse256LL = new BigInteger(1, ll); var kPar = new BigInteger(1, vch); var N = ECKey.CURVE.N; if (parse256LL.CompareTo(N) >= 0) { throw new InvalidOperationException("You won a prize ! this should happen very rarely. Take a screenshot, and roll the dice again."); } var key = parse256LL.Add(kPar).Mod(N); if (key == BigInteger.Zero) { throw new InvalidOperationException("You won the big prize ! this has probability lower than 1 in 2^127. Take a screenshot, and roll the dice again."); } var keyBytes = key.ToByteArrayUnsigned(); if (keyBytes.Length < 32) { keyBytes = new byte[32 - keyBytes.Length].Concat(keyBytes).ToArray(); } return(new Key(keyBytes)); #endif }
/// <summary> /// Given an item from the Hashes enumeration, get the HashAlgorithm associated with it. /// </summary> /// <param name="hash">A Hashes enumeration item</param> /// <returns>The HashAlgorithm that matches the enumerated hash</returns> private static HashAlgorithm GetHashAlgorithm(Hashes hash) { HashAlgorithm hasher = null; switch (hash) { case Hashes.MD5: hasher = new MD5CryptoServiceProvider(); break; case Hashes.SHA1: hasher = new SHA1CryptoServiceProvider(); break; case Hashes.SHA256: hasher = new SHA256Managed(); break; case Hashes.SHA384: hasher = new SHA384Managed(); break; case Hashes.SHA512: hasher = new SHA512Managed(); break; case Hashes.RIPEMD160: hasher = new RIPEMD160Managed(); break; case Hashes.Whirlpool: hasher = new WhirlpoolManaged(); break; case Hashes.Tiger: hasher = new TigerManaged(); break; // If we didn't get something we expected, default to MD5: default: hasher = new MD5CryptoServiceProvider(); break; } return hasher; }
public static string GetFatBlobName(this ITableEntity entity) { return("unk" + Hashes.Hash256(Encoding.UTF8.GetBytes(entity.PartitionKey + entity.RowKey)).ToString()); }
public void UpdateSignature(Key key, ProtocolVersion version = ProtocolVersion.PROTOCOL_VERSION) { UpdatePayload(); signature = new VarString(key.Sign(Hashes.Hash256(payload.GetString())).ToDER()); }
/// <summary> /// Recreates the private key of the parent from the private key of the child /// combinated with the public key of the parent (hardened children cannot be /// used to recreate the parent). /// </summary> public ExtKey GetParentExtKey(ExtPubKey parent) { if (parent == null) { throw new ArgumentNullException(nameof(parent)); } if (Depth == 0) { throw new InvalidOperationException("This ExtKey is the root key of the HD tree"); } if (IsHardened) { throw new InvalidOperationException("This private key is hardened, so you can't get its parent"); } var expectedFingerPrint = parent.PubKey.GetHDFingerPrint(); if (parent.Depth != this.Depth - 1 || expectedFingerPrint != parentFingerprint) { throw new ArgumentException("The parent ExtPubKey is not the immediate parent of this ExtKey", "parent"); } byte[] l = null; byte[] ll = new byte[32]; byte[] lr = new byte[32]; var pubKey = parent.PubKey.ToBytes(); l = Hashes.BIP32Hash(parent.vchChainCode, nChild, pubKey[0], pubKey.SafeSubarray(1)); Array.Copy(l, ll, 32); Array.Copy(l, 32, lr, 0, 32); var ccChild = lr; BigInteger parse256LL = new BigInteger(1, ll); BigInteger N = ECKey.CURVE.N; if (!ccChild.SequenceEqual(vchChainCode)) { throw new InvalidOperationException("The derived chain code of the parent is not equal to this child chain code"); } var keyBytes = PrivateKey.ToBytes(); var key = new BigInteger(1, keyBytes); BigInteger kPar = key.Add(parse256LL.Negate()).Mod(N); var keyParentBytes = kPar.ToByteArrayUnsigned(); if (keyParentBytes.Length < 32) { keyParentBytes = new byte[32 - keyParentBytes.Length].Concat(keyParentBytes).ToArray(); } var parentExtKey = new ExtKey { vchChainCode = parent.vchChainCode, nDepth = parent.Depth, parentFingerprint = parent.ParentFingerprint, nChild = parent.nChild, key = new Key(keyParentBytes) }; return(parentExtKey); }
public uint160 GetHash() { return(Hashes.Hash160(this.ToBytes())); }
/// <summary> /// Take the first four bytes of SHA256(SHA256(generatedaddress)) and call it addresshash. /// </summary> /// <param name="address"></param> /// <returns></returns> internal static byte[] HashAddress(BitcoinAddress address) { return(Hashes.Hash256(Encoders.ASCII.DecodeData(address.ToString())).ToBytes().Take(4).ToArray()); }
public static Hashes CalculateHashes_here(string strPath, OnHashProgress onHashProgress, bool getCRC32, bool getMD5, bool getSHA1) { bool getED2k = true; logger.Trace("Using C# code to has file: {0}", strPath); FileStream fs; Hashes rhash = new Hashes(); FileInfo fi = new FileInfo(strPath); fs = fi.OpenRead(); int lChunkSize = 9728000; long nBytes = fs.Length; long nBytesRemaining = fs.Length; int nBytesToRead = 0; long nBlocks = nBytes / lChunkSize; long nRemainder = nBytes % lChunkSize; //mod if (nRemainder > 0) { nBlocks++; } byte[] baED2KHash = new byte[16 * nBlocks]; if (nBytes > lChunkSize) { nBytesToRead = lChunkSize; } else { nBytesToRead = (int)nBytesRemaining; } onHashProgress?.Invoke(strPath, 0); MD4 md4 = MD4.Create(); MD5 md5 = MD5.Create(); SHA1 sha1 = SHA1.Create(); Crc32 crc32 = new Crc32(); byte[] ByteArray = new byte[nBytesToRead]; long iOffSet = 0; long iChunkCount = 0; while (nBytesRemaining > 0) { iChunkCount++; //logger.Trace("Hashing Chunk: " + iChunkCount.ToString()); int nBytesRead = fs.Read(ByteArray, 0, nBytesToRead); if (getED2k) { byte[] baHash = md4.ComputeHash(ByteArray, 0, nBytesRead); int j = (int)((iChunkCount - 1) * 16); for (int i = 0; i < 16; i++) { baED2KHash[j + i] = baHash[i]; } } if (getMD5) { md5.TransformBlock(ByteArray, 0, nBytesRead, ByteArray, 0); } if (getSHA1) { sha1.TransformBlock(ByteArray, 0, nBytesRead, ByteArray, 0); } if (getCRC32) { crc32.TransformBlock(ByteArray, 0, nBytesRead, ByteArray, 0); } int percentComplete = (int)(iChunkCount / (float)nBlocks * 100); onHashProgress?.Invoke(strPath, percentComplete); iOffSet += lChunkSize; nBytesRemaining = nBytes - iOffSet; if (nBytesRemaining < lChunkSize) { nBytesToRead = (int)nBytesRemaining; } } if (getMD5) { md5.TransformFinalBlock(ByteArray, 0, 0); } if (getSHA1) { sha1.TransformFinalBlock(ByteArray, 0, 0); } if (getCRC32) { crc32.TransformFinalBlock(ByteArray, 0, 0); } fs.Close(); onHashProgress?.Invoke(strPath, 100); if (getED2k) { //byte[] baHashFinal = md4.ComputeHash(baED2KHash); //rhash.ed2k = BitConverter.ToString(baHashFinal).Replace("-", string.Empty).ToUpper(); rhash.ED2K = nBlocks > 1 ? BitConverter.ToString(md4.ComputeHash(baED2KHash)).Replace("-", string.Empty).ToUpper() : BitConverter.ToString(baED2KHash).Replace("-", string.Empty).ToUpper(); } if (getCRC32) { rhash.CRC32 = BitConverter.ToString(crc32.Hash).Replace("-", string.Empty).ToUpper(); } if (getMD5) { rhash.MD5 = BitConverter.ToString(md5.Hash).Replace("-", string.Empty).ToUpper(); } if (getSHA1) { rhash.SHA1 = BitConverter.ToString(sha1.Hash).Replace("-", string.Empty).ToUpper(); } return(rhash); }
internal static bool VerifyChecksum(uint256 checksum, byte[] payload, int length) { return(checksum == Hashes.Hash256(payload, 0, length).GetLow32()); }
public ScriptId(Script script) : this(Hashes.Hash160(script._Script)) { }
public void ReadWrite(BitcoinStream stream) { if ((this.Payload == null) && stream.Serializing) { throw new InvalidOperationException("Payload not affected"); } if (stream.Serializing || (!stream.Serializing && !this.skipMagic)) { stream.ReadWrite(ref this.magic); } stream.ReadWrite(ref this.command); int length = 0; uint checksum = 0; bool hasChecksum = false; byte[] payloadBytes = stream.Serializing ? GetPayloadBytes(stream.ProtocolVersion, out length) : null; length = payloadBytes == null ? 0 : length; stream.ReadWrite(ref length); if (stream.ProtocolVersion >= ProtocolVersion.MEMPOOL_GD_VERSION) { if (stream.Serializing) { checksum = Hashes.Hash256(payloadBytes, 0, length).GetLow32(); } stream.ReadWrite(ref checksum); hasChecksum = true; } if (stream.Serializing) { stream.ReadWrite(ref payloadBytes, 0, length); } else { // MAX_SIZE 0x02000000 Serialize.h. if (length > 0x02000000) { throw new FormatException("Message payload too big ( > 0x02000000 bytes)"); } payloadBytes = (this.buffer == null) || (this.buffer.Length < length) ? new byte[length] : this.buffer; stream.ReadWrite(ref payloadBytes, 0, length); if (hasChecksum) { if (!VerifyChecksum(checksum, payloadBytes, length)) { if (NodeServerTrace.Trace.Switch.ShouldTrace(TraceEventType.Verbose)) { NodeServerTrace.Trace.TraceEvent(TraceEventType.Verbose, 0, "Invalid message checksum bytes"); } throw new FormatException("Message checksum invalid"); } } BitcoinStream payloadStream = new BitcoinStream(payloadBytes); payloadStream.CopyParameters(stream); Type payloadType = PayloadAttribute.GetCommandType(this.Command); bool unknown = payloadType == typeof(UnknowPayload); if (unknown) { NodeServerTrace.Trace.TraceEvent(TraceEventType.Warning, 0, "Unknown command received : " + this.Command); } object payload = this.payloadObject; payloadStream.ReadWrite(payloadType, ref payload); if (unknown) { ((UnknowPayload)payload).command = this.Command; } this.Payload = (Payload)payload; } }
public byte[] GetSharedSecret(Key key) { return(Hashes.SHA256(GetSharedPubkey(key).ToBytes())); }
public void key_test1() { BitcoinSecret bsecret1 = BitcoinNetwork.Main.CreateBitcoinSecret(strSecret1); BitcoinSecret bsecret2 = BitcoinNetwork.Main.CreateBitcoinSecret(strSecret2); BitcoinSecret bsecret1C = BitcoinNetwork.Main.CreateBitcoinSecret(strSecret1C); BitcoinSecret bsecret2C = BitcoinNetwork.Main.CreateBitcoinSecret(strSecret2C); Assert.Throws <FormatException>(() => BitcoinNetwork.Main.CreateBitcoinSecret(strAddressBad)); Key key1 = bsecret1.PrivateKey; Assert.True(key1.IsCompressed == false); Assert.True(bsecret1.Copy(true).PrivateKey.IsCompressed == true); Assert.True(bsecret1.Copy(true).Copy(false).IsCompressed == false); Assert.True(bsecret1.Copy(true).Copy(false).ToString() == bsecret1.ToString()); Key key2 = bsecret2.PrivateKey; Assert.True(key2.IsCompressed == false); Key key1C = bsecret1C.PrivateKey; Assert.True(key1C.IsCompressed == true); Key key2C = bsecret2C.PrivateKey; Assert.True(key1C.IsCompressed == true); PubKey pubkey1 = key1.PubKey; PubKey pubkey2 = key2.PubKey; PubKey pubkey1C = key1C.PubKey; PubKey pubkey2C = key2C.PubKey; Assert.True(addr1.Hash == pubkey1.Hash); Assert.True(addr2.Hash == pubkey2.Hash); Assert.True(addr1C.Hash == pubkey1C.Hash); Assert.True(addr2C.Hash == pubkey2C.Hash); for (int n = 0; n < 16; n++) { string strMsg = String.Format("Very secret message {0}: 11", n); if (n == 10) { //Test one long message strMsg = String.Join(",", Enumerable.Range(0, 2000).Select(i => i.ToString()).ToArray()); } uint256 hashMsg = Hashes.Hash256(TestUtils.ToBytes(strMsg)); // normal signatures ECDSASignature sign1 = null, sign2 = null, sign1C = null, sign2C = null; List <Task> tasks = new List <Task>(); tasks.Add(Task.Run(() => sign1 = key1.Sign(hashMsg))); tasks.Add(Task.Run(() => sign2 = key2.Sign(hashMsg))); tasks.Add(Task.Run(() => sign1C = key1C.Sign(hashMsg))); tasks.Add(Task.Run(() => sign2C = key2C.Sign(hashMsg))); Task.WaitAll(tasks.ToArray()); tasks.Clear(); tasks.Add(Task.Run(() => Assert.True(pubkey1.Verify(hashMsg, sign1)))); tasks.Add(Task.Run(() => Assert.True(pubkey2.Verify(hashMsg, sign2)))); tasks.Add(Task.Run(() => Assert.True(pubkey1C.Verify(hashMsg, sign1C)))); tasks.Add(Task.Run(() => Assert.True(pubkey2C.Verify(hashMsg, sign2C)))); Task.WaitAll(tasks.ToArray()); tasks.Clear(); tasks.Add(Task.Run(() => Assert.True(pubkey1.Verify(hashMsg, sign1)))); tasks.Add(Task.Run(() => Assert.True(!pubkey1.Verify(hashMsg, sign2)))); tasks.Add(Task.Run(() => Assert.True(pubkey1.Verify(hashMsg, sign1C)))); tasks.Add(Task.Run(() => Assert.True(!pubkey1.Verify(hashMsg, sign2C)))); tasks.Add(Task.Run(() => Assert.True(!pubkey2.Verify(hashMsg, sign1)))); tasks.Add(Task.Run(() => Assert.True(pubkey2.Verify(hashMsg, sign2)))); tasks.Add(Task.Run(() => Assert.True(!pubkey2.Verify(hashMsg, sign1C)))); tasks.Add(Task.Run(() => Assert.True(pubkey2.Verify(hashMsg, sign2C)))); tasks.Add(Task.Run(() => Assert.True(pubkey1C.Verify(hashMsg, sign1)))); tasks.Add(Task.Run(() => Assert.True(!pubkey1C.Verify(hashMsg, sign2)))); tasks.Add(Task.Run(() => Assert.True(pubkey1C.Verify(hashMsg, sign1C)))); tasks.Add(Task.Run(() => Assert.True(!pubkey1C.Verify(hashMsg, sign2C)))); tasks.Add(Task.Run(() => Assert.True(!pubkey2C.Verify(hashMsg, sign1)))); tasks.Add(Task.Run(() => Assert.True(pubkey2C.Verify(hashMsg, sign2)))); tasks.Add(Task.Run(() => Assert.True(!pubkey2C.Verify(hashMsg, sign1C)))); tasks.Add(Task.Run(() => Assert.True(pubkey2C.Verify(hashMsg, sign2C)))); Task.WaitAll(tasks.ToArray()); tasks.Clear(); // compact signatures (with key recovery) byte[] csign1 = null, csign2 = null, csign1C = null, csign2C = null; tasks.Add(Task.Run(() => csign1 = key1.SignCompact(hashMsg))); tasks.Add(Task.Run(() => csign2 = key2.SignCompact(hashMsg))); tasks.Add(Task.Run(() => csign1C = key1C.SignCompact(hashMsg))); tasks.Add(Task.Run(() => csign2C = key2C.SignCompact(hashMsg))); Task.WaitAll(tasks.ToArray()); tasks.Clear(); PubKey rkey1 = null, rkey2 = null, rkey1C = null, rkey2C = null; tasks.Add(Task.Run(() => rkey1 = PubKey.RecoverCompact(hashMsg, csign1))); tasks.Add(Task.Run(() => rkey2 = PubKey.RecoverCompact(hashMsg, csign2))); tasks.Add(Task.Run(() => rkey1C = PubKey.RecoverCompact(hashMsg, csign1C))); tasks.Add(Task.Run(() => rkey2C = PubKey.RecoverCompact(hashMsg, csign2C))); Task.WaitAll(tasks.ToArray()); tasks.Clear(); Assert.True(rkey1.ToHex() == pubkey1.ToHex()); Assert.True(rkey2.ToHex() == pubkey2.ToHex()); Assert.True(rkey1C.ToHex() == pubkey1C.ToHex()); Assert.True(rkey2C.ToHex() == pubkey2C.ToHex()); } }
private void comboBox1_DropDownClosed(object sender, EventArgs e) { chooseHash = (Hashes)Enum.Parse(typeof(Hashes), comboBox1.Text); }
public static Gen <uint256> Hash256() => PrimitiveGenerator.RandomBytes().Select(bs => Hashes.Hash256(bs));
public virtual IEnumerable <SubFingerprintData> Query(Hashes hashes, QueryConfiguration config) { var queryHashes = hashes.Select(_ => _.HashBins).ToList(); return(queryHashes.Any() ? SubFingerprintDao.ReadSubFingerprints(queryHashes, config) : Enumerable.Empty <SubFingerprintData>()); }
protected static Hashes CalculateHashes_here(string strPath, OnHashProgress onHashProgress) { FileStream fs; Hashes rhash=new Hashes(); FileInfo fi = new FileInfo(strPath); fs = fi.OpenRead(); int lChunkSize = 9728000; //string sHash = ""; long nBytes = (long)fs.Length; long nBytesRemaining = (long)fs.Length; int nBytesToRead = 0; long nBlocks = nBytes / lChunkSize; long nRemainder = nBytes % lChunkSize; //mod if (nRemainder > 0) nBlocks++; byte[] baED2KHash = new byte[16 * nBlocks]; if (nBytes > lChunkSize) nBytesToRead = lChunkSize; else nBytesToRead = (int)nBytesRemaining; if (onHashProgress != null) onHashProgress(strPath, 0); MD4 md4 = MD4.Create(); MD5 md5 = MD5.Create(); SHA1 sha1 = SHA1.Create(); Crc32 crc32=new Crc32(); byte[] ByteArray = new byte[nBytesToRead]; long iOffSet = 0; long iChunkCount = 0; while (nBytesRemaining > 0) { iChunkCount++; Console.WriteLine("Hashing Chunk: " + iChunkCount.ToString()); int nBytesRead = fs.Read(ByteArray, 0, nBytesToRead); byte[] baHash = md4.ComputeHash(ByteArray, 0, nBytesRead); md5.TransformBlock(ByteArray, 0, nBytesRead, ByteArray, 0); sha1.TransformBlock(ByteArray, 0, nBytesRead, ByteArray, 0); crc32.TransformBlock(ByteArray, 0, nBytesRead, ByteArray, 0); int percentComplete = (int)((float)iChunkCount / (float)nBlocks * 100); if (onHashProgress != null) onHashProgress(strPath, percentComplete); int j = (int)((iChunkCount - 1) * 16); for (int i = 0; i < 16; i++) baED2KHash[j + i] = baHash[i]; iOffSet += lChunkSize; nBytesRemaining = nBytes - iOffSet; if (nBytesRemaining < lChunkSize) nBytesToRead = (int)nBytesRemaining; } md5.TransformFinalBlock(ByteArray, 0, 0); sha1.TransformFinalBlock(ByteArray, 0, 0); crc32.TransformFinalBlock(ByteArray, 0, 0); fs.Close(); if (onHashProgress != null) onHashProgress(strPath, 100); byte[] baHashFinal = md4.ComputeHash(baED2KHash); rhash.ed2k = BitConverter.ToString(baHashFinal).Replace("-", "").ToUpper(); rhash.crc32 = BitConverter.ToString(crc32.Hash).Replace("-", "").ToUpper(); rhash.md5 = BitConverter.ToString(md5.Hash).Replace("-", "").ToUpper(); rhash.sha1 = BitConverter.ToString(sha1.Hash).Replace("-", "").ToUpper(); return rhash; }
public static Gen <uint160> Hash160() => PrimitiveGenerator.RandomBytes().Select(bs => Hashes.Hash160(bs));
/// <summary> /// Computes the cryptographic hash of an input string over a specified number of /// iterations and returns a Base64-encoded result. This version defaults to using the /// UTF-8 encoding. /// </summary> /// <param name="hash">The cryptographic hash algorithm to use, specified by one of /// the <see cref="Hashes"/> enumeration values.</param> /// <param name="text">The input string to hash. The system default encoding is /// assumed with this version of this method.</param> /// <param name="count">An iteration count. The hash will be applied to the string /// this many times. This must be a positive integer.</param> /// <returns>A Base64-encoded string representing the hash of the input string</returns> /// <exception cref="HashEngineException">Thrown whenever anything bad happens when the /// hash is computed</exception> public static string HashString(Hashes hash, string text, int count) { return HashString(hash, Encoding.UTF8, text, count); }
/// <summary> /// Executes a method on the resource. The default behaviour is to call the corresponding execution methods defined in the specialized /// interfaces <see cref="IHttpGetMethod"/>, <see cref="IHttpPostMethod"/>, <see cref="IHttpPutMethod"/> and <see cref="IHttpDeleteMethod"/> /// if they are defined for the resource. /// </summary> /// <param name="Server">HTTP Server</param> /// <param name="Request">HTTP Request</param> /// <param name="Response">HTTP Response</param> /// <exception cref="HttpException">If an error occurred when processing the method.</exception> public virtual async Task Execute(HttpServer Server, HttpRequest Request, HttpResponse Response) { HttpRequestHeader Header = Request.Header; string Method = Request.Header.Method; if (this.UserSessions && Request.Session is null) { HttpFieldCookie Cookie; string HttpSessionID; if ((Cookie = Request.Header.Cookie) is null || string.IsNullOrEmpty(HttpSessionID = Cookie["HttpSessionID"])) { HttpSessionID = Convert.ToBase64String(Hashes.ComputeSHA512Hash(Guid.NewGuid().ToByteArray())); Response.SetCookie(new Cookie("HttpSessionID", HttpSessionID, null, "/", null, false, true)); } Request.Session = Server.GetSession(HttpSessionID); } switch (Method) { case "GET": case "HEAD": if (this.getRanges != null) { Response.SetHeader("Accept-Ranges", "bytes"); if (Header.Range != null) { ByteRangeInterval FirstInterval = Header.Range.FirstInterval; if (FirstInterval is null) { throw new RangeNotSatisfiableException(); } else { Response.OnlyHeader = Method == "HEAD"; Response.StatusCode = 206; Response.StatusMessage = "Partial Content"; await this.getRanges.GET(Request, Response, FirstInterval); } } else { Response.OnlyHeader = Method == "HEAD"; if (this.get != null) { await this.get.GET(Request, Response); } else { await this.getRanges.GET(Request, Response, new ByteRangeInterval(0, null)); } } } else if (this.get != null) { Response.OnlyHeader = Method == "HEAD"; await this.get.GET(Request, Response); } else { throw new MethodNotAllowedException(this.allowedMethods); } break; case "POST": if (this.postRanges != null) { if (Header.ContentRange != null) { ContentByteRangeInterval Interval = Header.ContentRange.Interval; if (Interval is null) { throw new RangeNotSatisfiableException(); } else { await this.postRanges.POST(Request, Response, Interval); } } else { if (this.post != null) { await this.post.POST(Request, Response); } else { long Total; if (Header.ContentLength != null) { Total = Header.ContentLength.ContentLength; } else if (Request.DataStream != null) { Total = Request.DataStream.Position; } else { Total = 0; } await this.postRanges.POST(Request, Response, new ContentByteRangeInterval(0, Total - 1, Total)); } } } else if (this.post != null) { await this.post.POST(Request, Response); } else { throw new MethodNotAllowedException(this.allowedMethods); } break; case "PUT": if (this.putRanges != null) { if (Header.ContentRange != null) { ContentByteRangeInterval Interval = Header.ContentRange.Interval; if (Interval is null) { throw new RangeNotSatisfiableException(); } else { await this.putRanges.PUT(Request, Response, Interval); } } else { if (this.put != null) { await this.put.PUT(Request, Response); } else { long Total; if (Header.ContentLength != null) { Total = Header.ContentLength.ContentLength; } else if (Request.DataStream != null) { Total = Request.DataStream.Position; } else { Total = 0; } await this.putRanges.PUT(Request, Response, new ContentByteRangeInterval(0, Total - 1, Total)); } } } else if (this.put != null) { await this.put.PUT(Request, Response); } else { throw new MethodNotAllowedException(this.allowedMethods); } break; case "DELETE": if (this.delete is null) { throw new MethodNotAllowedException(this.allowedMethods); } else { await this.delete.DELETE(Request, Response); } break; case "OPTIONS": if (this.options is null) { throw new MethodNotAllowedException(this.allowedMethods); } else { await this.options.OPTIONS(Request, Response); } break; case "TRACE": if (this.trace is null) { throw new MethodNotAllowedException(this.allowedMethods); } else { await this.trace.TRACE(Request, Response); } break; default: throw new MethodNotAllowedException(this.allowedMethods); } if (this.Synchronous) { await Response.SendResponse(); Response.Dispose(); } }
/// <summary> /// Executes the GET method on the resource. /// </summary> /// <param name="Request">HTTP Request</param> /// <param name="Response">HTTP Response</param> /// <exception cref="HttpException">If an error occurred when processing the method.</exception> public async Task GET(HttpRequest Request, HttpResponse Response) { if (!Request.Header.TryGetHeaderField("Upgrade", out HttpField Upgrade) || Upgrade.Value != "websocket") { throw new UpgradeRequiredException("websocket"); } string Challenge; string WebSocketProtocol = null; int? WebSocketVersion; int i; if (Request.Header.TryGetHeaderField("Sec-WebSocket-Key", out HttpField Field)) { Challenge = Field.Value; } else { throw new BadRequestException(); } if (Request.Header.TryGetHeaderField("Sec-WebSocket-Protocol", out Field)) { string[] Options = Field.Value.Split(','); foreach (string Option in Options) { i = Array.IndexOf <string>(this.subProtocols, Option.Trim().ToLower()); if (i >= 0) { WebSocketProtocol = this.subProtocols[i]; break; } } if (WebSocketProtocol is null) { throw new NotSupportedException(); } } if (Request.Header.TryGetHeaderField("Sec-WebSocket-Version", out Field) && int.TryParse(Field.Value, out i)) { if (i < 13) { throw new PreconditionFailedException(); } WebSocketVersion = i; } else { throw new BadRequestException(); } if (Request.Header.TryGetHeaderField("Sec-WebSocket-Extensions", out Field)) { // TODO: §9.1 } if (Request.clientConnection is null) { throw new ForbiddenException("Invalid connection."); } WebSocket Socket = new WebSocket(this, Request, Response); this.Accept?.Invoke(this, new WebSocketEventArgs(Socket)); string ChallengeResponse = Convert.ToBase64String(Hashes.ComputeSHA1Hash( Encoding.UTF8.GetBytes(Challenge.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"))); Response.StatusCode = 101; Response.StatusMessage = "Switching Protocols"; Response.SetHeader("Upgrade", "websocket"); Response.SetHeader("Connection", "Upgrade"); Response.SetHeader("Sec-WebSocket-Accept", ChallengeResponse); if (WebSocketProtocol != null) { Response.SetHeader("Sec-WebSocket-Protocol", WebSocketProtocol); } Request.clientConnection.Upgrade(Socket); await Response.SendResponse(); this.Connected?.Invoke(this, new WebSocketEventArgs(Socket)); }
public static Hashes GetHashes() { Hashes h = new Hashes(); if (h.LoadHashesFromNet()) { return h; } return null; }
/// <summary> /// Given a <see cref="Hashes"/> enumeration object, convert it to a user-friendly /// string suitable for display. This is also used for compatibility when exporting /// site parameters to the cross-platform export file format. /// </summary> /// <param name="hash">A <see cref="Hashes"/> enumeration object</param> /// <returns>A user-friendly display string representing the hash</returns> public static string HashEnumToDisplayHash(Hashes hash) { string displayHash = null; switch (hash) { case Hashes.MD5: displayHash = "MD-5"; break; case Hashes.RIPEMD160: displayHash = "RIPEMD-160"; break; case Hashes.SHA1: displayHash = "SHA-1"; break; case Hashes.SHA256: displayHash = "SHA-256"; break; case Hashes.SHA384: displayHash = "SHA-384"; break; case Hashes.SHA512: displayHash = "SHA-512"; break; case Hashes.Tiger: case Hashes.Whirlpool: displayHash = hash.ToString(); break; default: break; } return displayHash; }