public static uint Verify(OmniHashcash hashcash, ReadOnlySequence <byte> sequence, ReadOnlyMemory <byte> key) { if (hashcash is null) { throw new ArgumentNullException(nameof(hashcash)); } if (hashcash.AlgorithmType == OmniHashcashAlgorithmType.Simple_Sha2_256) { var target = Hmac_Sha2_256.ComputeHash(sequence, key.Span); return(MinerHelper.Verify_Simple_Sha2_256(hashcash.Key.Span, target)); } return(0); }
public static bool TryComputeHash(ReadOnlySpan <byte> password, ReadOnlySpan <byte> salt, int iterationCount, Span <byte> destination) { const int hashLength = 32; int keyLength = destination.Length / hashLength; if (destination.Length % hashLength != 0) { keyLength++; } var extendedkeyLength = (salt.Length + 4); Span <byte> extendedkey = extendedkeyLength <= 128 ? stackalloc byte[extendedkeyLength] : new byte[extendedkeyLength]; BytesOperations.Copy(salt, extendedkey, salt.Length); for (int i = 0; i < keyLength; i++) { extendedkey[salt.Length] = (byte)(((i + 1) >> 24) & 0xFF); extendedkey[salt.Length + 1] = (byte)(((i + 1) >> 16) & 0xFF); extendedkey[salt.Length + 2] = (byte)(((i + 1) >> 8) & 0xFF); extendedkey[salt.Length + 3] = (byte)(((i + 1)) & 0xFF); Span <byte> f = stackalloc byte[hashLength]; Span <byte> u = stackalloc byte[hashLength]; Hmac_Sha2_256.TryComputeHash(extendedkey, password, u); BytesOperations.Zero(extendedkey.Slice(salt.Length, 4)); BytesOperations.Copy(u, f, hashLength); for (int j = 1; j < iterationCount; j++) { Hmac_Sha2_256.TryComputeHash(u, password, u); BytesOperations.Xor(f, u, f); } int position = i * hashLength; int remain = Math.Min(hashLength, destination.Length - position); BytesOperations.Copy(f, destination.Slice(position), remain); } return(true); }
public static async ValueTask <OmniHashcash> Create(ReadOnlySequence <byte> sequence, ReadOnlyMemory <byte> key, OmniHashcashAlgorithmType hashcashAlgorithmType, int limit, TimeSpan timeout, CancellationToken token) { if (!EnumHelper.IsValid(hashcashAlgorithmType)) { throw new ArgumentException(nameof(OmniHashcashAlgorithmType)); } return(await Task.Run(() => { if (hashcashAlgorithmType == OmniHashcashAlgorithmType.Simple_Sha2_256) { var target = Hmac_Sha2_256.ComputeHash(sequence, key.Span); var hashcashKey = MinerHelper.Compute_Simple_Sha2_256(target, limit, timeout, token); return new OmniHashcash(OmniHashcashAlgorithmType.Simple_Sha2_256, hashcashKey); } throw new NotSupportedException(nameof(hashcashAlgorithmType)); }, token)); }