/// <summary> /// Computes hash value for given data. /// </summary> /// <param name="hashFunction">Hash function to use.</param> /// <param name="data">Data to be hashed.</param> /// <param name="desiredHashSize">Desired size of resulting hash, in bits.</param> /// <returns> /// Hash value of the data as byte array. /// </returns> public static byte[] ComputeHash(this IHashFunction hashFunction, byte[] data, int desiredHashSize) { var hash = new BigInteger(); var desiredHashBytes = (desiredHashSize + 7) / 8; var seededData = new byte[data.Length + 4]; Array.Copy(data, 0, seededData, 4, data.Length); var hashesNeeded = (desiredHashSize + (hashFunction.HashSize - 1)) / hashFunction.HashSize; // Compute as many hashes as needed for (int x = 0; x < Math.Max(hashesNeeded, 1); ++x) { byte[] currentData; if (x != 0) { Array.Copy(BitConverter.GetBytes(x), seededData, 4); currentData = seededData; } else { // Use original data for first currentData = data; } var elementHash = new BigInteger( hashFunction.ComputeHash(currentData) .Concat(new[] { (byte)0 }) .ToArray()); hash |= elementHash << (x * hashFunction.HashSize); } // XOr-fold the extra bits if (hashesNeeded * hashFunction.HashSize != desiredHashSize) { var mask = ((new BigInteger(1) << desiredHashSize) - 1); hash = (hash ^ (hash >> desiredHashSize)) & mask; } // Convert to array that contains desiredHashSize bits var hashBytes = hash.ToByteArray(); // Account for missing or extra bytes. if (hashBytes.Length != desiredHashBytes) { var buffer = new byte[desiredHashBytes]; Array.Copy(hashBytes, buffer, Math.Min(hashBytes.Length, desiredHashBytes)); hashBytes = buffer; } return(hashBytes); }
static byte[] ComputeHash(string destinationFilePath, IHashFunction hashFunction) { using (var fileStream = new BufferedStream(File.OpenRead(destinationFilePath), DefaultBufferChunkSize)) { return(hashFunction.ComputeHash(fileStream)); } }
//public void SetToMultiSig(int m, int n, Tuple<PublicKey, bool>[] pubKeyList) //{ // if (m < 1 || m > 16 || m > n) // throw new ArgumentOutOfRangeException(nameof(m), "M must be between 1 and 16 and smaller than N."); // if (n < 1 || n > 16) // throw new ArgumentOutOfRangeException(nameof(n), "N must be between 1 and 16."); // if (pubKeyList == null || pubKeyList.Length == 0) // throw new ArgumentNullException(nameof(pubKeyList), "Pubkey list can not be null or empty."); // if (pubKeyList.Length != n) // throw new ArgumentOutOfRangeException(nameof(pubKeyList), $"Pubkey list must contain N (={n}) items."); // OperationList = new IOperation[n + 3]; // OP_m | pub1 | pub2 | ... | pub(n) | OP_n | OP_CheckMultiSig // OperationList[0] = new PushDataOp(m); // OperationList[n + 1] = new PushDataOp(n); // OperationList[n + 2] = new CheckMultiSigOp(); // int i = 1; // foreach (var item in pubKeyList) // { // OperationList[i++] = new PushDataOp(item.Item1.ToByteArray(item.Item2)); // } //} //public void SetToP2SH_P2WPKH(PublicKey pubKey) //{ // byte[] hash = hashFunc.ComputeHash(pubKey.ToByteArray(true)); // Always use compressed // OperationList = new IOperation[] // { // new PushDataOp(OP._0), // new PushDataOp(hash) // }; //} public void SetToP2SH_P2WSH(Script witnessScript) { byte[] hash = witHashFunc.ComputeHash(witnessScript.ToByteArray()); OperationList = new IOperation[] { new PushDataOp(OP._0), new PushDataOp(hash) }; }
/// <summary> /// Computes hash value for given data. /// </summary> /// <typeparam name="ModelT">Type of data to be hashed.</typeparam> /// <param name="hashFunction">Hash function to use.</param> /// <param name="data">Data to be hashed.</param> /// <returns> /// Hash value of the data as byte array. /// </returns> /// <remarks> /// <see cref="BinaryFormatter"/> is used to turn given data into a byte array. /// </remarks> public static byte[] ComputeHash <ModelT>(this IHashFunction hashFunction, ModelT data) { using (var memoryStream = new MemoryStream()) { var binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(memoryStream, data); return(hashFunction.ComputeHash( memoryStream.ToArray())); } }
/// <summary> /// Computes hash value for given data. /// </summary> /// <typeparam name="ModelT">Type of data to be hashed.</typeparam> /// <param name="hashFunction">Hash function to use.</param> /// <param name="data">Data to be hashed.</param> /// <param name="desiredHashSize">Desired size of resulting hash, in bits.</param> /// <returns> /// Hash value of the data as byte array. /// </returns> /// <remarks> /// <see cref="BinaryFormatter"/> is used to turn given data into a byte array. /// </remarks> public static IHashValue ComputeHash <ModelT>(this IHashFunction hashFunction, ModelT data, int desiredHashSize) { using (var memoryStream = new MemoryStream()) { var binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(memoryStream, data); return(hashFunction.ComputeHash( memoryStream.ToArray(), desiredHashSize)); } }
/// <summary> /// Decrypts the given base-58 encoded encrypted key using the given password bytes and first 4 bytes of hash of /// (un)compressed P2PKH address as <see cref="Scrypt"/> salt. /// </summary> /// <exception cref="ArgumentNullException"/> /// <exception cref="FormatException"/> /// <exception cref="ObjectDisposedException"/> /// <param name="encrypted">Base-58 encrypted key (it will be normalized using Unicode Normalization Form C (NFC))</param> /// <param name="password">Password to use</param> /// <param name="isCompressed">Indicates whether to use compressed or uncompressed public key to build P2PKH address</param> /// <returns>The private key</returns> public PrivateKey Decrypt(string encrypted, byte[] password, out bool isCompressed) { if (isDisposed) { throw new ObjectDisposedException(nameof(BIP0038), "Instance was disposed."); } if (string.IsNullOrWhiteSpace(encrypted)) { throw new ArgumentNullException(nameof(encrypted), "Invalid (null) encrypted key."); } if (password == null) { throw new ArgumentNullException(nameof(password), "Password can not be null."); } byte[] encryptedBytes = b58enc.DecodeWithCheckSum(encrypted); if (encryptedBytes.Length != EncodedLength) { throw new FormatException("Invalid encrypted bytes length."); } if (!((Span <byte>)encryptedBytes).Slice(0, 2).SequenceEqual(prefix)) { throw new FormatException("Invalid prefix."); } isCompressed = IsCompressed(encryptedBytes[2]); Span <byte> salt = ((Span <byte>)encryptedBytes).Slice(3, 4); byte[] dk = scrypt.GetBytes(password, salt.ToArray(), 64); byte[] decryptedResult = new byte[32]; aes.Key = dk.SubArray(32, 32); // AES key is derivedhalf2 using ICryptoTransform decryptor = aes.CreateDecryptor(); decryptor.TransformBlock(encryptedBytes, 7, 16, decryptedResult, 0); decryptor.TransformBlock(encryptedBytes, 23, 16, decryptedResult, 16); // XOR method will only work on first item's length (32 byte here) so it doesn't matter of dk.Legth is 64 PrivateKey result = new PrivateKey(XOR(decryptedResult, dk)); string address = addressMaker.GetP2pkh(result.ToPublicKey(), isCompressed, NetworkType.MainNet); Span <byte> computedHash = hash.ComputeHash(Encoding.ASCII.GetBytes(address)).SubArray(0, 4); if (!computedHash.SequenceEqual(salt)) { throw new FormatException("Wrong password (derived address hash is not the same)."); } return(result); }
private uint[] GroupHashes(uint[] result) { if (_groupSize < 2) { return(result); } var groupedResult = new uint[_hashCount / _groupSize]; var bytes = new byte[_groupSize * sizeof(uint)]; for (var i = 0; i < groupedResult.Length; i++) { Buffer.BlockCopy(result, i * _groupSize * sizeof(uint), bytes, 0, bytes.Length); var hash = _groupHashFunction.ComputeHash(bytes); groupedResult[i] = BitConverter.ToUInt32(hash.Hash, 0); } return(groupedResult); }
/// <summary> /// Creates a unique key to identify a query expression. /// </summary> /// <param name="expression">Query expression</param> /// <param name="parameterValues">Query parameter values</param> /// <returns>Unique key object</returns> public object CreateQueryKey(Expression expression, IReadOnlyDictionary <string, object> parameterValues) { // use internal hash cide to identify base query var expressionHashCode = ExpressionEqualityComparer.Instance.GetHashCode(expression); // creating a Uniform Resource Identifier var expressionCacheKey = $"hash://{expressionHashCode}"; // if query has parameter add key values as uri-query string if (parameterValues.Count > 0) { var parameterStrings = parameterValues.Select(d => $"{d.Key}={d.Value?.GetHashCode()}"); expressionCacheKey += $"?{String.Join("&", parameterStrings)}"; } var hash = __hashFunction.ComputeHash(expressionCacheKey); return(hash.AsBase64String()); }
public async Task <AudioFileModel> UploadFile(byte[] content, string filename, string folderpath) { var hash = BitConverter.ToString(_hasher.ComputeHash(content)).Replace("-", ""); var fullname = Path.Combine(folderpath, hash); if (!File.Exists(fullname)) { File.WriteAllBytes(fullname, content); } var entity = new AudioFile { CreatedAt = DateTime.Now, DisplayName = filename, Hash = hash }; entity = _audioFileRepository.Add(entity); await _uow.CommitAsync(); return(_mapper.Map <AudioFile, AudioFileModel>(entity)); }
private string Hash(string fragment) => Urlfy(_cityHash.ComputeHash(Encoding.UTF8.GetBytes(fragment), 256).AsHexString());
/// <summary> /// Computes hash value for given data. /// </summary> /// <param name="hashFunction">Hash function to use.</param> /// <param name="data">Data to be hashed.</param> /// <returns> /// Hash value of the data as byte array. /// </returns> public static byte[] ComputeHash(this IHashFunction hashFunction, int data) { return(hashFunction.ComputeHash( BitConverter.GetBytes(data))); }
private int ComputeHash(T element, int spacing) { return(Math.Abs((FirstHashFunction.ComputeHash(element) + spacing * SecondHashFunction.ComputeHash(element)) % SizeOfBitArray)); }
/// <summary> /// Computes hash value for given data. /// </summary> /// <param name="hashFunction">Hash function to use.</param> /// <param name="data">Data to be hashed.</param> /// <param name="desizedHashSize">Desired size of resulting hash, in bits.</param> /// <returns> /// Hash value of the data as byte array. /// </returns> public static byte[] ComputeHash(this IHashFunction hashFunction, ushort data, int desizedHashSize) { return(hashFunction.ComputeHash( BitConverter.GetBytes(data), desizedHashSize)); }
/// <summary> /// Computes hash value for given data. /// </summary> /// <param name="hashFunction">Hash function to use.</param> /// <param name="data">Data to be hashed.</param> /// <returns> /// Hash value of the data as byte array. /// </returns> public static byte[] ComputeHash(this IHashFunction hashFunction, byte data) { return(hashFunction.ComputeHash( new[] { data })); }
/// <summary> /// Computes hash value for given data. /// </summary> /// <param name="hashFunction">Hash function to use.</param> /// <param name="data">Data to be hashed.</param> /// <param name="desizedHashSize">Desired size of resulting hash, in bits.</param> /// <returns> /// Hash value of the data as byte array. /// </returns> /// <remarks> /// UTF-8 encoding used to convert string to bytes. /// </remarks> public static byte[] ComputeHash(this IHashFunction hashFunction, string data, int desizedHashSize) { return(hashFunction.ComputeHash( Encoding.UTF8.GetBytes(data), desizedHashSize)); }
/// <summary> /// Computes hash value for given data. /// </summary> /// <param name="hashFunction">Hash function to use.</param> /// <param name="data">Data to be hashed.</param> /// <param name="desizedHashSize">Desired size of resulting hash, in bits.</param> /// <returns> /// Hash value of the data as byte array. /// </returns> public static byte[] ComputeHash(this IHashFunction hashFunction, sbyte data, int desizedHashSize) { return(hashFunction.ComputeHash( new[] { (byte)data }, desizedHashSize)); }
/// <summary> /// Computes hash value for given data. /// </summary> /// <param name="hashFunction">Hash function to use.</param> /// <param name="data">Data to be hashed.</param> /// <returns> /// Hash value of the data as byte array. /// </returns> public static IHashValue ComputeHash(this IHashFunction hashFunction, sbyte data) { return(hashFunction.ComputeHash( new[] { (byte)data })); }
/// <summary> /// Computes hash value for given data. /// </summary> /// <param name="hashFunction">Hash function to use.</param> /// <param name="data">Data to be hashed.</param> /// <returns> /// Hash value of the data as byte array. /// </returns> /// <remarks> /// UTF-8 encoding used to convert string to bytes. /// </remarks> public static byte[] ComputeHash(this IHashFunction hashFunction, string data) { return(hashFunction.ComputeHash( Encoding.UTF8.GetBytes(data))); }
private byte[] CalculateCheckSum(byte[] data) { return(hash.ComputeHash(data).SubArray(0, CheckSumSize)); }
/// <summary> /// Computes hash value for given data. /// </summary> /// <param name="hashFunction">Hash function to use.</param> /// <param name="data">Data to be hashed.</param> /// <returns> /// Hash value of the data as byte array. /// </returns> public static IHashValue ComputeHash(this IHashFunction hashFunction, float data) { return(hashFunction.ComputeHash( BitConverter.GetBytes(data))); }
/// <summary> /// Computes hash value for given data. /// </summary> /// <param name="hashFunction">Hash function to use.</param> /// <param name="data">Data to be hashed.</param> /// <param name="desiredHashSize">Desired size of resulting hash, in bits.</param> /// <returns> /// Hash value of the data as byte array. /// </returns> public static IHashValue ComputeHash(this IHashFunction hashFunction, byte data, int desiredHashSize) { return(hashFunction.ComputeHash( new[] { data }, desiredHashSize)); }
/// <summary> /// Computes hash value for given data. /// </summary> /// <param name="hashFunction">Hash function to use.</param> /// <param name="data">Data to be hashed.</param> /// <param name="desiredHashSize">Desired size of resulting hash, in bits.</param> /// <returns> /// Hash value of the data as byte array. /// </returns> public static IHashValue ComputeHash(this IHashFunction hashFunction, ulong data, int desiredHashSize) { return(hashFunction.ComputeHash( BitConverter.GetBytes(data), desiredHashSize)); }