示例#1
0
        /// <summary>
        /// This an optimized version of doing HttpUtility.UrlEncode(Convert.ToBase64String(hashPayLoad)).
        /// This avoids the over head of converting it to a string and back to a byte[].
        /// </summary>
        private static unsafe string OptimizedConvertToBase64string(byte[] hashPayLoad)
        {
            // Create a large enough buffer that URL encode can use it.
            // Increase the buffer by 3x so it can be used for the URL encoding
            int capacity = Base64.GetMaxEncodedToUtf8Length(hashPayLoad.Length) * 3;

            byte[] rentedBuffer = ArrayPool <byte> .Shared.Rent(capacity);

            try
            {
                Span <byte> encodingBuffer = rentedBuffer;
                // This replaces the Convert.ToBase64String
                OperationStatus status = Base64.EncodeToUtf8(
                    hashPayLoad,
                    encodingBuffer,
                    out int _,
                    out int bytesWritten);

                if (status != OperationStatus.Done)
                {
                    throw new ArgumentException($"Authorization key payload is invalid. {status}");
                }

                return(AuthorizationHelper.UrlEncodeBase64SpanInPlace(encodingBuffer, bytesWritten));
            }
            finally
            {
                if (rentedBuffer != null)
                {
                    ArrayPool <byte> .Shared.Return(rentedBuffer);
                }
            }
        }