示例#1
0
        internal string CreateUserHash(HttpContext context)
        {
            ReadOnlySpan <byte> saltSpan = m_saltProvider.GetSalt();

            using IMemoryOwner <byte> uidMemoryOwner = MemoryPool <byte> .Shared.Rent(m_maxIdentitySize + saltSpan.Length);

            Span <byte> uidSpan = uidMemoryOwner.Memory.Span;

            uidSpan.Fill(0);

            int identityBytesWritten = -1;

            foreach (IUserIdentityProvider provider in m_userIdentityProviders)
            {
                if (provider.TryWriteBytes(context, uidSpan.Slice(0, provider.MaxBytesInIdentity), out identityBytesWritten))
                {
                    break;
                }
            }

            if (identityBytesWritten <= 0)
            {
                return(string.Empty);
            }

            saltSpan.CopyTo(uidSpan.Slice(identityBytesWritten));

            using IMemoryOwner <byte> hashMemoryOwner = MemoryPool <byte> .Shared.Rent(HashSize);

            Span <byte> hashSpan = hashMemoryOwner.Memory.Span;

#if NETCOREAPP3_1
            using HashAlgorithm hashAlgorithm = new SHA256Managed();             // need to have new instance each time since its not thread-safe

            if (!hashAlgorithm.TryComputeHash(uidSpan, hashSpan, out _))
            {
                return(string.Empty);
            }

            return(BitConverter.ToString(hashSpan.ToArray()).Replace("-", ""));
#else
            SHA256.HashData(uidSpan, hashSpan);

            return(Convert.ToHexString(hashSpan));
#endif
        }
        internal string CreateUserHash(HttpContext context)
        {
            ReadOnlySpan <byte> saltSpan = m_saltProvider.GetSalt();

            using IMemoryOwner <byte> uidMemoryOwner = MemoryPool <byte> .Shared.Rent(m_maxIdentitySize + saltSpan.Length);

            Span <byte> uidSpan = uidMemoryOwner.Memory.Span;

            int         identityBytesWritten = -1;
            Span <byte> identitySpan         = uidSpan.Slice(0, m_maxIdentitySize);

            foreach (IUserIdentityProvider provider in m_userIdentityProviders)
            {
                if (provider.TryWriteBytes(context, identitySpan, out identityBytesWritten))
                {
                    break;
                }
            }

            if (identityBytesWritten <= 0)
            {
                return(string.Empty);
            }

            saltSpan.CopyTo(uidSpan.Slice(identityBytesWritten));

            using IMemoryOwner <byte> hashMemoryOwner = MemoryPool <byte> .Shared.Rent(HashSize);

            Span <byte> hashSpan = hashMemoryOwner.Memory.Span;

            if (!m_hashAlgorithm.TryComputeHash(uidSpan, hashSpan, out int hashBytesWritten))
            {
                return(string.Empty);
            }

#if NETCOREAPP3_1
            return(BitConverter.ToString(hashSpan.ToArray()).Replace("-", ""));
#else
            return(Convert.ToHexString(hashSpan));
#endif
        }