Beispiel #1
0
        private static string ReadString(BinaryReader reader, int length)
        {
            var data            = reader.ReadBytes(length);
            var terminatorIndex = Array.FindIndex(data, x => x == 0);

            return(StringEncoding.GetString(data, 0, terminatorIndex < 0 ? length : terminatorIndex));
        }
        /// <summary>
        /// Hash the raw password bytes using Argon2 with the specified salt bytes.
        /// Unless you need to specify your own salt for interoperability purposes, prefer the Hash(byte[] password) overload instead.
        /// Do not compare two Argon2 hashes directly. Instead, use the Verify or VerifyAndUpdate methods.
        /// <param name="password">The raw bytes of the password to be hashed</param>
        /// <param name="salt">The raw salt bytes to be used for the hash. The salt must be at least 8 bytes.</param>
        /// <returns>A formatted string representing the hashed password, encoded with the parameters used to perform the hash</returns>
        /// </summary>
        public string Hash(ReadOnlySpan <char> password, ReadOnlySpan <byte> salt)
        {
            Span <byte> hash          = stackalloc byte[(int)HashLength];
            Span <byte> encoded       = stackalloc byte[(int)(39 + ((HashLength + salt.Length) * 4 + 3) / 3)];
            Span <byte> passwordBytes = stackalloc byte[StringEncoding.GetByteCount(password)];

            StringEncoding.GetBytes(password, passwordBytes);

            var result = Argon2.Library.Hash(
                TimeCost,
                MemoryCost,
                Parallelism,
                passwordBytes,
                salt,
                hash,
                encoded,
                (int)ArgonType,
                0x13
                );

            if (result != Argon2Error.OK)
            {
                throw new Argon2Exception("hashing", result);
            }

            var firstNonNull = encoded.Length - 2;

            while (encoded[firstNonNull] == 0)
            {
                firstNonNull--;
            }

            return(Encoding.ASCII.GetString(encoded.Slice(0, firstNonNull + 1)));
        }
Beispiel #3
0
        public static RoleTest Read(byte[] buffer, int offset)
        {
            var msg = new RoleTest();

            msg.RoleId = BitConverter.ToInt16(buffer, offset);
            offset    += 2;
            var RoleNameLength = buffer[offset];

            offset++;
            msg.RoleName = StringEncoding.GetString(buffer, offset, RoleNameLength);
            offset      += RoleNameLength;
            msg.Id       = Int24.ReadInt24(buffer, offset);
            offset      += 3;
            var countIds = buffer[offset];

            offset++;
            var listIds = new List <int>();

            for (var i = 0; i < countIds; i++)
            {
                var item = Int24.ReadInt24(buffer, offset);
                offset += 3;
                listIds.Add(item);
            }
            msg.Ids = listIds;
            return(msg);
        }
            public IntPtr MarshalManagedToNative(object managedObj)
            {
                if (managedObj is null)
                {
                    return(IntPtr.Zero);
                }
                byte[] bytes     = null;
                var    byteCount = 0;

                if (managedObj is string str)
                {
                    bytes     = StringEncoding.GetBytes(str);
                    byteCount = bytes.Length + 1;
                }

                if (managedObj is StringBuilder builder)
                {
                    bytes     = StringEncoding.GetBytes(builder.ToString());
                    byteCount = StringEncoding.GetMaxByteCount(builder.Capacity) + 1;
                }

                if (bytes is null)
                {
                    throw new ArgumentException("The input argument is not a supported type.");
                }
                var ptr = Marshal.AllocHGlobal(byteCount);

                Marshal.Copy(bytes, 0, ptr, bytes.Length);
                // Put zero string termination
                Marshal.WriteByte(ptr + bytes.Length, 0);
                return(ptr);
            }
        FieldProperties ParseField(string tableName, XElement xField)
        {
            string         name           = xField.Attribute("Name").Value;
            var            dataType       = (DataType)Enum.Parse(typeof(DataType), xField.Attribute("DataType").Value);
            FieldFlags     flags          = FieldFlags.None;
            Type           valueType      = null;
            StringEncoding stringEncoding = StringEncoding.Undefined;
            int            maxLength      = 0;
            DateTimeType   dateTimeType   = DateTimeType.Native;
            DateTimeKind   dateTimeKind   = DateTimeKind.Unspecified;
            string         description    = null;

            foreach (XElement element in xField.Elements())
            {
                switch (element.Name.LocalName)
                {
                case "Flags": flags = (FieldFlags)Enum.Parse(typeof(FieldFlags), element.Value); break;

                case "ValueType": valueType = LoadType(element.Value); break;

                case "StringEncoding": stringEncoding = (StringEncoding)Enum.Parse(typeof(StringEncoding), element.Value); break;

                case "MaximumLength": maxLength = int.Parse(element.Value); break;

                case "DateTimeType": dateTimeType = (DateTimeType)Enum.Parse(typeof(DateTimeType), element.Value); break;

                case "DateTimeKind": dateTimeKind = (DateTimeKind)Enum.Parse(typeof(DateTimeKind), element.Value); break;

                case "Description": description = element.Value; break;

                default: throw new InvalidDataException(string.Format("Unknown tree type {0}", element.Name.LocalName));
                }
            }
            return(new FieldProperties(tableName, flags, dataType, valueType, maxLength, name, dataType, dateTimeType, dateTimeKind, stringEncoding, name, description, null, null));
        }
 public void Constructor1()
 {
     string data = "sofisticadas, el “Análisis de";
     StringEncoding converter = new StringEncoding (data);
     converter.ReplaceCodesTable(StringEncoding.CharactersDefault);
     Assert.AreEqual ("sofisticadas, el &#147;An&aacute;lisis de", converter.GetStringUnicode (), "C01");
 }
 public static void WriteText(this string strPath, string Text, StringEncoding _Encoding)
 {
     if (_Encoding == StringEncoding.ASCII)
         File.WriteAllText(strPath, Text, Encoding.ASCII);
     if (_Encoding == StringEncoding.UNICODE)
         File.WriteAllText(strPath, Text, Encoding.Unicode);
 }
Beispiel #8
0
        /// <summary>
        /// Parses a length-prefixed string.
        /// </summary>
        /// <returns>The parsed string.</returns>
        public string ReadString()
        {
            uint length = ReadVarUInt32();

            byte[] bytes = ReadBytes((int)length);
            return(StringEncoding.GetString(bytes));
        }
Beispiel #9
0
 public StringDataType(
     uint aSize,
     StringPadding aStringPadding,
     StringEncoding aStringEncoding) : base(DatatypeClass.String, aSize)
 {
     StringPadding  = aStringPadding;
     StringEncoding = aStringEncoding;
 }
Beispiel #10
0
 public void WriteString(string value)
 {
     WriteInt16((short)value.Length);
     if (value.Length > 0)
     {
         WriteUInt8Array(StringEncoding.GetBytes(value));
     }
 }
Beispiel #11
0
 public static byte[] GetEncodedBytes(string s, StringEncoding enc)
 {
     if (!string.IsNullOrEmpty(s))
     {
         return(EncodingDictionary.GetEncodingFromISO(enc).GetBytes(s));
     }
     return(new byte[0]);
 }
Beispiel #12
0
        public static byte[] StringToBytes(BotData data, [Variable] string input, StringEncoding encoding = StringEncoding.UTF8)
        {
            data.Logger.LogHeader();
            var bytes = MapEncoding(encoding).GetBytes(input);

            data.Logger.Log($"Got bytes from {encoding} string", LogColors.Flavescent);
            return(bytes);
        }
Beispiel #13
0
 public static byte[] Write(string data, StringEncoding enc)
 {
     if (IsEven(data))
     {
         return(EncodingDictionary.GetEncodingFromISO(enc).GetBytes(data));
     }
     return(PadOddBytes(EncodingDictionary.GetEncodingFromISO(enc), data));
 }
Beispiel #14
0
        public static string BytesToString(BotData data, [Variable] byte[] input, StringEncoding encoding = StringEncoding.UTF8)
        {
            data.Logger.LogHeader();
            var str = MapEncoding(encoding).GetString(input);

            data.Logger.Log($"Decoded {encoding} string from byte array: {str}", LogColors.Flavescent);
            return(str);
        }
Beispiel #15
0
 void sendStruct()
 {
     JFPackage.PAG_STRUCTURE _s = new JFPackage.PAG_STRUCTURE(
         StringEncoding.GetBytes("Hello"),
         cnt,
         StringEncoding.GetBytes("guccang"),
         StringEncoding.GetBytes("What")
         );
     NetMgr.getSingleton().sendMsg(_s);
 }
Beispiel #16
0
        public string Decode(string encoded, StringEncoding encoding, bool urlEncode)
        {
            if (encoded == null)
            {
                return(null);
            }
            var toDecode = urlEncode ? encoded.UrlDecoded() : encoded;

            return(_encoders[encoding].Decode(toDecode));
        }
Beispiel #17
0
        public string Hash(ReadOnlySpan <char> password, ReadOnlySpan <byte> salt)
        {
            Span <byte> passwordBytes = stackalloc byte[StringEncoding.GetByteCount(password)];

            StringEncoding.GetBytes(password, passwordBytes);

            Span <byte> hash = stackalloc byte[(int)HashLength];

            return(Hash(passwordBytes, salt, hash));
        }
Beispiel #18
0
        public bool Verify(ReadOnlySpan <char> expectedHash, ReadOnlySpan <char> password)
        {
            Span <byte> expectedHashBytes = stackalloc byte[StringEncoding.GetByteCount(expectedHash)];

            StringEncoding.GetBytes(expectedHash, expectedHashBytes);
            Span <byte> passwordBytes = stackalloc byte[StringEncoding.GetByteCount(password)];

            StringEncoding.GetBytes(password, passwordBytes);
            return(Verify(expectedHashBytes, passwordBytes));
        }
Beispiel #19
0
        public string Encode(string decoded, StringEncoding encoding, bool urlEncode)
        {
            if (decoded == null)
            {
                return(null);
            }
            var encoded = _encoders[encoding].Encode(decoded);

            return(urlEncode ? encoded.UrlEncoded() : encoded);
        }
Beispiel #20
0
 public static void WriteText(this string strPath, string Text, StringEncoding _Encoding)
 {
     if (_Encoding == StringEncoding.ASCII)
     {
         File.WriteAllText(strPath, Text, Encoding.ASCII);
     }
     if (_Encoding == StringEncoding.UNICODE)
     {
         File.WriteAllText(strPath, Text, Encoding.Unicode);
     }
 }
Beispiel #21
0
        public static byte[] GetDataLittleEndian(IDICOMElement el, StringEncoding enc)
        {
            var vr = VRDictionary.GetVRFromType(el);

            switch (vr)
            {
            case VR.AttributeTag:
                var at = el as AttributeTag;
                return(LittleEndianWriter.WriteTag(at.DataContainer));

            case VR.FloatingPointDouble:
                var fpd = el as FloatingPointDouble;
                return(LittleEndianWriter.WriteDoublePrecision(fpd.DataContainer));

            case VR.FloatingPointSingle:
                var fps = el as FloatingPointSingle;
                return(LittleEndianWriter.WriteSinglePrecision(fps.DataContainer));

            case VR.OtherByteString:
                var obs = el as OtherByteString;
                return(DataRestriction.EnforceEvenLength(obs.DataContainer.MultipicityValue.ToArray(), vr));

            case VR.OtherFloatString:
                var ofs = el as OtherFloatString;
                return(ofs.DataContainer.MultipicityValue.ToArray());

            case VR.OtherWordString:
                var ows = el as OtherWordString;
                return(ows.DataContainer.MultipicityValue.ToArray());

            case VR.SignedLong:
                var sl = el as SignedLong;
                return(LittleEndianWriter.WriteSignedLong(sl.DataContainer));

            case VR.SignedShort:
                var sis = el as SignedShort;
                return(LittleEndianWriter.WriteSignedShort(sis.DataContainer));

            case VR.Unknown:
                var uk = el as Unknown;
                return(DataRestriction.EnforceEvenLength(uk.DataContainer.MultipicityValue.ToArray(), vr));

            case VR.UnsignedLong:
                var ul = el as UnsignedLong;
                return(LittleEndianWriter.WriteUnsignedLong(ul.DataContainer));

            case VR.UnsignedShort:
                var ush = el as UnsignedShort;
                return(LittleEndianWriter.WriteUnsignedShort(ush.DataContainer));

            default:
                return(GetStringBytes(vr, el, enc));
            }
        }
Beispiel #22
0
        /// <summary>
        /// Gets the encoding implmntation for e specidified <see cref="StringEncoding"/>
        /// </summary>
        /// <returns>The encoding.</returns>
        /// <param name="aValue">The StringEncoding to convert.</param>
        public static Encoding GetEncoding(this StringEncoding aValue)
        {
            switch (aValue)
            {
            case StringEncoding.ASCII: return(Encoding.ASCII);

            case StringEncoding.UTF8: return(Encoding.UTF8);

            default:
                throw new System.ArgumentException($"Unknown Encoding: {aValue}");
            }
        }
Beispiel #23
0
        public override void WriteString(string value)
        {
            var raw    = value.AsSpan();
            int length = StringEncoding.GetByteCount(raw);

            //reserve additional 4 bytes for the length prefix
            WriteInt32(length);
            //write chars to span
            StringEncoding.GetBytes(raw, Allocate(length));
            //padd offset to match 4-bytes chunks
            WritePadding(length);
        }
Beispiel #24
0
        public string ReadString()
        {
            short length = ReadInt16();

            if (length == 0)
            {
                return(string.Empty);
            }
            var data = ReadUInt8Array(length * 2);

            return(StringEncoding.GetString(data));
        }
Beispiel #25
0
        /// <summary>
        /// Reads a string from the base address of the process memory (some values, such as player name, require this)
        /// </summary>
        /// <param name="address">The address of the string to read</param>
        /// <param name="maxSize">The maximum size of the string</param>
        /// <returns></returns>
        public string ReadStringBase(IntPtr address, int maxSize = 512)
        {
            var memoryStringBytes = _mem.ReadMemory(GameProcess.Id, BaseAddress + (int)address, maxSize); // This differs from the above here, in that you must add the offset to the base address in order to read it.

            var ret = StringEncoding.GetString(memoryStringBytes);

            if (ret.IndexOf('\0') != -1)
            {
                ret = ret.Remove(ret.IndexOf('\0'));
            }

            return(ret);
        }
Beispiel #26
0
        /// <summary>
        /// Reads a string from the process memory
        /// </summary>
        /// <param name="address">The address of the string to read</param>
        /// <param name="maxSize">The maximum size of the string</param>
        /// <returns></returns>
        public string ReadString(IntPtr address, int maxSize = 512)
        {
            var memoryStringBytes = _mem.ReadMemory(GameProcess.Id, address, maxSize);

            var ret = StringEncoding.GetString(memoryStringBytes);

            if (ret.IndexOf('\0') != -1)
            {
                ret = ret.Remove(ret.IndexOf('\0'));
            }

            return(ret);
        }
Beispiel #27
0
        public string ReadString(int length, StringEncoding encoding)
        {
            switch (encoding)
            {
            case StringEncoding.ASCII:
                return(Encoding.ASCII.GetString(this.ReadBytes(length)));

            case StringEncoding.UTF8:
                return(Encoding.UTF8.GetString(this.ReadBytes(length)));

            default:
                throw new ArgumentException("encoding");
            }
        }
Beispiel #28
0
    void sendArray()
    {
        JFPackage.PAG_ArrayInner inner = new JFPackage.PAG_ArrayInner(
            StringEncoding.GetBytes("ArrayDest"),
            cnt,
            StringEncoding.GetBytes("guccang"),
            StringEncoding.GetBytes("arr")
            );
        List <JFPackage.PAG_ArrayInner> lst = new List <JFPackage.PAG_ArrayInner>();

        lst.Add(inner); lst.Add(inner);
        JFPackage.PAG_ARRAY _a = JFTools.buildArrayStruct <JFPackage.PAG_ArrayInner, JFPackage.PAG_ARRAY>(lst);
        NetMgr.getSingleton().sendMsg(_a);
    }
 public void Prueba()
 {
     string data = "a°a";
     StringEncoding converter = new StringEncoding (data);
     Console.WriteLine("El codigo::");
     Console.WriteLine("tamaño!::"+converter.data_byte.Count);
     for (int i=0; i < converter.data_byte.Count; i++){
     Console.WriteLine("::"+converter.data_byte[i]);
     }
     Console.WriteLine("::aca termina");
     converter.ReplaceCodesTable (StringEncoding.CharactersDefault);
     Console.WriteLine ("::"+converter.GetStringUnicode ()+"::");
     StringEncoding.CodesCharacters();
 }
Beispiel #30
0
        public void Write(string value, StringEncoding encoding)
        {
            var bytes = _textEncoding.GetBytes(value);

            switch (encoding)
            {
            case StringEncoding.LengthPrefixedInt8:
                Write((sbyte)bytes.Length);
                goto default;

            case StringEncoding.LengthPrefixedUInt8:
                Write((byte)bytes.Length);
                goto default;

            case StringEncoding.LengthPrefixedInt16:
                Write((short)bytes.Length);
                goto default;

            case StringEncoding.LengthPrefixedUInt16:
                Write((ushort)bytes.Length);
                goto default;

            case StringEncoding.LengthPrefixedInt32:
                Write((int)bytes.Length);
                goto default;

            case StringEncoding.LengthPrefixedUInt32:
                Write((uint)bytes.Length);
                goto default;

            case StringEncoding.LengthPrefixedInt64:
                Write((long)bytes.Length);
                goto default;

            case StringEncoding.LengthPrefixedUInt64:
                Write((ulong)bytes.Length);
                goto default;

            case StringEncoding.NullTerminated:
                Array.Resize(ref bytes, bytes.Length + 1);
                bytes[bytes.Length - 1] = 0;
                goto default;

            case StringEncoding.FixedLength:
            default:
                Write(bytes);
                break;
            }
        }
            public unsafe object MarshalNativeToManaged(IntPtr nativeData)
            {
                if (nativeData == IntPtr.Zero)
                {
                    return(null);
                }
                var bytes   = (byte *)nativeData;
                var nbBytes = 0;

                while (*(bytes + nbBytes) != 0)
                {
                    nbBytes++;
                }
                return(StringEncoding.GetString(bytes, nbBytes));
            }
Beispiel #32
0
 internal RawString(ReadOnlySpan <byte> source, StringEncoding encoding)
 {
     if (source.Length == 0)
     {
         _headPointer = default;
         _byteLength  = default;
         Encoding     = encoding;
         return;
     }
     _headPointer = Marshal.AllocHGlobal(source.Length);
     _byteLength  = source.Length;
     Encoding     = encoding;
     source.CopyTo(new Span <byte>((void *)_headPointer, source.Length));
     UnmanagedMemoryChecker.RegisterNewAllocatedBytes(_byteLength);
 }
Beispiel #33
0
 private StringDataType(
     IDatatypeHeader aHeader,
     StringPadding aStringPadding,
     StringEncoding aStringEncoding) : this(
         aHeader.Size,
         aStringPadding,
         aStringEncoding)
 {
     if (aHeader.Class != DatatypeClass.String)
     {
         throw new ArgumentException(
                   $"Header Class must be {nameof(DatatypeClass.String)}",
                   nameof(aHeader));
     }
 }
Beispiel #34
0
        public static string ToString(IntPtr lParam, int length, StringEncoding marshalAs, bool tranformExceptionsToNull)
        {
            if (lParam == IntPtr.Zero) 
                throw new ArgumentNullException("lParam");

            if (length < 0) 
                throw new ArgumentOutOfRangeException("length");

            if (marshalAs != StringEncoding.MirandaDefault && marshalAs != StringEncoding.Ansi && marshalAs != StringEncoding.Unicode)
                throw new ArgumentOutOfRangeException("marshalAs");                       

            try
            {
                reEval:
                switch (marshalAs)
                {
                    case StringEncoding.MirandaDefault:
                        marshalAs = MirandaEnvironment.MirandaStringEncoding;
                        if (marshalAs == StringEncoding.MirandaDefault) throw new ArgumentException(TextResources.ExceptionMsg_CannotDetectMirandaDefaultStringEncoding);
                        goto reEval;
                    case StringEncoding.Ansi:
                        if (length > 0)
                            return Marshal.PtrToStringAnsi(lParam, length);
                        else
                            return Marshal.PtrToStringAnsi(lParam);
                    case StringEncoding.Unicode:
                        if (length > 0)
                            return Marshal.PtrToStringUni(lParam, length);
                        else
                            return Marshal.PtrToStringUni(lParam);                    
                    default:
                        return null;
                }
            }
            catch (Exception e)
            {
                if (!tranformExceptionsToNull)
                    throw new ArgumentException("lParam", TextResources.ExceptionMsg_InvalidValueToTranslate + e.Message, e);
                else
                    return null;
            }
        }
        public UnmanagedStringHandle(string str, StringEncoding encoding)
        {
        reEval:
            switch (encoding)
            {
                case StringEncoding.Unicode:
                    this.intPtr = Marshal.StringToHGlobalUni(str);
                    break;
                case StringEncoding.Ansi:
                    this.intPtr = Marshal.StringToHGlobalAnsi(str);
                    break;
                default:
                    encoding = MirandaEnvironment.MirandaStringEncoding;

                    if (encoding == StringEncoding.MirandaDefault) 
                        throw new ArgumentException(TextResources.ExceptionMsg_CannotDetectMirandaDefaultStringEncoding);

                    goto reEval;
            }

            this.originalString = str;
            this.encoding = encoding;
        }
 public void Constructor2Caso3()
 {
     StringEncoding converter = new StringEncoding ("");
     Assert.IsNotNull (converter, "CO2 C3");
 }
 public void Constructor2Caso2()
 {
     string text = "";
     StringEncoding converter = new StringEncoding (text, 1255);
     Assert.AreEqual (text, converter.GetStringUnicode(), "CO2 C2");
 }
 public WindowsFileSystem(StringEncoding encoding)
 {
     _encoding = encoding;
 }
Beispiel #39
0
 public HelpAttribute(StringEncoding encode, uint length = 0)
 {
     this.Encode = encode;
     this.TerminatorLength = length;
 }
Beispiel #40
0
 public string GetLParamAsString(StringEncoding encoding)
 {
     return Translate.ToString(LParam, encoding);
 }
Beispiel #41
0
 private void EncodeText(string source)
 {
     StringEncoding encoder = new StringEncoding (source);
     encoder.ReplaceCodesTable (StringEncoding.CharactersDefault);
     this.text = encoder.GetStringUnicode ();
 }
 public void Constructor2Caso1()
 {
     string data = "\u307b,\u308b,\u305a,\u3042,\u306d";
     StringEncoding converter = new StringEncoding (data, 932);
     Assert.AreEqual (data, converter.GetStringUnicode(), "CO2 C1");
 }
Beispiel #43
0
 public static UnmanagedStringHandle ToHandle(string str, StringEncoding encoding)
 {
     return new UnmanagedStringHandle(str, encoding);
 }
 /// <summary>
 /// Constructs a string attribute with specified encoding type.
 /// </summary>
 /// <param name="encodingType">The string encoding type</param>
 public StringAttribute(StringEncoding encodingType)
 {
     EncodingType = encodingType;
 }
 /// <summary>
 /// Constructs a string attribute.
 /// </summary>
 public StringAttribute()
 {
     EncodingType = StringEncoding.Unicode;
 }
Beispiel #46
0
 public static string ToString(IntPtr lParam, StringEncoding marshalAs, bool transformExceptionsToNull)
 {
     return ToString(lParam, 0, marshalAs, transformExceptionsToNull);
 }
Beispiel #47
0
 public static string ToString(IntPtr lParam, int length, StringEncoding marshalAs)
 {
     return ToString(lParam, length, marshalAs, false);
 }
Beispiel #48
0
 public ContactInfo FindContact(string searchValue, ContactInfoProperty searchCriterion, StringEncoding valueEncoding)
 {
     return FindContact(searchValue, searchCriterion, valueEncoding, StringComparison.Ordinal);
 }
Beispiel #49
0
        public ContactInfo FindContact(string searchValue, ContactInfoProperty searchCriterion, StringEncoding valueEncoding, StringComparison comparisonType)
        {
            if (searchValue == null)
                throw new ArgumentNullException("searchValues");

            foreach (IntPtr handle in GetContactHandles())
            {
                object value;
                ContactInfoPropertyType type;

                if (ContactInfo.GetProperty(handle, searchCriterion, out value, out type)
                    && searchValue.Equals(value.ToString(), comparisonType))
                    return ContactInfo.FromHandle(handle);
            }

            Debug.Assert(false);
            return null;
        }