Example #1
0
        public void EnumerateObjects_NoAnObject_Fail()
        {
            JwtHeaderDocument.TryParseHeader(Utf8.GetBytes("{\"object\":[1, 2, 3, 4, 5]}"), null, TokenValidationPolicy.NoValidation, out var header, out _);
            header.TryGetHeaderParameter("object", out var element);

            Assert.Throws <InvalidOperationException>(() => element.EnumerateObject());
        }
Example #2
0
        public void EnumerateObjects()
        {
            JwtHeaderDocument.TryParseHeader(Utf8.GetBytes("{\"object\":{\"p1\":1, \"p2\":{}, \"p3\":{\"x\":true}, \"p4\":true, \"p5\":false, \"p6\":null, \"p7\":\"text\", \"p8\":[], \"p8\":[true, false]}}"), null, TokenValidationPolicy.NoValidation, out var header, out _);
            header.TryGetHeaderParameter("object", out var element);

            var enumerator = element.EnumerateObject();

            enumerator.MoveNext();
            Assert.Equal(JsonValueKind.Number, enumerator.Current.Value.ValueKind);
            enumerator.MoveNext();
            Assert.Equal(JsonValueKind.Object, enumerator.Current.Value.ValueKind);
            enumerator.MoveNext();
            Assert.Equal(JsonValueKind.Object, enumerator.Current.Value.ValueKind);
            enumerator.MoveNext();
            Assert.Equal(JsonValueKind.True, enumerator.Current.Value.ValueKind);
            enumerator.MoveNext();
            Assert.Equal(JsonValueKind.False, enumerator.Current.Value.ValueKind);
            enumerator.MoveNext();
            Assert.Equal(JsonValueKind.Null, enumerator.Current.Value.ValueKind);
            enumerator.MoveNext();
            Assert.Equal(JsonValueKind.String, enumerator.Current.Value.ValueKind);
            enumerator.MoveNext();
            Assert.Equal(JsonValueKind.Array, enumerator.Current.Value.ValueKind);
            enumerator.MoveNext();
            Assert.Equal(JsonValueKind.Array, enumerator.Current.Value.ValueKind);
        }
Example #3
0
        public void EnumerateArrayOfInteger_NotAnArray_Fail()
        {
            JwtHeaderDocument.TryParseHeader(Utf8.GetBytes("{\"array\":{\"x\":1}}"), null, TokenValidationPolicy.NoValidation, out var header, out _);
            header.TryGetHeaderParameter("array", out var element);

            Assert.Throws <InvalidOperationException>(() => element.EnumerateArray <long>());
        }
Example #4
0
        public void EnumerateArrayOfObject()
        {
            JwtHeaderDocument.TryParseHeader(Utf8.GetBytes("{\"array\":[ 1, {}, {\"x\":true}, true, false, null, \"text\", [], [true, false]]}"), null, TokenValidationPolicy.NoValidation, out var header, out _);
            header.TryGetHeaderParameter("array", out var element);

            var enumerator = element.EnumerateArray();

            enumerator.MoveNext();
            Assert.Equal(JsonValueKind.Number, enumerator.Current.ValueKind);
            enumerator.MoveNext();
            Assert.Equal(JsonValueKind.Object, enumerator.Current.ValueKind);
            enumerator.MoveNext();
            Assert.Equal(JsonValueKind.Object, enumerator.Current.ValueKind);
            enumerator.MoveNext();
            Assert.Equal(JsonValueKind.True, enumerator.Current.ValueKind);
            enumerator.MoveNext();
            Assert.Equal(JsonValueKind.False, enumerator.Current.ValueKind);
            enumerator.MoveNext();
            Assert.Equal(JsonValueKind.Null, enumerator.Current.ValueKind);
            enumerator.MoveNext();
            Assert.Equal(JsonValueKind.String, enumerator.Current.ValueKind);
            enumerator.MoveNext();
            Assert.Equal(JsonValueKind.Array, enumerator.Current.ValueKind);
            enumerator.MoveNext();
            Assert.Equal(JsonValueKind.Array, enumerator.Current.ValueKind);
        }
        public Utf8StringHandle(string str)
            : base(true)
        {
            IntPtr buffer;

            if (str == null)
            {
                buffer = IntPtr.Zero;
            }
            else
            {
                if (str.Length == 0)
                {
                    buffer = Marshal.AllocHGlobal(1);

                    unsafe
                    {
                        *(byte *)buffer = 0;
                    }
                }
                else
                {
                    var strlen    = Utf8.GetByteCount(str);
                    var strBuffer = new byte[strlen + 1];

                    Utf8.GetBytes(str, 0, str.Length, strBuffer, 0);

                    buffer = Marshal.AllocHGlobal(strBuffer.Length);

                    Marshal.Copy(strBuffer, 0, buffer, strBuffer.Length);
                }
            }

            SetHandle(buffer);
        }
            public override bool Fallback(char charUnknown, int index)
            {
                // Do the work of figuring out what sequence of characters should replace
                // charUnknown. index is the position in the original string of this character,
                // in case that's relevant.

                // If we end up generating a sequence of replacement characters, return
                // true, and the encoder will start calling GetNextChar. Otherwise return
                // false.

                // Alternatively, instead of returning false, you can simply extract
                // DefaultString from this.fb and return that for failure cases.

                Span <char> buf = stackalloc char[1];
                Span <byte> tmp = stackalloc byte[4];

                buf[0] = charUnknown;
                var count = Utf8.GetBytes(buf, tmp);

                for (var i = 0; i < count; i++)
                {
                    ref var b      = ref tmp[i];
                    var     s      = byteToHex[b];
                    var     offset = i * 4 + 1;
                    buffer[offset + 0] = (byte)'\\';
                    buffer[offset + 2] = (byte)s[0];
                    buffer[offset + 3] = (byte)s[1];
                }
        #pragma warning restore 0649

        public static OrderedDictionary Read(string json)
        {
            var manifest = (LegacyJsonWorkbookDocumentManifest) new DataContractJsonSerializer(
                typeof(LegacyJsonWorkbookDocumentManifest)).ReadObject(
                new MemoryStream(Utf8.GetBytes(json)));

            var packageDictionaries = new List <object> ();

            if (manifest.packages != null)
            {
                foreach (var package in manifest.packages)
                {
                    packageDictionaries.Add(new OrderedDictionary {
                        ["id"]      = package.id,
                        ["version"] = package.version
                    });
                }
            }

            return(new OrderedDictionary {
                ["uti"] = manifest.uti,
                ["platform"] = manifest.platform,
                ["packages"] = packageDictionaries
            });
        }
            private async Task ProcessResponsePayload(CancellationToken ct, TextWriter responseWriter, Stream responseStream)
            {
                if (_responseStreamFactory != null)
                {
                    using (var streamToSend = await _responseStreamFactory(ct))
                    {
                        // Content-Length header
                        await responseWriter.WriteFormattedLineAsync($"Content-Length: {streamToSend.Length}");

                        await responseWriter.WriteLineAsync();

                        // Ensure header is flushed before writing to inner stream directly
                        await responseWriter.FlushAsync();

                        // Write the stream content to inner stream
                        await streamToSend.CopyToAsync(responseStream, 2048, ct);
                    }
                }
                else
                {
                    var bytes = Utf8.GetBytes(_responseContent);

                    // Content-Length header
                    await responseWriter.WriteFormattedLineAsync($"Content-Length: {bytes.Length}");

                    await responseWriter.WriteLineAsync();

                    // Ensure header is flushed before writing to inner stream directly
                    await responseWriter.FlushAsync();

                    // Write the stream content to inner stream
                    await responseStream.WriteAsync(bytes, 0, bytes.Length, ct);
                }
            }
Example #9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RequestMessage"/> class.
 /// </summary>
 /// <param name="serviceName">Name of the service.</param>
 /// <param name="username">Authentication username.</param>
 /// <param name="methodName">The name of the authentication method.</param>
 protected RequestMessage(ServiceName serviceName, string username, string methodName)
 {
     _serviceName     = serviceName.ToArray();
     _userName        = Utf8.GetBytes(username);
     _methodNameBytes = Ascii.GetBytes(methodName);
     _methodName      = methodName;
 }
Example #10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RequestMessageHost"/> class.
 /// </summary>
 /// <param name="serviceName">Name of the service.</param>
 /// <param name="username">Authentication username.</param>
 /// <param name="publicKeyAlgorithm">The public key algorithm.</param>
 /// <param name="publicHostKey">The public host key.</param>
 /// <param name="clientHostName">Name of the client host.</param>
 /// <param name="clientUsername">The client username.</param>
 /// <param name="signature">The signature.</param>
 public RequestMessageHost(ServiceName serviceName, string username, string publicKeyAlgorithm, byte[] publicHostKey, string clientHostName, string clientUsername, byte[] signature)
     : base(serviceName, username, "hostbased")
 {
     PublicKeyAlgorithm = Ascii.GetBytes(publicKeyAlgorithm);
     PublicHostKey      = publicHostKey;
     ClientHostName     = Ascii.GetBytes(clientHostName);
     ClientUsername     = Utf8.GetBytes(clientUsername);
     Signature          = signature;
 }
Example #11
0
 public override ClaimsPrincipal ValidateToken(string token, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
 {
     using (var stream = new MemoryStream(Utf8.GetBytes(token)))
         using (var reader = XmlReader.Create(stream))
         {
             reader.MoveToContent();
             return(ValidateToken(reader, validationParameters, out validatedToken));
         }
 }
Example #12
0
            public SignatureKeyData(string name, byte[] signature)
            {
#if true //old TUNING
                this.AlgorithmName = Utf8.GetBytes(name);
#else
                this.AlgorithmName = name;
#endif
                this.Signature = signature;
            }
Example #13
0
        public static Image FromData(string data, int width = 0, int height = 0)
        {
            if (uriRegex.IsMatch(data))
            {
                return(FromUri(data, width, height));
            }

            return(FromData(Utf8.GetBytes(data), width, height));
        }
        /// <summary>
        /// Encrypts an email string.
        /// </summary>
        public static string EncryptEmail(string email, RSA rsa, RSAEncryptionPadding padding)
        {
            // 1) Convert to UTF8.
            var bytes = Utf8.GetBytes(email);

            // 2) Encrypt.
            var encrypted = rsa.Encrypt(bytes, padding);

            // 3) Base64-encode.
            return(Convert.ToBase64String(encrypted));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="EnvironmentVariableRequestInfo"/> class.
        /// </summary>
        /// <param name="variableName">Name of the variable.</param>
        /// <param name="variableValue">The variable value.</param>
        public EnvironmentVariableRequestInfo(string variableName, string variableValue)
            : this()
        {
#if TUNING
            _variableName  = Utf8.GetBytes(variableName);
            _variableValue = Utf8.GetBytes(variableValue);
#else
            VariableName  = variableName;
            VariableValue = variableValue;
#endif
        }
Example #16
0
 // assume invoked only if "this" is not utf8
 internal sbyte[] GetBytesUTF8(String s)
 {
     if (IsUTF8)
     {
         return(GetBytes(s));
     }
     if (Utf8 == null)
     {
         Utf8 = new ZipCoder(StandardCharsets.UTF_8);
     }
     return(Utf8.GetBytes(s));
 }
Example #17
0
        public void EnumerateArrayOfString()
        {
            JwtHeaderDocument.TryParseHeader(Utf8.GetBytes("{\"array\":[\"text1\", \"text2\", \"text3\", \"text4\", \"text5\"]}"), null, TokenValidationPolicy.NoValidation, out var header, out _);
            header.TryGetHeaderParameter("array", out var element);
            var enumerator = element.EnumerateArray <string>();

            enumerator.MoveNext();
            Assert.Equal("text1", enumerator.Current.GetString());
            enumerator.MoveNext();
            Assert.Equal("text2", enumerator.Current.GetString());
            enumerator.MoveNext();
            Assert.Equal("text3", enumerator.Current.GetString());
            enumerator.MoveNext();
            Assert.Equal("text4", enumerator.Current.GetString());
            enumerator.MoveNext();
            Assert.Equal("text5", enumerator.Current.GetString());
        }
Example #18
0
        public void Pbkdf2_DeriveKey()
        {
            var salt = new byte[16] {
                217, 96, 147, 112, 150, 117, 70, 247, 127, 8, 155, 137, 174, 42, 80, 215
            };
            var password = Utf8.GetBytes(_password);

            using var pbkdf2_managed = new Rfc2898DeriveBytes(password, salt, 4096, HashAlgorithmName.SHA256);
            var result1 = pbkdf2_managed.GetBytes(16);


            Span <byte> result2 = stackalloc byte[16];

            Pbkdf2.DeriveKey(password, salt, Sha256.Shared, 4096, result2);

            Assert.Equal(result1, result2.ToArray());
        }
Example #19
0
        public void EnumerateArrayOfInteger()
        {
            JwtHeaderDocument.TryParseHeader(Utf8.GetBytes("{\"array\":[1, 2, 3, 4, 5]}"), null, TokenValidationPolicy.NoValidation, out var header, out _);
            header.TryGetHeaderParameter("array", out var element);

            var enumerator = element.EnumerateArray <long>();

            enumerator.MoveNext();
            Assert.Equal(1, enumerator.Current.GetInt64());
            enumerator.MoveNext();
            Assert.Equal(2, enumerator.Current.GetInt64());
            enumerator.MoveNext();
            Assert.Equal(3, enumerator.Current.GetInt64());
            enumerator.MoveNext();
            Assert.Equal(4, enumerator.Current.GetInt64());
            enumerator.MoveNext();
            Assert.Equal(5, enumerator.Current.GetInt64());
        }
        /// <summary>
        /// Converts an email string to a Gravatar-compatible MD5 hash. See https://en.gravatar.com/site/implement/hash/
        /// </summary>
        public static string HashEmail(string email)
        {
            // 1) Trim leading and trailing space characters.
            email = email.Trim(' ');
            if (email == "")
            {
                return("");
            }

            // 2) Force all characters to lowercase.
            email = email.ToLowerInvariant();

            // 3) (assumed) UTF8-encode.
            var bytes = Utf8.GetBytes(email);

            // 4) MD5 hash
            var hash = Md5.ComputeHash(bytes);

            // 5) (assumed from example) Convert to lowercase hex string.
            return(hash.ToLowercaseHexString());
        }
Example #21
0
            /// <summary>
            ///
            /// </summary>
            /// <param name="routerID"></param>
            /// <param name="sessionID"></param>
            /// <param name="message"></param>
            public static void SendMessage(RouterIdentity routerID, SessionIdentity sessionID, string message)
            {
                var data = Utf8.GetBytes(message);

                SendMessage(routerID, sessionID, data, 0, data.Length);
            }
 public SignatureKeyData(string name, byte[] signature)
 {
     AlgorithmName = Utf8.GetBytes(name);
     Signature     = signature;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="EnvironmentVariableRequestInfo"/> class.
 /// </summary>
 /// <param name="variableName">Name of the variable.</param>
 /// <param name="variableValue">The variable value.</param>
 public EnvironmentVariableRequestInfo(string variableName, string variableValue)
     : this()
 {
     _variableName  = Utf8.GetBytes(variableName);
     _variableValue = Utf8.GetBytes(variableValue);
 }
Example #24
0
            /// <summary>
            /// Notify message of server to client
            /// </summary>
            /// <param name="routerID"></param>
            /// <param name="message"></param>
            /// <exception cref="Exception"></exception>
            public static void Notify(RouterIdentity routerID, string message)
            {
                var data = Utf8.GetBytes(message);

                Notify(routerID, data, 0, data.Length);
            }
Example #25
0
        // String <-> SourceFragment

        public static SourceFragment FromString(string uxSourceCode)
        {
            return(new SourceFragment(Utf8.GetBytes(uxSourceCode)));
        }
Example #26
0
 public static Image FromSvg(string svgData, int width = 0, int height = 0)
 => new Image(
     ImageFormat.Svg,
     Utf8.GetBytes(svgData),
     width,
     height);
Example #27
0
        private byte[] BuildSecretAppend(string?apuS, string?apvS)
        {
            byte[]? apuToReturn = null;
            byte[]? apvToReturn = null;
            byte[] secretAppend;
            try
            {
                int         apuLength = apuS == null ? 0 : Utf8.GetMaxByteCount(apuS.Length);
                Span <byte> apu       = apuLength <= Constants.MaxStackallocBytes
                                        ? stackalloc byte[apuLength]
                                        : (apuToReturn = ArrayPool <byte> .Shared.Rent(apuLength));
                if (apuS != null)
                {
                    apuLength = Utf8.GetBytes(apuS, apu);
                    apu       = apu.Slice(0, apuLength);
                }

                int         apvLength = apvS == null ? 0 : Utf8.GetMaxByteCount(apvS.Length);
                Span <byte> apv       = apvLength <= Constants.MaxStackallocBytes
                                        ? stackalloc byte[apvLength]
                                        : (apvToReturn = ArrayPool <byte> .Shared.Rent(apvLength));
                if (apvS != null)
                {
                    apvLength = Utf8.GetBytes(apvS, apv);
                    apv       = apv.Slice(0, apvLength);
                }

                apuLength = Base64Url.GetArraySizeRequiredToDecode(apuLength);
                apvLength = Base64Url.GetArraySizeRequiredToDecode(apvLength);

                int       algorithmLength   = sizeof(int) + _algorithmNameLength;
                int       partyUInfoLength  = sizeof(int) + apuLength;
                int       partyVInfoLength  = sizeof(int) + apvLength;
                const int suppPubInfoLength = sizeof(int);

                int secretAppendLength = algorithmLength + partyUInfoLength + partyVInfoLength + suppPubInfoLength;
                secretAppend = new byte[secretAppendLength];
                var secretAppendSpan = secretAppend.AsSpan();
                WriteAlgorithmId(secretAppendSpan);
                secretAppendSpan = secretAppendSpan.Slice(algorithmLength);
                WritePartyInfo(apu, apuLength, secretAppendSpan);
                secretAppendSpan = secretAppendSpan.Slice(partyUInfoLength);
                WritePartyInfo(apv, apvLength, secretAppendSpan);
                secretAppendSpan = secretAppendSpan.Slice(partyVInfoLength);
                BinaryPrimitives.WriteInt32BigEndian(secretAppendSpan, _keySizeInBytes << 3);
            }
            finally
            {
                if (apuToReturn != null)
                {
                    ArrayPool <byte> .Shared.Return(apuToReturn);
                }

                if (apvToReturn != null)
                {
                    ArrayPool <byte> .Shared.Return(apvToReturn);
                }
            }

            return(secretAppend);
        }
Example #28
0
 public static Image FromUri(string uri, int width = 0, int height = 0)
 => new Image(
     ImageFormat.Uri,
     Utf8.GetBytes(uri),
     width,
     height);