示例#1
0
        public static bool TryComputeHash(ReadOnlySequence <byte> sequence, ReadOnlySpan <byte> key, Span <byte> destination)
        {
            if (destination.Length < 32)
            {
                throw new ArgumentOutOfRangeException(nameof(destination));
            }

            Span <byte> extendedKey = stackalloc byte[_blockLength];

            if (key.Length > _blockLength)
            {
                Sha2_256.TryComputeHash(key, extendedKey);
            }
            else
            {
                BytesOperations.Copy(key, extendedKey, Math.Min(key.Length, extendedKey.Length));
            }

            Span <byte> ixor = stackalloc byte[_blockLength];

            BytesOperations.Xor(_ipad, extendedKey, ixor);

            Span <byte> oxor = stackalloc byte[_blockLength];

            BytesOperations.Xor(_opad, extendedKey, oxor);

            Span <byte> ihash = stackalloc byte[32];

            using (var incrementalHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256))
            {
                incrementalHash.AppendData(ixor);

                foreach (var segment in sequence)
                {
                    incrementalHash.AppendData(segment.Span);
                }

                incrementalHash.TryGetHashAndReset(ihash, out _);
            }

            using (var incrementalHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256))
            {
                incrementalHash.AppendData(oxor);
                incrementalHash.AppendData(ihash);

                return(incrementalHash.TryGetHashAndReset(destination, out _));
            }
        }
示例#2
0
 public static bool Verify(ReadOnlyMemory <byte> publicKey, ReadOnlyMemory <byte> signature, ReadOnlySequence <byte> sequence)
 {
     using var ecdsa = ECDsa.Create();
     ecdsa.ImportSubjectPublicKeyInfo(publicKey.Span, out var _);
     return(ecdsa.VerifyHash(Sha2_256.ComputeHash(sequence).AsSpan(), signature.Span));
 }
示例#3
0
 public static byte[] Sign(ReadOnlyMemory <byte> privateKey, ReadOnlySequence <byte> sequence)
 {
     using var ecdsa = ECDsa.Create();
     ecdsa.ImportPkcs8PrivateKey(privateKey.Span, out var _);
     return(ecdsa.SignHash(Sha2_256.ComputeHash(sequence)));
 }