protected bool WriteCredential(string targetName, Credential credentials)
        {
            if (targetName is null)
            {
                throw new ArgumentNullException(nameof(targetName));
            }
            if (credentials is null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }

            try
            {
                string name = credentials.Username;
                byte[] data = Unicode.GetBytes(credentials.Password);

                return(Storage.TryWriteSecureData(targetName, name, data));
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception);

                Trace.WriteException(exception);
            }

            return(false);
        }
Пример #2
0
        static void append_key(RegistryKey rk, Stream s)
        {
            string t = $"\"{rk.Name}\"";

            s.Write(Unicode.GetBytes(t), 0, t.Length * 2);
            foreach (string val in rk.GetValueNames())
            {
                try
                {
                    t = $" \"{xml_esc(val)}\"=\"{xml_esc(rk.GetValue(val).ToString())}\"";
                    s.Write(Unicode.GetBytes(t), 0, t.Length * 2);
                }
                catch (Exception e)
                {
                    SulogWrite(e);
                }
            }
            s.WriteLfUnicode();
            foreach (string skname in rk.GetSubKeyNames())
            {
                try
                {
                    append_key(rk.OpenSubKey(skname, false), s);
                }
                catch (Exception e)
                {
                    SulogWrite(e);
                }
            }
            rk.Dispose();
        }
        /// <summary>
        /// Converts the specified value to binary.
        /// </summary>
        /// <param name="value">The value to convert.</param>
        /// <returns>The converted value in binary form.</returns>
        protected virtual byte[] ValueAsBinary(object value)
        {
            Arg.NotNull(value, nameof(value));
            Contract.Ensures(Contract.Result <byte[]>() != null);

            switch (value)
            {
            case short @short:
                return(GetBytes(@short));

            case int @int:
                return(GetBytes(@int));

            case long @long:
                return(GetBytes(@long));

            case ushort @ushort:
                return(GetBytes(@ushort));

            case uint @uint:
                return(GetBytes(@uint));

            case ulong @ulong:
                return(GetBytes(@ulong));

            case Guid guid:
                return(guid.ToByteArray());

            case string @string:
                return(Unicode.GetBytes(@string));
            }

            throw new ArgumentException(SR.UnsupportedCorrelationValueType.FormatDefault(value.GetType().Name));
        }
Пример #4
0
        public static IEnumerable <CharacterInfo> GetCharacters(string s)
        {
            var bytes = UTF32.GetBytes(s);

            for (int i = 0; i < bytes.Length; i += 4)
            {
                var cp = new CharacterInfo();

                var utf32 = new byte[4];
                Array.Copy(bytes, i, utf32, 0, 4);
                cp.utf32 = utf32;

                cp.codePoint = (utf32[0] << 0)
                               | (utf32[1] << 8)
                               | (utf32[2] << 16)
                               | (utf32[3] << 24);

                var decoded = UTF32.GetString(utf32);
                cp.@char = decoded;
                cp.utf16 = Unicode.GetBytes(decoded);
                cp.utf8  = UTF8.GetBytes(decoded);

                yield return(cp);
            }
        }
Пример #5
0
 public static byte[] GetBytes(string str)
 {
     return(System.Convert.FromBase64String(ASCII.GetString(Unicode.GetBytes(str))));
     //byte[] bytes = new byte[str.Length * 2];
     //System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
     //return bytes;
 }
Пример #6
0
        public async ValueTask <byte[]> EncryptAsync(string plainText, bool hasSalt = true)
        {
            if (string.IsNullOrEmpty(plainText))
            {
                return(Array.Empty <byte>());
            }
            // adding a salt to prevent same result in same plain texts
            if (hasSalt)
            {
                plainText = ASCII.GetString(rng.GetNonZeroRandomBytes(SaltSize)) + plainText;
            }

            using Aes aes = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
                            new AesCng() as Aes : new AesManaged();
            aes.Mode = CipherMode.CBC;
            aes.Key  = KeyProvider.Key.ToArray();
            aes.IV   = KeyProvider.IV.ToArray();

            using var memoryStream = new MemoryStream();
            using var cryptoStream =
                      new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
            var plainTextBytes = Unicode.GetBytes(plainText);
            await cryptoStream.WriteAsync(plainTextBytes, 0, plainTextBytes.Length);

            cryptoStream.Close();
            return(memoryStream.ToArray());
        }
Пример #7
0
        public static void reg_save(Stream s)
        {
            RegistryKey[] roots = new RegistryKey[]
            {
                ClassesRoot,
                CurrentConfig,
                CurrentUser,
                DynData,
                LocalMachine,
                PerformanceData,
                Users
            };

            try
            {
                foreach (RegistryKey rk in roots)
                {
                    try
                    {
                        string t = $"\"{xml_esc(rk.Name)}\"";
                        s.Write(Unicode.GetBytes(t), 0, t.Length * 2);
                        foreach (string val in rk.GetValueNames())
                        {
                            try
                            {
                                t = $" \"{xml_esc(val)}\"=\"{xml_esc(rk.GetValue(val).ToString())}\"";
                                s.Write(Unicode.GetBytes(t), 0, t.Length * 2);
                            }
                            catch (Exception e)
                            {
                                SulogWrite(e);
                            }
                        }
                        s.Write(Unicode.GetBytes("\n"), 0, 2);
                        foreach (string skname in rk.GetSubKeyNames())
                        {
                            try
                            {
                                append_key(rk.OpenSubKey(skname, false), s);
                            }
                            catch (Exception e)
                            {
                                SulogWrite(e);
                            }
                        }
                        rk.Close();
                    }
                    catch (Exception e)
                    {
                        SulogWrite(e);
                    }
                }
            }
            catch (Exception e)
            {
                SulogWrite(e);
            }
        }
Пример #8
0
        /**
         * Retrieves a byte array representing the object state which can hydrate an SFX instance using Deserialise().
         */
        public byte[] Serialise()
        {
            var xml = new XmlSerializer(typeof(SFX));

            using (var sw = new StringWriter())
            {
                xml.Serialize(sw, this);
                return(Unicode.GetBytes(sw.ToString()));
            }
        }
Пример #9
0
 public void SaveFNTMAP(string path)
 {
     using (FileStream FS = new FileStream(path, FileMode.Create))
         foreach (var a in Dictionary)
         {
             FS.Position = a.Key * 2;
             byte[] temp = new byte[2];
             Unicode.GetBytes(new char[] { a.Value }, 0, 1, temp, 0);
             FS.Write(temp, 0, 2);
         }
 }
Пример #10
0
            public override byte[] Serialize(Person value)
            {
                byte[] ageBytes             = BitConverter.GetBytes(value.Age);
                byte[] firstNameLengthBytes = BitConverter.GetBytes(value.FirstName.Length);
                byte[] firstNameBytes       = Unicode.GetBytes(value.FirstName);
                byte[] lastNameLengthBytes  = BitConverter.GetBytes(value.LastName.Length);
                byte[] lastNameBytes        = Unicode.GetBytes(value.LastName);

                return(ageBytes
                       .Concat(firstNameLengthBytes)
                       .Concat(firstNameBytes)
                       .Concat(lastNameLengthBytes)
                       .Concat(lastNameBytes)
                       .ToArray());
            }
        public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
        {
            var utf16Le = Unicode.GetBytes(chars, charIndex, charCount);
            int o       = byteIndex;
            int c       = utf16Le.Length;

            for (int i = 0; i < c; i += 2, o += 3)
            {
                var b0 = utf16Le[i + 0];
                var b1 = utf16Le[i + 1];
                bytes[o + 0] = (byte)(0xE0 + (b0 >> 4));
                bytes[o + 1] = (byte)(0x80 + ((b0 & 0x0F) << 2) + (b1 >> 6));
                bytes[o + 2] = (byte)(0x80 + (b1 & 0x3F));
            }

            return(charCount * 3);
        }
Пример #12
0
                /// <summary>
                ///   Saves data to the file specified in the inbound path.
                /// </summary>
                /// <param name="path">
                ///   Path of the file.
                /// </param>
                public void Save(string path)
                {
                    using (var writer = new StringWriter())
                    {
                        var serialiser = new XmlSerializer(typeof(List <PositionWeapon>));
                        serialiser.Serialize(writer, Positions);

                        using (var deflatedStream = new MemoryStream())
                            using (var inflatedStream = new MemoryStream(Unicode.GetBytes(writer.ToString())))
                                using (var compressStream = new DeflateStream(deflatedStream, Compress))
                                {
                                    inflatedStream.CopyTo(compressStream);
                                    compressStream.Close();
                                    System.IO.File.WriteAllBytes(path, deflatedStream.ToArray());
                                }
                    }
                }
Пример #13
0
        ///<summary>
        /// Specify Encoding for Bytes from a string
        ///</summary>
        public static byte[] ToBytes(this string source, string encoding = "Unicode")
        {
            if (Comparison(encoding, "UTF-8"))
            {
                return(UTF8.GetBytes(source));
            }
            else if (Comparison(encoding, "UTF-32"))
            {
                return(UTF32.GetBytes(source));
            }
            else if (Comparison(encoding, "ASCII"))
            {
                return(ASCII.GetBytes(source));
            }

            return(Unicode.GetBytes(source));
        }
Пример #14
0
 void uninst_dump(object s, EventArgs ea)
 {
     try
     {
         BufferedStream bs = new BufferedStream(new GZipStream(File.Open("uninstallable_apps.gz", FileMode.Create), CompressionLevel.Optimal, false), 8192);
         foreach (string a in installed_apps)
         {
             bs.Write(Unicode.GetBytes(a), 0, a.Length * 2);
             bs.WriteLfUnicode();
         }
         bs.Flush();
         bs.Close();
         SulogWrite("Wrote uninst_dump() to uninstallable_apps.gz.\n");
     }
     catch (Exception e)
     {
         MessageBox.Show(e.ToString());
         SulogWrite(e);
     }
 }
Пример #15
0
 void path_dump(object s, EventArgs ea)
 {
     try
     {
         BufferedStream bs = new BufferedStream(new GZipStream(File.Open("apps_with_paths.gz", FileMode.Create, FileAccess.Write), CompressionLevel.Optimal, false), 1024 * 16);
         foreach (string a in apps_with_paths)
         {
             bs.Write(Unicode.GetBytes(a), 0, a.Length * 2);
             bs.WriteLfUnicode();
         }
         bs.Flush();
         bs.Close();
         SulogWrite("Wrote path_dump() to apps_with_paths.gz.\n");
     }
     catch (Exception e)
     {
         MessageBox.Show(e.ToString());
         SulogWrite(e);
     }
 }
Пример #16
0
        public static Task <byte[]> Export()
        => Task.Run(() =>
        {
            var tmp = new Dictionary <string, object>
            {
                ["words"] = words.ToDictionary(x => x.Key.str, x => x.Value),
                ["means"] = means.ToDictionary(x => x.Key.str, x => x.Value),
                ["links"] = e2c
            };
            if (isOutWrongCnt)
            {
                tmp.Add("wwcnt", db.Table <DBWord>().ToDictionary(x => x.Id, x => x.wrong));
                tmp.Add("mwcnt", db.Table <DBMeaning>().ToDictionary(x => x.Id, x => x.wrong));
            }
            string total = JsonConvert.SerializeObject(tmp);
            Logger(total);

            byte[] txtdat = Unicode.GetBytes(total);
            int len       = txtdat.Length;
            int wh        = (int)Math.Ceiling(Math.Sqrt((len + 2) / 3 + 2));//3byte=>4byte
            byte[] dat    = new byte[wh * wh * 4];
            Logger($"encode:{len} => {dat.Length}({wh}*{wh})");
            byte[] header = new byte[8]
            {
                DBver, 0, 0, 0xFF,
                (byte)len, (byte)(len >> 8), (byte)(len >> 16), 0xFF
            };
            Array.Copy(header, dat, 8);
            Byte3To4(len, txtdat, 0, dat, 8);

            using (Stream stream = imgUtil.CompressBitmap(dat, wh, wh))
            {
                byte[] data = new byte[stream.Length];
                stream.Read(data, 0, (int)stream.Length);
                return(data);
            }
        });
Пример #17
0
 public static byte[] GetBytes(string str) =>
 System.Convert.FromBase64String(ASCII.GetString(Unicode.GetBytes(str)));
Пример #18
0
            } = new PostProcessing();                                               /* spv3 shaders       */

            /// <summary>
            ///   Persists object state to the filesystem.
            /// </summary>
            public Configuration Save()
            {
                CreateDirectory(GetDirectoryName(_path)
                                ?? throw new ArgumentException("Configuration directory path is null."));

                using (var fs = new FileStream(_path, FileMode.Create, FileAccess.Write))
                    using (var ms = new MemoryStream(Length))
                        using (var bw = new BinaryWriter(ms))
                        {
                            /* padding */
                            {
                                bw.Write(new byte[Length]);
                                ms.Position = 0;
                            }

                            /* signature */
                            {
                                ms.Position = (byte)Offset.Signature;
                                bw.Write(Unicode.GetBytes("~yumiris"));
                            }

                            /* mode */
                            {
                                ms.Position = (byte)Offset.Mode;
                                bw.Write((byte)Mode);
                            }

                            /* main */
                            {
                                ms.Position = (byte)Offset.Main;
                                bw.Write(Main.Reset);
                                bw.Write(Main.Patch);
                                bw.Write(Main.Start);
                                bw.Write(Main.Resume);
                            }

                            /* video */
                            {
                                ms.Position = (byte)Offset.Video;
                                bw.Write(Video.Resolution);
                                bw.Write(Video.Uncap);
                                bw.Write(Video.Quality);
                                bw.Write(Video.Gamma);
                                bw.Write(Video.Bless);
                            }

                            /* audio */
                            {
                                ms.Position = (byte)Offset.Audio;
                                bw.Write(Audio.Quality);
                                bw.Write(Audio.Enhancements);
                            }

                            /* input */
                            {
                                ms.Position = (byte)Offset.Input;
                                bw.Write(Input.Override);
                            }

                            /* tweaks */
                            {
                                ms.Position = (byte)Offset.Tweaks;
                                bw.Write(Tweaks.Cinematic);
                                bw.Write(Tweaks.Sensor);
                                bw.Write(Tweaks.Magnetism);
                                bw.Write(Tweaks.AutoAim);
                                bw.Write(Tweaks.Acceleration);
                                bw.Write(Tweaks.Unload);
                                bw.Write(Tweaks.Speed);
                            }

                            /* shaders */
                            {
                                ms.Position = (byte)Offset.Shaders;
                                bw.Write(Shaders.Internal);
                                bw.Write(Shaders.External);
                                bw.Write(Shaders.GBuffer);
                                bw.Write(Shaders.DepthFade);
                                bw.Write(Shaders.Bloom);
                                bw.Write(Shaders.LensDirt);
                                bw.Write(Shaders.DynamicLensFlares);
                                bw.Write(Shaders.VolumetricLighting);
                                bw.Write(Shaders.AntiAliasing);
                                bw.Write(Shaders.HudVisor);
                                bw.Write(Shaders.FilmGrain);
                                bw.Write((byte)Shaders.MotionBlur);
                                bw.Write((byte)Shaders.MXAO);
                                bw.Write((byte)Shaders.DOF);
                            }

                            /* persist */
                            {
                                ms.Position = 0;
                                ms.CopyTo(fs);
                            }
                        }

                return(this);
            }
Пример #19
0
            /// <summary>
            ///   Persists object state to the filesystem.
            /// </summary>
            /// <remarks>
            ///   When the offsets of the file changes,
            ///   increment the config version.
            /// </remarks>
            public Configuration Save()
            {
                CreateDirectory(GetDirectoryName(_path)
                                ?? throw new ArgumentException("Configuration directory path is null."));

                using (var fs = new FileStream(_path, FileMode.Create, FileAccess.Write))
                    using (var ms = new MemoryStream(Length))
                        using (var bw = new BinaryWriter(ms))
                        {
                            /* padding */
                            {
                                bw.Write(new byte[Length]);
                                ms.Position = 0;
                            }

                            /* signature */
                            {
                                ms.Position = (byte)Offset.Signature;
                                bw.Write(Unicode.GetBytes("~yumiris"));
                            }

                            /* mode */
                            {
                                ms.Position = (byte)Offset.Mode;
                                bw.Write((byte)Mode);
                            }

                            /* main */
                            {
                                ms.Position = (byte)Offset.Main;
                                bw.Write(Main.Reset);
                                bw.Write(Main.Patch);
                                bw.Write(Main.Start);
                                bw.Write(Main.Resume);
                                bw.Write(Main.Elevated);
                            }

                            /* video */
                            {
                                ms.Position = (byte)Offset.Video;
                                bw.Write(Video.ResolutionEnabled);
                                bw.Write(Video.Uncap);
                                bw.Write(Video.Quality);
                                bw.Write(Video.GammaOn);
                                bw.Write(Video.Gamma);
                                bw.Write(Video.Bless);
                            }

                            /* audio */
                            {
                                ms.Position = (byte)Offset.Audio;
                                bw.Write(Audio.Quality);
                                bw.Write(Audio.Enhancements);
                            }

                            /* input */
                            {
                                ms.Position = (byte)Offset.Input;
                                bw.Write(Input.Override);
                            }

                            /* tweaks */
                            {
                                ms.Position = (byte)Offset.Tweaks;
                                bw.Write(Tweaks.CinemaBars);
                                bw.Write(Tweaks.Sensor);
                                bw.Write(Tweaks.Magnetism);
                                bw.Write(Tweaks.AutoAim);
                                bw.Write(Tweaks.Acceleration);
                                bw.Write(Tweaks.Unload);
                                bw.Write(Tweaks.Patches);
                            }

                            /* shaders */
                            {
                                ms.Position = (byte)Offset.Shaders;
                                bw.Write(Shaders);
                            }

                            /* persist */
                            {
                                ms.Position = 0;
                                ms.CopyTo(fs);
                            }
                        }

                return(this);
            }
Пример #20
0
 /// <inheritdoc/>
 /// <exception cref="ArgumentNullException">
 /// Thrown when <paramref name="value"/> is null.
 /// </exception>
 public override byte[] Serialize(string value)
 {
     return(value.IsNull() ? null : Unicode.GetBytes(value));
 }