public Link( uint folderID, Guid objectGUID, uint objectFolderTypeID, DateTime dateCreated )
 {
     FolderID           = folderID;
     ObjectGUID         = new UUID( objectGUID.ToByteArray() ).ToString();
     ObjectFolderTypeID = objectFolderTypeID;
     DateCreated        = dateCreated;
 }
Beispiel #2
0
        public void DeleteMessageToSend(Guid transactionId)
        {
            Api.JetSetCurrentIndex(session, outgoing, "by_tx_id");

            Api.MakeKey(session, outgoing, transactionId.ToByteArray(), MakeKeyGrbit.NewKey);
            if (Api.TrySeek(session, outgoing, SeekGrbit.SeekEQ) == false)
                return;
            Api.MakeKey(session, outgoing, transactionId.ToByteArray(), MakeKeyGrbit.NewKey);
            try
            {
                Api.JetSetIndexRange(session, outgoing,
                                     SetIndexRangeGrbit.RangeInclusive | SetIndexRangeGrbit.RangeUpperLimit);
            }
            catch (EsentErrorException e)
            {
                if (e.Error!=JET_err.NoCurrentRecord)
                    throw;
                return;
            }
            do
            {
                logger.DebugFormat("Deleting output message {0}",
                    Api.RetrieveColumnAsInt32(session, outgoing, outgoingColumns["msg_id"]).Value);
                Api.JetDelete(session, outgoing);
            } while (Api.TryMoveNext(session, outgoing));
        }
 public static Guid CreateFrom(Guid commitId, int aggregateVersion)
 {
     var data = new byte[20];
     commitId.ToByteArray().CopyTo(data, 0);
     BitConverter.GetBytes(aggregateVersion).CopyTo(data, 16);
     return CreateFrom(@namespace, 5, data);
 }
        public LocalizationSettingsAggregateData GetSettings(Guid entityId, string language)
        {
            return ExecuteTransaction<LocalizationSettingsAggregateData>((connection, transaction) =>
            {
                var settingsAggregateData = connection.Query<LocalizationSettingsAggregateData>(
                    @"SELECT ID, ENTITY_ID, PARENT_ID, LANGUAGE, FORMATTING
                    FROM LOCALIZATION_SETTINGS
                    WHERE ENTITY_ID = :entity_id",
                    new { entity_id = entityId.ToByteArray() },
                    transaction).FirstOrDefault();

                settingsAggregateData.Localizations = connection.Query<LocalizationData>(
                    @"SELECT ID, LOCALIZATION_SETTINGS_ID, KEY, VALUE
                    FROM LOCALE_OVERRIDES
                    WHERE LOCALIZATION_SETTINGS_ID = :id",
                    new { id = settingsAggregateData.Id },
                    transaction).ToList();

                settingsAggregateData.Formattings = connection.Query<FormattingData>(
                    @"SELECT ID, LOCALIZATION_SETTINGS_ID, KEY, VALUE
                    FROM FORMATTING_OVERRIDES
                    WHERE LOCALIZATION_SETTINGS_ID = :id",
                    new { id = settingsAggregateData.Id },
                    transaction).ToList();

                return settingsAggregateData;
            });
        }
Beispiel #5
0
        internal static bool IdEquals(ImmutableArray<byte> left, Guid rightGuid, uint rightStamp)
        {
            if (left.Length != 20)
            {
                // invalid id
                return false;
            }

            byte[] guidBytes = rightGuid.ToByteArray();
            for (int i = 0; i < guidBytes.Length; i++)
            {
                if (guidBytes[i] != left[i])
                {
                    return false;
                }
            }

            byte[] stampBytes = BitConverter.GetBytes(rightStamp);
            for (int i = 0; i < stampBytes.Length; i++)
            {
                if (stampBytes[i] != left[guidBytes.Length + i])
                {
                    return false;
                }
            }

            return true;
        }
        private static Guid CreateFrom(Guid namespaceId, int version, byte[] nameBytes)
        {
            if (version != 3 && version != 5)
                throw new ArgumentOutOfRangeException("version", "version must be either 3 or 5.");

            if (nameBytes == null)
                throw new ArgumentNullException("nameBytes");

            // convert the namespace UUID to network order (step 3)
            var namespaceBytes = namespaceId.ToByteArray();
            SwapByteOrder(namespaceBytes);

            // comput the hash of the name space ID concatenated with the name (step 4)
            byte[] hash;
            using (var algorithm = version == 3 ? (HashAlgorithm) MD5.Create() : SHA1.Create())
            {
                algorithm.TransformBlock(namespaceBytes, 0, namespaceBytes.Length, null, 0);
                algorithm.TransformFinalBlock(nameBytes, 0, nameBytes.Length);
                hash = algorithm.Hash;
            }

            // most bytes from the hash are copied straight to the bytes of the new GUID (steps 5-7, 9, 11-12)
            var newGuid = new byte[16];
            Array.Copy(hash, 0, newGuid, 0, 16);

            // set the four most significant bits (bits 12 through 15) of the time_hi_and_version field to the appropriate 4-bit version number from Section 4.1.3 (step 8)
            newGuid[6] = (byte) ((newGuid[6] & 0x0F) | (version << 4));

            // set the two most significant bits (bits 6 and 7) of the clock_seq_hi_and_reserved to zero and one, respectively (step 10)
            newGuid[8] = (byte) ((newGuid[8] & 0x3F) | 0x80);

            // convert the resulting UUID to local byte order (step 13)
            SwapByteOrder(newGuid);
            return new Guid(newGuid);
        }
 public void BytesToGuid()
 {
     var guid = new Guid("21EC2020-3AEA-1069-A2DD-08002B30309D");
     var bytes = guid.ToByteArray();
     dynamic result = new { Bar = bytes }.ToExpando(new { Bar = typeof(Guid) });
     Assert.AreEqual(guid, result.Bar);
 }
Beispiel #8
0
		public static void AssertNotModifiedByAnotherTransaction(TableStorage storage, ITransactionStorageActions transactionStorageActions, string key, Table.ReadResult readResult, TransactionInformation transactionInformation)
		{
			if (readResult == null)
				return;
			var txIdAsBytes = readResult.Key.Value<byte[]>("txId");
			if (txIdAsBytes == null)
				return;

			var txId = new Guid(txIdAsBytes);
			if (transactionInformation != null && transactionInformation.Id == txId)
			{
				return;
			}

			var existingTx = storage.Transactions.Read(new RavenJObject { { "txId", txId.ToByteArray() } });
			if (existingTx == null)//probably a bug, ignoring this as not a real tx
				return;

			var timeout = existingTx.Key.Value<DateTime>("timeout");
			if (SystemTime.UtcNow > timeout)
			{
				transactionStorageActions.RollbackTransaction(txId);
				return;
			}

			throw new ConcurrencyException("Document '" + key + "' is locked by transacton: " + txId);
		}
 private void setFieldsFromGuid(Guid guid, TeamPicture teamPicture)
 {
     teamPicture.Message = guid.ToString();
     teamPicture.Picture = guid.ToByteArray();
     teamPicture.PictureHeight = HEIGHT;
     teamPicture.PictureWidth = WIDTH;
 }
Beispiel #10
0
    public GUIDObject(Object target, System.Guid guid)
    {
        Target = target;

        GUID           = guid;
        SerializedGUID = guid.ToByteArray();
    }
Beispiel #11
0
        public static string GetConnectionString(Guid OrgID)
        {
            if (OrgID == Guid.Empty)
            {
                UserContext user = UserContext.Current;
                if (user != null)
                {
                    if (user.SelectedOrganization != null)
                        return user.SelectedOrganization.ConnectionString;
                }
                if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Session != null && System.Web.HttpContext.Current.Session["OrgId"] != null)
                    OrgID = (Guid)System.Web.HttpContext.Current.Session["OrgId"];
            }
            else
            {
                byte[] _guid = OrgID.ToByteArray();
                if (_guid[0] != 0 && _guid[1] == 0 && _guid[2] == 0 && _guid[15] == 0)
                {
                    if (ConfigurationManager.ConnectionStrings["bigWebDesk.ConnectionString" + _guid[0].ToString()] != null)
                    {
                        if (!string.IsNullOrEmpty(ConfigurationManager.ConnectionStrings["bigWebDesk.ConnectionString" + _guid[0].ToString()].ConnectionString))
                            return ConfigurationManager.ConnectionStrings["bigWebDesk.ConnectionString" + _guid[0].ToString()].ConnectionString;
                    }
                }
            }

            string conn = Micajah.Common.Bll.Providers.OrganizationProvider.GetConnectionString(OrgID, false);
            if (string.IsNullOrEmpty(conn))
            {
                if (ConfigurationManager.ConnectionStrings["bigWebDesk.ConnectionString"] != null)
                    conn = ConfigurationManager.ConnectionStrings["bigWebDesk.ConnectionString"].ConnectionString;
            }

            return conn;
        }
Beispiel #12
0
        /// <summary>
        /// Инициализирует новый экземпляр класса
        /// </summary>
        /// <param name="identifier">Идентификатор параметра</param>
        /// <param name="p_time">Время параметра</param>
        /// <param name="val">Значение параметра в указанное время</param>
        public DataBaseParameterValue(Guid identifier, long p_time, float val)
        {
            guid = new Guid(identifier.ToByteArray());
            time = p_time;

            p_value = val;
        }
Beispiel #13
0
        public Base GetCompletedWork(Guid jobGuid)
        {
            if (_ConnectionToManager == null || !_ConnectionToManager.IsConnected()) throw new Exception("Not connected to the manager");

            while (true)
            {
                Packet p = new Packet(1100);
                p.Add(jobGuid.ToByteArray(),true);
                _ConnectionToManager.SendPacket(p);
                Stopwatch sendTime = new Stopwatch();
                sendTime.Start();
                while (sendTime.ElapsedMilliseconds < _CommsTimeout)
                {
                    if (_ConnectionToManager.GetPacketsToProcessCount() > 0)
                    {
                        foreach (Packet packet in _ConnectionToManager.GetPacketsToProcess())
                        {
                            switch (packet.Type)
                            {
                                case 1101:
                                    return null;
                                case 1102:
                                    Object[] packetObjects = packet.GetObjects();
                                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                                    return (Base) binaryFormatter.Deserialize(new MemoryStream((Byte[]) packetObjects[0]));
                            }
                        }
                        Thread.Sleep(100);
                    }
                }
                if (_ConnectionToManager.IsConnected())_ConnectionToManager.Disconnect();
                _ConnectionToManager.Connect(_IpAddress, _Port, 204800);
            }
            return null;
        }
Beispiel #14
0
        public static byte[] PackScreenCaptureData(Guid id, Image image, Rectangle bounds)
        {
            var idData = id.ToByteArray();

            byte[] imgData;
            using (var ms = new MemoryStream())
            {
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                imgData = ms.ToArray();
            }

            var topData = BitConverter.GetBytes(bounds.Top);
            var botData = BitConverter.GetBytes(bounds.Bottom);
            var leftData = BitConverter.GetBytes(bounds.Left);
            var rightData = BitConverter.GetBytes(bounds.Right);

            var sizeOfInt = topData.Length;
            var result = new byte[imgData.Length + (4 * sizeOfInt) + idData.Length];
            Array.Copy(topData, 0, result, 0, topData.Length);
            Array.Copy(botData, 0, result, sizeOfInt, botData.Length);
            Array.Copy(leftData, 0, result, 2 * sizeOfInt, leftData.Length);
            Array.Copy(rightData, 0, result, 3 * sizeOfInt, rightData.Length);
            Array.Copy(imgData, 0, result, 4 * sizeOfInt, imgData.Length);
            Array.Copy(idData, 0, result, (4 * sizeOfInt) + imgData.Length, idData.Length);

            return result;
        }
    public void TestMethod5()
    {
      Guid guid = new Guid("{d3902802-2842-4d50-bc5b-134c27efe5ff}");
      Console.WriteLine(guid);

      byte[] guidBytes = guid.ToByteArray();
      byte[] sifted = new byte[guidBytes.Length + 1];
      Buffer.BlockCopy(guidBytes, 0, sifted, 0, guidBytes.Length);

      BigInteger bigInteger = new BigInteger(sifted);
      Assert.AreEqual(BigInteger.One, bigInteger.Sign);

      string encoded = BaseConvert.ToBaseString(bigInteger, BaseConvert.Base62);
      Assert.IsNotNull(encoded);
      Console.WriteLine(encoded);

      BigInteger result = BaseConvert.FromBaseString(encoded, BaseConvert.Base62);
      Assert.IsNotNull(result);

      byte[] actualBytes = result.ToByteArray();
      byte[] bytes = new byte[16];

      int count = Math.Min(bytes.Length, actualBytes.Length);
      Buffer.BlockCopy(actualBytes, 0, bytes, 0, count);

      Guid actual = new Guid(bytes);
      Assert.AreEqual(guid, actual);
      Console.WriteLine(actual);
    }
Beispiel #16
0
        /// <summary>
        /// Conversion of a GUID to a string 
        /// representing the GUID 
        /// </summary>
        /// <param name="guid">The GUID to convert</param>
        /// <returns>IFC (base64) encoded GUID string</returns>
        public static string ToIfcGuid( Guid guid )
        {
            uint[] num = new uint[6];
              char[] str = new char[22];
              int i, n;
              byte[] b = guid.ToByteArray();

              // Creation of six 32 Bit integers from the components of the GUID structure
              num[0] = ( uint ) ( BitConverter.ToUInt32( b, 0 ) / 16777216 );
              num[1] = ( uint ) ( BitConverter.ToUInt32( b, 0 ) % 16777216 );
              num[2] = ( uint ) ( BitConverter.ToUInt16( b, 4 ) * 256 + BitConverter.ToInt16( b, 6 ) / 256 );
              num[3] = ( uint ) ( ( BitConverter.ToUInt16( b, 6 ) % 256 ) * 65536 + b[8] * 256 + b[9] );
              num[4] = ( uint ) ( b[10] * 65536 + b[11] * 256 + b[12] );
              num[5] = ( uint ) ( b[13] * 65536 + b[14] * 256 + b[15] );

              // Conversion of the numbers into a system using a base of 64
              n = 2;
              int pos = 0;
              for( i = 0; i < 6; i++ )
              {
            cv_to_64( num[i], ref str, pos, n );
            pos += n; n = 4;
              }
              return new String( str );
        }
Beispiel #17
0
        static private string ConvertToIFCGuid(System.Guid guid)
        {
            byte[]  byteArray = guid.ToByteArray();
            ulong[] num       = new ulong[6];
            num[0] = byteArray[3];
            num[1] = byteArray[2] * (ulong)65536 + byteArray[1] * (ulong)256 + byteArray[0];
            num[2] = byteArray[5] * (ulong)65536 + byteArray[4] * (ulong)256 + byteArray[7];
            num[3] = byteArray[6] * (ulong)65536 + byteArray[8] * (ulong)256 + byteArray[9];
            num[4] = byteArray[10] * (ulong)65536 + byteArray[11] * (ulong)256 + byteArray[12];
            num[5] = byteArray[13] * (ulong)65536 + byteArray[14] * (ulong)256 + byteArray[15];

            char[] buf    = new char[22];
            int    offset = 0;

            for (int ii = 0; ii < 6; ii++)
            {
                int len = (ii == 0) ? 2 : 4;
                for (int jj = 0; jj < len; jj++)
                {
                    buf[offset + len - jj - 1] = s_ConversionTable_2X[(int)(num[ii] % 64)];
                    num[ii] /= 64;
                }
                offset += len;
            }

            return(new string(buf));
        }
Beispiel #18
0
        /// <summary>
        /// 从 SQL SERVER 返回的 GUID 中生成时间信息
        /// </summary>
        /// <param name="guid">包含时间信息的 COMB </param>
        /// <returns>时间</returns>
        public static DateTime GetDateFromComb(System.Guid guid)
        {
            DateTime baseDate = new DateTime(1900, 1, 1);

            byte[] daysArray  = new byte[4];
            byte[] msecsArray = new byte[4];
            byte[] guidArray  = guid.ToByteArray();

            // Copy the date parts of the guid to the respective byte arrays.
            Array.Copy(guidArray, guidArray.Length - 6, daysArray, 2, 2);
            Array.Copy(guidArray, guidArray.Length - 4, msecsArray, 0, 4);

            // Reverse the arrays to put them into the appropriate order
            Array.Reverse(daysArray);
            Array.Reverse(msecsArray);

            // Convert the bytes to ints
            int days  = BitConverter.ToInt32(daysArray, 0);
            int msecs = BitConverter.ToInt32(msecsArray, 0);

            DateTime date = baseDate.AddDays(days);

            date = date.AddMilliseconds(msecs * 3.333333);

            return(date);
        }
Beispiel #19
0
        public void ConsumeMessage(Guid msgId, Func<DateTime, string, bool> shouldConsumeMessage)
        {
            var key = new JObject { { "MsgId", msgId.ToByteArray() } };
            var readResult = messages.Read(key);
            if (readResult == null)
            {
                var pendingResult = pendingMessages.Read(key);
                if (pendingResult != null)
                {
                    pendingMessages.Remove(key);
                    var pendingQueue = pendingResult.Key.Value<string>("Queue");
                    var pendingExpiry = pendingResult.Key.Value<DateTime>("Expiry");
                    if (shouldConsumeMessage(pendingExpiry, pendingQueue) == false)
                    {
                        ((JObject)pendingResult.Key).Remove("Hide");
                        messages.UpdateKey(pendingResult.Key);
                    }
                    else
                    {
                        queuesStorageActions.DecrementMessageCount(pendingQueue);
                    }
                }
                return;
            }

            var queue = readResult.Key.Value<string>("Queue");
            var epxiry = readResult.Key.Value<DateTime>("Expiry");
            if (shouldConsumeMessage(epxiry, queue) == false)
                return;
            messages.Remove(key);
            queuesStorageActions.DecrementMessageCount(queue);
        }
Beispiel #20
0
 public override Linq.Translation.SqlGen.SqlStatement GetLiteral(Guid literal)
 {
     var bytes = literal.ToByteArray();
       var hex = HexUtil.ByteArrayToHex(bytes);
       var result = "X'" + hex + "'";
       return result;
 }
Beispiel #21
0
        public void AddMarkerReq(Card card, Guid id, string name, ushort count, ushort origCount, bool isScriptChange)
        {
            //Log.Info("[ProtOut] AddMarkerReq");

            if(Program.Client == null)return;
            MemoryStream stream = new MemoryStream(512);
            stream.Seek(4, SeekOrigin.Begin);
            BinaryWriter writer = new BinaryWriter(stream);

              if (Program.Client.Muted != 0)
              writer.Write(Program.Client.Muted);
              else
              writer.Write(0);
            writer.Write((byte)59);
            writer.Write(card.Id);
            writer.Write(id.ToByteArray());
            writer.Write(name);
            writer.Write(count);
            writer.Write(origCount);
            writer.Write(isScriptChange);

            writer.Flush(); writer.Seek(0, SeekOrigin.Begin);
            writer.Write((int)stream.Length);
            writer.Close();
            Send(stream.ToArray());
        }
 public override string ToString(Guid g, bool upcase, bool newline)
 {
     if (IsLoopBack(g)) return "::1" + (newline?"\r\n":"");
     byte[] bytes = g.ToByteArray();
     if (IsIPv4(g)) return string.Format("{0}.{1}.{2}.{3}", bytes[12], bytes[13], bytes[14], bytes[15]) + (newline?"\r\n":"");
     return (new System.Net.IPAddress(bytes)).ToString() + (newline?"\r\n":"");
 }
Beispiel #23
0
    public Crypto(Guid sessionId, byte[] cipherKey, byte[] cipherNonce, byte[] macKey)
    {
        if (cipherKey.Length != 16) {
            throw new System.ArgumentException("Chipher Key must be 16 bytes");
        }

        if (cipherNonce.Length != 8) {
            throw new System.ArgumentException("Chipher Nonce must be 8 bytes");
        }

        if (macKey.Length != 32) {
            throw new System.ArgumentException("Mac Key must be 32 bytes");
        }

        _sequence = 0;
        _sessionId = _TransposeGuidBytes(sessionId.ToByteArray());
        _cipherKey = cipherKey;
        _cipherNonce = cipherNonce;
        _macKey = macKey;

        if (_sessionId.Length != 16) {
            throw new System.ArgumentException("Session ID must be 16 bytes");
        }

        _cipherCounterSize = _cipherNonce.Length + sizeof(uint) + sizeof(uint);
    }
Beispiel #24
0
        //=== ?

        /// <summary> Creates a Form Guid. </summary>
        public static string Guid()
        {
            System.Guid g    = System.Guid.NewGuid();
            string      guid = Convert.ToBase64String(g.ToByteArray()).Replace("=", "").Replace("+", "").Replace("/", "");

            return(guid);
        }
Beispiel #25
0
        public string GetPinHash(Guid customerId, string pin)
        {
            var buffer = ASCIIEncoding.Default.GetBytes(pin + ConfigurationManager.AppSettings["PinSalt"]).Concat(customerId.ToByteArray()).ToArray();
            var hash = new SHA256Managed().ComputeHash(buffer);

            return ASCIIEncoding.UTF8.GetString(hash);
        }
        //
        // Converts Guid class to GUID structure that we can pass into native
        //
        internal static GUID ConvertGuidToGUID(Guid guid)
        {
            GUID newGuid = new GUID();

            if (guid != null){
                byte[] guidBytes = guid.ToByteArray();
                string guidString = guid.ToString();

                int startVal = 0;
                int endVal = guidString.IndexOf('-');
                newGuid.data1 = (uint)(Convert.ToUInt32(guidString.Substring(startVal, endVal - startVal), 16));
                startVal = endVal + 1;
                endVal = guidString.IndexOf('-', endVal + 1);
                newGuid.data2 = (ushort)(Convert.ToUInt16(guidString.Substring(startVal, endVal - startVal), 16));
                startVal = endVal + 1;
                endVal = guidString.IndexOf('-', endVal + 1);
                newGuid.data3 = (ushort)(Convert.ToUInt16(guidString.Substring(startVal, endVal - startVal), 16));
                newGuid.data4 = guidBytes[8];
                newGuid.data5 = guidBytes[9];
                newGuid.data6 = guidBytes[10];
                newGuid.data7 = guidBytes[11];
                newGuid.data8 = guidBytes[12];
                newGuid.data9 = guidBytes[13];
                newGuid.data10 = guidBytes[14];
                newGuid.data11 = guidBytes[15];
            }
            return newGuid;
        }
Beispiel #27
0
        /// <summary>
        /// Generate a namespace GUID (V3 or V5) with a given algorithm
        /// </summary>
        /// <param name="namespaceId">The namespace we're generating the GUID in</param>
        /// <param name="name">The name we're generating the GUID for</param>
        /// <param name="version">The version to generate (MD5 or SHA1)</param>
        /// <returns></returns>
        private static UUID GenerateNameBased(System.Guid namespaceId, string name, GuidVersion version)
        {
            if (version != GuidVersion.MD5 && version != GuidVersion.SHA1)
            {
                throw new ArgumentException("version", "Name based guids can only be version 3, or 5");
            }

            if (String.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name", "The name parameter cannot be empty or null");
            }

            byte[] nameBytes      = Encoding.UTF8.GetBytes(name);
            byte[] namespaceBytes = namespaceId.ToByteArray();

            if (BitConverter.IsLittleEndian)
            {
                ToggleEndianess(namespaceBytes);
            }

            var hash = version == GuidVersion.MD5 ?
                       HashProvider.GenerateMD5Hash(namespaceBytes, nameBytes) :
                       HashProvider.GenerateSHA1Hash(namespaceBytes, nameBytes);

            if (BitConverter.IsLittleEndian)
            {
                ToggleEndianess(hash);
            }

            return(GenerateFromComponents(
                       hash.Skip(Constants.TIMESTAMP_BYTE_INDEX).Take(Constants.TIME_BYTES_LENGTH).ToArray(),
                       hash.Skip(Constants.CLOCK_SEQUENCE_BYTE_INDEX).Take(Constants.CLOCK_SEQUENCE_BYTES_LENGTH).ToArray(),
                       hash.Skip(Constants.NODE_BYTE_INDEX).Take(Constants.NODE_BYTES_LENGTH).ToArray(),
                       version, GuidVariant.RFC4122));
        }
Beispiel #28
0
 public static string HashPassword(string password, Guid salt)
 {
     //this is a many iterations of hashing with sha256... try and steal our passwords now!
     int iterations = (int)password[0];
     SHA256 passwordHash = SHA256.Create();
     byte[] passwordBytes = new byte[(password.Length * sizeof(char))];
     System.Buffer.BlockCopy(password.ToCharArray(), 0, passwordBytes, 0, passwordBytes.Length);
     passwordBytes = passwordBytes.Concat(salt.ToByteArray()).ToArray();
     passwordHash.ComputeHash(passwordBytes);
     for (int i = 0; i < iterations; i++)
     {
         var computedBytes = passwordHash.Hash.Concat(salt.ToByteArray()).ToArray();
         passwordHash.ComputeHash(computedBytes);
     }
     return Convert.ToBase64String(passwordHash.Hash);
 }
Beispiel #29
0
 public static string Encode(Guid guid)
 {
     string enc = Convert.ToBase64String(guid.ToByteArray());
     enc = enc.Replace("/", "_");
     enc = enc.Replace("+", "-");
     return enc.Substring(0, 22);
 }
 public static CriticalAllocHandle FromGuid(Guid input)
 {
     int size = Marshal.SizeOf(typeof(Guid));
     CriticalAllocHandle handle = CriticalAllocHandle.FromSize(size);
     Marshal.Copy(input.ToByteArray(), 0, (IntPtr) handle, size);
     return handle;
 }
Beispiel #31
0
        /// <summary>
        /// Convert from a <see cref="System.Guid"/> to a <see cref="System.Protobuf.guid"/>
        /// </summary>
        /// <param name="guid"><see cref="System.Guid"/> to convert</param>
        /// <returns>A <see cref="System.Protobuf.guid"/></returns>
        public static System.Protobuf.guid ToProtobuf(this System.Guid guid)
        {
            var protobufGuid = new System.Protobuf.guid();

            protobufGuid.Value = ByteString.CopyFrom(guid.ToByteArray());
            return(protobufGuid);
        }
Beispiel #32
0
 public static byte[] InitCommandRequest(Guid guid, string name)
 {
     var data = new byte[16 + Encoding.Unicode.GetByteCount(name) + 1];
     Array.Copy(guid.ToByteArray(), data, 16);
     Assign (name, data, 16);
     return Encode(PACKET_TYPE_INIT_COMMAND_REQUEST, data);
 }
 private string GetPath(Guid identity)
 {
     var bytes = identity.ToByteArray();
     var a = bytes[3].ToHex();
     var b = bytes[2].ToHex();
     return Path.Combine(RootPath, a, b);
 }
Beispiel #34
0
        // Generate a Version 5 (SHA1 Name Based) Guid from a name.
        public static Guid GenerateGuidFromName(string name)
        {
            // Any fixed GUID will do for a namespace.
            Guid namespaceId = new Guid("28F1468D-672B-489A-8E0C-7C5B3030630C");

            using (SHA1 hasher = SHA1.Create())
            {
                var nameBytes = System.Text.Encoding.UTF8.GetBytes(name ?? string.Empty);
                var namespaceBytes = namespaceId.ToByteArray();

                SwapGuidByteOrder(namespaceBytes);

                var streamToHash = new byte[namespaceBytes.Length + nameBytes.Length];

                Array.Copy(namespaceBytes, streamToHash, namespaceBytes.Length);
                Array.Copy(nameBytes, 0, streamToHash, namespaceBytes.Length, nameBytes.Length);

                var hashResult = hasher.ComputeHash(streamToHash);

                var res = new byte[16];

                Array.Copy(hashResult, res, res.Length);

                unchecked { res[6] = (byte)(0x50 | (res[6] & 0x0F)); }
                unchecked { res[8] = (byte)(0x40 | (res[8] & 0x3F)); }

                SwapGuidByteOrder(res);

                return new Guid(res);
            }
        }
Beispiel #35
0
 internal static string Compress22(Guid newGuid)
 {
     string modifiedBase64 = Convert.ToBase64String(newGuid.ToByteArray())
         .Replace('+', '-').Replace('/', '_')    // avoid invalid URL characters
         .Substring(0, 22);                      // truncate trailing "==" characters
     return modifiedBase64;
 }
Beispiel #36
0
        public static string Encode(System.Guid guid)
        {
            string base64String = Convert.ToBase64String(guid.ToByteArray());

            base64String = base64String.Replace("/", "_").Replace("+", "-");
            return(base64String.Substring(0, 22));
        }
Beispiel #37
0
        // Creates a version 5 (SHA-1) UUID following section 4.3 of RFC 4122.
        // Unlike the more common version 4 UUID algorithm, this uses a stable hash
        // based on an input name, so the same name always produces the same UUID.
        public static Guid GetVersion5Uuid(Guid namespaceId, string name)
        {
            // Convert inputs to byte arrays.
            var namespaceBytes = namespaceId.ToByteArray();
            var nameBytes = Encoding.UTF8.GetBytes(name);

            // Convert to network byte ordering.
            SwapByteOrder(namespaceBytes);

            // Concatenate the namespace and name.
            var inputBytes = namespaceBytes.Concat(nameBytes).ToArray();

            // Take the first 16 bytes of the SHA-1 hash.
            byte[] result;

            using (var sha1 = SHA1.Create())
            {
                result = sha1.ComputeHash(inputBytes).Take(16).ToArray();
            }

            // Set the variant bits (MSB0-1 = 2 means standard RFC 4122 UUID).
            result[8] &= 0x3F;
            result[8] |= 2 << 6;

            // Set the version bits (MSB0-3 = 5 means SHA-1 name-based UUID).
            result[6] &= 0x0F;
            result[6] |= 5 << 4;

            // Convert to local byte ordering.
            SwapByteOrder(result);

            return new Guid(result);
        }
Beispiel #38
0
 internal unsafe void SetGuid(System.Guid Value)
 {
     fixed(Byte *P = Guid)
     {
         Byte[] Bytes = Value.ToByteArray();
         Marshal.Copy(Bytes, 0, (IntPtr)P, 16);
     }
 }
Beispiel #39
0
        /// <summary>
        /// Returns a new Guid COMB, consisting of the provided Guid and provided timestamp.
        /// </summary>
        public static System.Guid Create(System.Guid value, DateTime timestamp)
        {
            var bytes   = value.ToByteArray();
            var dtbytes = Utilities.DateTimeToBytes(timestamp);

            Array.Copy(dtbytes, 0, bytes, StartIndexSqlServer, Utilities.NumDateBytes);
            return(new System.Guid(bytes));
        }
Beispiel #40
0
 void generateLine()
 {
     System.Guid g = System.Guid.NewGuid();
     guid = System.Convert.ToBase64String(g.ToByteArray());
     Debug.Log(guid);
     guid = guid.Replace("=", "");
     guid = guid.Replace("+", "");
 }
Beispiel #41
0
 public static Qualifier ToQualifier(this System.Guid guid)
 {
     return(new GlobalUniqueId {
         Guid = new Guid {
             Raw = guid.ToByteArray().ToByteString()
         }
     }.ToQualifier());
 }
        public static ShortUid ToShortUid(System.Guid uid)
        {
            var  arr  = uid.ToByteArray();
            long low  = (int)(arr[3] << 24) | (int)(arr[2] << 16) | (int)(arr[1] << 8) | (int)arr[0];
            long high = (long)((int)(arr[7] << 24) | (int)(arr[6] << 16) | (int)(arr[5] << 8) | (int)arr[4]) << 32;

            return(new ShortUid(high | low));
        }
Beispiel #43
0
        /// <summary>
        /// Returns the timestamp previously stored in a COMB Guid value.
        /// </summary>
        public static DateTime GetTimestamp(System.Guid comb)
        {
            var bytes   = comb.ToByteArray();
            var dtbytes = new byte[Utilities.NumDateBytes];

            Array.Copy(bytes, StartIndexSqlServer, dtbytes, 0, Utilities.NumDateBytes);
            return(Utilities.BytesToDateTime(dtbytes));
        }
Beispiel #44
0
 public static GlobalUniqueId ToGlobalUniqueId(this System.Guid guid)
 {
     return(new GlobalUniqueId {
         Guid = new Guid {
             Raw = guid.ToByteArray().ToByteString()
         }
     });
 }
        private uint AppendGuid(System.Guid guid)
        {
            uint index;

            index = (uint)_rawStream.Length / GuidStream.GuidSize + 1;
            AppendRawData(guid.ToByteArray());
            return(index);
        }
Beispiel #46
0
        /// <summary>
        ///    Renders the current instance as a raw ASF object
        ///    containing specified data.
        /// </summary>
        /// <param name="data">
        ///    A <see cref="ByteVector" /> object containing the data to
        ///    contained in the rendered version of the current
        ///    instance.
        /// </param>
        /// <returns>
        ///    A <see cref="ByteVector" /> object containing the
        ///    rendered version of the current instance.
        /// </returns>
        /// <remarks>
        ///    Child classes implementing <see cref="Render()" /> should
        ///    render their contents and then send the data through this
        ///    method to produce the final output.
        /// </remarks>
        protected ByteVector Render(ByteVector data)
        {
            ulong      length = (ulong)((data != null ? data.Count : 0) + 24);
            ByteVector v      = id.ToByteArray();

            v.Add(RenderQWord(length));
            v.Add(data);
            return(v);
        }
    private static void WriteGuidAsBits(this IList <byte> byteArray, System.Guid value, ref int startingBit)
    {
        var array = value.ToByteArray();

        for (int i = 0; i < GUID_BYTES; i++)
        {
            byteArray.WriteByteAsBits(array[i], ref startingBit);
        }
    }
Beispiel #48
0
    private string GeneratePlayerId()
    {
        System.Guid guid     = System.Guid.NewGuid();
        string      nickName = System.Convert.ToBase64String(guid.ToByteArray());

        nickName = nickName.Replace("=", "");
        nickName = nickName.Replace("+", "");
        return(string.Format("USER-{0}", nickName));
    }
        /// <summary>
        ///  Вывод серийного номера VCI CAN-адаптера
        /// </summary>
        string GetSerialNumberText(ref object serialNumberGuid)
        {
            string resultText;


            if (serialNumberGuid.GetType() == typeof(System.Guid))
            {
                System.Guid tempGuid  = (System.Guid)serialNumberGuid;
                byte[]      byteArray = tempGuid.ToByteArray();
                if (((char)byteArray[0] == 'H') && ((char)byteArray[1] == 'W'))
                {
                    resultText = "";
                    int i = 0;
                    while (true)
                    {
                        if (byteArray[i] != 0)
                        {
                            resultText += (char)byteArray[i];
                        }
                        else
                        {
                            break;
                        }
                        i++;

                        if (i == byteArray.Length)
                        {
                            break;
                        }
                    }
                }
                else
                {
                    resultText = serialNumberGuid.ToString();
                }
            }
            else
            {
                string tempString = (string)(string)serialNumberGuid;
                resultText = "";
                for (int i = 0; i < tempString.Length; i++)
                {
                    if (tempString[i] != 0)
                    {
                        resultText += tempString[i];
                    }
                    else
                    {
                        break;
                    }
                }
            }

            return(resultText);
        }
    private static void PantryItemSetResetID()
    {
        GameObject     selectedGameObject = Selection.activeGameObject;
        mcSceneJsonObj script             = selectedGameObject.GetComponent <mcSceneJsonObj>();

        System.Guid _GUID = System.Guid.NewGuid();
        byte[]      gb    = _GUID.ToByteArray();
        Int32       newId = System.BitConverter.ToInt32(gb, 0) & 0x7fffffff;

        script.Id = newId;
    }
Beispiel #51
0
        public static System.Guid EnsureStartsWithLetter(System.Guid guid)
        {
            var bytes = guid.ToByteArray();

            if ((bytes[3] & 0xf0) < 0xa0)
            {
                bytes[3] |= 0xc0;
                return(new System.Guid(bytes));
            }
            return(guid);
        }
Beispiel #52
0
    /// <summary>
    /// GUID をSerializedProperty に対して設定する
    /// ここで指定する SerializedProperty は、byte 配列であること
    /// </summary>
    /// <param name="property"></param>
    /// <param name="guid"></param>
    void setGUIDToProperty(SerializedProperty property, System.Guid guid)
    {
        var guidToByteArray = guid.ToByteArray();

        property.ClearArray();
        for (int i = 0; i < 16; ++i)
        {
            property.InsertArrayElementAtIndex(i);
            var element = property.GetArrayElementAtIndex(i);
            element.intValue = guidToByteArray[i];
        }
    }
    public static string GetRandomString()
    {
        System.Guid g = System.Guid.NewGuid();

        string GuidString = System.Convert.ToBase64String(g.ToByteArray());

        GuidString = GuidString.Replace("=", "");
        GuidString = GuidString.Replace("+", "");
        GuidString = GuidString.Replace("/", "");

        return(GuidString);
    }
 public TrackingEventDataWithIDs(
     System.Guid _playerGuid,
     System.Guid _gameVersionGuid,
     TrackingEvent _trackingEvent,
     CustomData _customData = null,
     string _section        = null,
     int[] _coordinates     = null
     ) : base(_trackingEvent, _customData, _section, _coordinates)
 {
     player      = new System.Guid(_playerGuid.ToByteArray());
     gameVersion = new System.Guid(_gameVersionGuid.ToByteArray());
 }
Beispiel #55
0
        /// <summary>
        /// Returns the timestamp previously stored in a COMB Guid value.
        /// </summary>
        public static DateTime GetTimestamp(System.Guid comb)
        {
            var bytes   = comb.ToByteArray();
            var dtbytes = new byte[Utilities.NumDateBytes];

            Array.Copy(bytes, 0, dtbytes, 0, Utilities.NumDateBytes);

            // Move nybbles 5-8 to 6-9, overwriting the existing 9 (version "4")
            dtbytes[4] = (byte)((byte)(dtbytes[3] << 4) | (byte)(dtbytes[4] & 0x0F));
            dtbytes[3] = (byte)((byte)(dtbytes[2] << 4) | (byte)(dtbytes[3] >> 4));
            dtbytes[2] = (byte)(dtbytes[2] >> 4);
            return(Utilities.BytesToDateTime(dtbytes));
        }
Beispiel #56
0
        /// <summary>
        /// convert guid to uniquecode(Upper)
        /// </summary>
        /// <param name="value">Guid value</param>
        /// <returns>uniquecode value</returns>
        public static string ToUniqueCode(this System.Guid value)
        {
            long i = 1;

            byte[] bytes = value.ToByteArray();
            foreach (byte b in bytes)
            {
                i *= ((int)b + 1);
            }
            string code = string.Format("{0:x}", i - DateTime.Now.Ticks);

            return(code);
        }
Beispiel #57
0
        public override ByteVector Render()
        {
            ByteVector output = stream_type.ToByteArray();

            output.Add(error_correction_type.ToByteArray());
            output.Add(RenderQWord(time_offset));
            output.Add(RenderDWord((uint)type_specific_data.Count));
            output.Add(RenderDWord((uint)error_correction_data.Count));
            output.Add(RenderWord(flags));
            output.Add(RenderDWord(reserved));
            output.Add(type_specific_data);
            output.Add(error_correction_data);
            return(Render(output));
        }
Beispiel #58
0
        /// <summary>
        /// Returns a new Guid COMB, consisting of the provided Guid and provided timestamp.
        /// </summary>
        public static System.Guid Create(System.Guid value, DateTime timestamp)
        {
            var bytes   = value.ToByteArray();
            var dtbytes = Utilities.DateTimeToBytes(timestamp);

            // Nybble 6-9 move left to 5-8. Nybble 9 is set to "4" (the version)
            dtbytes[2] = (byte)((byte)(dtbytes[2] << 4) | (byte)(dtbytes[3] >> 4));
            dtbytes[3] = (byte)((byte)(dtbytes[3] << 4) | (byte)(dtbytes[4] >> 4));
            dtbytes[4] = (byte)(0x40 | (byte)(dtbytes[4] & 0x0F));

            // Overwrite the first six bytes
            Array.Copy(dtbytes, 0, bytes, 0, Utilities.NumDateBytes);
            return(new System.Guid(bytes));
        }
        /// <summary>
        ///     Renders the current instance as a raw ASF Description
        ///     Record.
        /// </summary>
        /// <returns>
        ///     A <see cref="ByteVector" /> object containing the
        ///     rendered version of the current instance.
        /// </returns>
        public ByteVector Render()
        {
            ByteVector value;

            switch (Type)
            {
            case DataType.Unicode:
                value = Object.RenderUnicode(strValue);
                break;

            case DataType.Bytes:
                value = byteValue;
                break;

            case DataType.Bool:
            case DataType.DWord:
                value = Object.RenderDWord((uint)longValue);
                break;

            case DataType.QWord:
                value = Object.RenderQWord(longValue);
                break;

            case DataType.Word:
                value = Object.RenderWord((ushort)longValue);
                break;

            case DataType.Guid:
                value = guidValue.ToByteArray();
                break;

            default:
                return(null);
            }

            var name = Object.RenderUnicode(Name);

            var output = new ByteVector
            {
                Object.RenderWord(LanguageListIndex),
                Object.RenderWord(StreamNumber),
                Object.RenderWord((ushort)name.Count),
                Object.RenderWord((ushort)Type),
                Object.RenderDWord((uint)value.Count),
                name,
                value
            };

            return(output);
        }
Beispiel #60
0
        /// <summary>
        /// 返回guid1是否大于guid2
        /// </summary>
        /// <param name="guid1"></param>
        /// <param name="guid2"></param>
        /// <returns></returns>
        public static bool GreaterThan(System.Guid guid1, System.Guid guid2)
        {
            var bytes1 = guid1.ToByteArray();
            var bytes2 = guid2.ToByteArray();

            for (int i = 0; i < 16; i++)
            {
                if (bytes1[i] < bytes2[i])
                {
                    return(false);
                }
            }
            return(true);
        }