Ejemplo n.º 1
0
        public static uint GetRandomNumber(uint maxNumber)
        {
            if (maxNumber < 1)
            {
                throw new System.Exception("The maxNumber value should be greater than 1");
            }
            // Generate a random number.
            uint random = CryptographicBuffer.GenerateRandomNumber();

            //create random number within maxNumber
            //this hurt my brain
            if (maxNumber < random)
            {
                uint randomMod = GetNDigits(random, (int)Math.Floor(Math.Log10(maxNumber) + 1));
                if (maxNumber < randomMod)
                {
                    return(randomMod - maxNumber);
                }
                else
                {
                    return(randomMod);
                }
            }
            else
            {
                return(random);
            }
        }
        private byte[] getCiphertext(byte[] key, byte[] message)
        {
            try
            {
                SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); // TODO: PKCS5 padding
                IBuffer          buffKey             = CryptographicBuffer.CreateFromByteArray(key);
                CryptographicKey ckey = objAlg.CreateSymmetricKey(buffKey);


                IBuffer buffPlaintext = CryptographicBuffer.CreateFromByteArray(message);
                byte[]  iv            = BitConverter.GetBytes(CryptographicBuffer.GenerateRandomNumber());
                IBuffer buffIV        = CryptographicBuffer.CreateFromByteArray(iv);
                IBuffer buffEncrypt   = CryptographicEngine.Encrypt(ckey, buffPlaintext, buffIV);

                byte[] ret;
                CryptographicBuffer.CopyToByteArray(buffEncrypt, out ret);

                /*Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                 * cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"));*/

                return(Util.join(iv, ret));
            }
            catch (/*NoSuchAlgorithmException | NoSuchPaddingException | java.security.InvalidKeyException | IllegalBlockSizeException | BadPaddingException*/ Exception e)
            {
                throw new Exception(e.Message);
            }
        }
Ejemplo n.º 3
0
 private void RandomTimer_Tick(object sender, object e)
 {
     if (randomCounter > 0)
     {
         randomCounter--;
     }
     if (BlackArrow.Visibility == Visibility.Visible || WhiteArrow.Visibility == Visibility.Visible)
     {
         BlackArrow.Visibility = Visibility.Collapsed;
         WhiteArrow.Visibility = Visibility.Collapsed;
     }
     else
     {
         uint random = CryptographicBuffer.GenerateRandomNumber();
         if (random % 2 == 0)
         {
             BlackArrow.Visibility = Visibility.Collapsed;
             WhiteArrow.Visibility = Visibility.Visible;
         }
         else
         {
             BlackArrow.Visibility = Visibility.Visible;
             WhiteArrow.Visibility = Visibility.Collapsed;
         }
         if (randomCounter == 0)
         {
             RandomAnimationTimer.Stop();
         }
     }
 }
Ejemplo n.º 4
0
        public UInt16 GenerateRndNumber()
        {
            // Generate a random number.
            UInt32 Rnd = CryptographicBuffer.GenerateRandomNumber() % 220; //limit between 0 and 220

            return((UInt16)Rnd);
        }
Ejemplo n.º 5
0
        async Task IrisSub()
        {
            var dic = new Dictionary <string, object>
            {
                { "seq_id", SeqId.ToString() },
                { "sub", new List <string>() },
                { "snapshot_at_ms", SnapshotAt.ToUnixTimeMiliSeconds() }
            };
            var json       = JsonConvert.SerializeObject(dic);
            var bytes      = Encoding.UTF8.GetBytes(json);
            var dataStream = new MemoryStream(512);

            using (var zlibStream = new ZlibStream(dataStream, CompressionMode.Compress, CompressionLevel.Level9, true))
            {
                await zlibStream.WriteAsync(bytes, 0, bytes.Length);
            }

            var compressed    = dataStream.GetWindowsRuntimeBuffer(0, (int)dataStream.Length);
            var publishPacket = new PublishPacket(QualityOfService.AtLeastOnce, false, false)
            {
                Payload   = compressed,
                PacketId  = (ushort)CryptographicBuffer.GenerateRandomNumber(),
                TopicName = "/ig_sub_iris"
            };
            await FbnsPacketEncoder.EncodePacket(publishPacket, _outboundWriter);
        }
Ejemplo n.º 6
0
        public static uint GenerateRandomNumber()
        {
            // Generate a random number.
            uint random = CryptographicBuffer.GenerateRandomNumber();

            return(random);
        }
Ejemplo n.º 7
0
        async Task RealtimeSub()
        {
            var user = _instaApi.GetLoggedUser().LoggedInUser;
            var dic  = new Dictionary <string, List <string> >
            {
                { "sub",
                  new List <string>
                  {
                      GraphQLSubscriptions.GetAppPresenceSubscription(),
                GraphQLSubscriptions.GetZeroProvisionSubscription(_instaApi.GetCurrentDevice().DeviceGuid.ToString()),
                      GraphQLSubscriptions.GetDirectStatusSubscription(),
                      GraphQLSubscriptions.GetDirectTypingSubscription(user?.Pk.ToString()),
                      GraphQLSubscriptions.GetAsyncAdSubscription(user?.Pk.ToString())
                  } }
            };
            var json       = JsonConvert.SerializeObject(dic);
            var bytes      = Encoding.UTF8.GetBytes(json);
            var dataStream = new MemoryStream(512);

            using (var zlibStream = new ZlibStream(dataStream, CompressionMode.Compress, CompressionLevel.Level9, true))
            {
                await zlibStream.WriteAsync(bytes, 0, bytes.Length);
            }

            var compressed    = dataStream.GetWindowsRuntimeBuffer(0, (int)dataStream.Length);
            var publishPacket = new PublishPacket(QualityOfService.AtLeastOnce, false, false)
            {
                Payload   = compressed,
                PacketId  = (ushort)CryptographicBuffer.GenerateRandomNumber(),
                TopicName = "/ig_realtime_sub"
            };
            await FbnsPacketEncoder.EncodePacket(publishPacket, _outboundWriter);
        }
Ejemplo n.º 8
0
        async Task PubSub()
        {
            var user = _instaApi.GetLoggedUser().LoggedInUser;
            var dic  = new Dictionary <string, List <string> >
            {
                { "sub",
                  new List <string>
                  {
                      SkyWalker.DirectSubscribe(user?.Pk.ToString()),
                      SkyWalker.LiveSubscribe(user?.Pk.ToString()),
                  } }
            };
            var json       = JsonConvert.SerializeObject(dic);
            var bytes      = Encoding.UTF8.GetBytes(json);
            var dataStream = new MemoryStream(512);

            using (var zlibStream = new ZlibStream(dataStream, CompressionMode.Compress, CompressionLevel.Level9, true))
            {
                await zlibStream.WriteAsync(bytes, 0, bytes.Length);
            }

            var compressed    = dataStream.GetWindowsRuntimeBuffer(0, (int)dataStream.Length);
            var publishPacket = new PublishPacket(QualityOfService.AtLeastOnce, false, false)
            {
                Payload   = compressed,
                PacketId  = (ushort)CryptographicBuffer.GenerateRandomNumber(),
                TopicName = "/pubsub"
            };
            await FbnsPacketEncoder.EncodePacket(publishPacket, _outboundWriter);
        }
Ejemplo n.º 9
0
        /// <summary>
        ///     Indicate activity
        /// </summary>
        /// <param name="threadId">Thread id</param>
        /// <param name="isActive">Active status</param>
        public async Task <IResult <bool> > IndicateActivityAsync(string threadId, bool isActive)
        {
            try
            {
                var token = ExtensionHelper.GetThreadToken();

                var data = new Dictionary <string, string>
                {
                    { "action", "indicate_activity" },
                    { "item_type", "indicate_activity" },
                    { "thread_id", threadId },
                    { "client_context", token },
                    { "activity_status", isActive ? "1" : "0" },
                };
                var json          = JsonConvert.SerializeObject(data);
                var bytes         = Encoding.UTF8.GetBytes(json);
                var publishPacket = new PublishPacket(QualityOfService.AtLeastOnce, false, false)
                {
                    Payload   = ZlibHelper.Compress(bytes).AsBuffer(),
                    PacketId  = (ushort)CryptographicBuffer.GenerateRandomNumber(),
                    TopicName = "132"
                };
                await FbnsPacketEncoder.EncodePacket(publishPacket, _outboundWriter);

                return(Result.Success(true));
            }
            catch (SocketException socketException)
            {
                return(Result.Fail(socketException, default(bool), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                return(Result.Fail <bool>(exception));
            }
        }
        public static T TakeRandom <T>(this IEnumerable <T> enumerable)
        {
            var random = new Random((int)CryptographicBuffer.GenerateRandomNumber());
            var index  = random.Next(0, enumerable.Count());

            return(enumerable.ElementAt(index));
        }
Ejemplo n.º 11
0
        async Task SubscribeForDM()
        {
            var messageSync     = new SubscriptionRequest("/ig_message_sync", QualityOfService.AtLeastOnce);
            var sendMessageResp = new SubscriptionRequest("/ig_send_message_response", QualityOfService.AtLeastOnce);
            var subIrisResp     = new SubscriptionRequest("/ig_sub_iris_response", QualityOfService.AtLeastOnce);
            var subscribePacket = new SubscribePacket((ushort)CryptographicBuffer.GenerateRandomNumber(), messageSync, sendMessageResp, subIrisResp);

            await FbnsPacketEncoder.EncodePacket(subscribePacket, _outboundWriter);
        }
Ejemplo n.º 12
0
        private async Task <IResult <InstaDirectRespondPayload> > SendDirectItem(Dictionary <string, string> dic, string token = null)
        {
            try
            {
                if (string.IsNullOrEmpty(token))
                {
                    token = ExtensionHelper.GetThreadToken();
                }

                var data = new Dictionary <string, string>
                {
                    { "action", "send_item" },
                    { "client_context", token },
                };
                foreach (var item in dic)
                {
                    data.Add(item.Key, item.Value);
                }
                var json  = JsonConvert.SerializeObject(data);
                var bytes = Encoding.UTF8.GetBytes(json);

                //id: '132',
                //path: '/ig_send_message',
                var publishPacket = new PublishPacket(QualityOfService.AtLeastOnce, false, false)
                {
                    Payload   = ZlibHelper.Compress(bytes).AsBuffer(),
                    PacketId  = (ushort)CryptographicBuffer.GenerateRandomNumber(),
                    TopicName = "132"
                };
                await FbnsPacketEncoder.EncodePacket(publishPacket, _outboundWriter);

                await Task.Delay(WaitForResponseDelay);

                var responseItem = Responses.GetItem(token);
                if (responseItem != null)
                {
                    Responses.Remove(responseItem);
                    return(responseItem.IsSucceed ?
                           Result.Success(ConvertersFabric.Instance.GetDirectRespondConverter(responseItem).Convert().Payload) :
                           Result.Fail(responseItem.Payload?.Message, ConvertersFabric.Instance
                                       .GetDirectRespondConverter(responseItem).Convert().Payload));
                }
                else
                {
                    return(Result.Fail <InstaDirectRespondPayload>("Couldn't get any response in the waiting time...\nMessage might sent after this period"));
                }
            }
            catch (SocketException socketException)
            {
                return(Result.Fail(socketException, default(InstaDirectRespondPayload), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                return(Result.Fail <InstaDirectRespondPayload>(exception));
            }
        }
Ejemplo n.º 13
0
        public ushort GetRandom(ushort max)
        {
            uint   rand     = CryptographicBuffer.GenerateRandomNumber();
            uint   high     = uint.MaxValue;
            double randD    = Convert.ToDouble(rand);
            double HighD    = Convert.ToDouble(high);
            double fraction = randD / HighD;
            double result   = max * fraction;
            ushort retval   = Convert.ToUInt16(result);

            return(retval);
        }
Ejemplo n.º 14
0
 private static uint getNextSignedPreKeyId()
 {
     try
     {
         var signedPreKeyIndex = conn.Get <SignedPreKeyIndex>(1);
         return(signedPreKeyIndex.Next);
     }
     catch (Exception e)
     {
         return(CryptographicBuffer.GenerateRandomNumber() % Medium.MAX_VALUE);
     }
 }
Ejemplo n.º 15
0
 void RollDice()
 {
     nRandomResult = 0;
     uint nMaxTries = 0;
     while (nRandomResult == 0 && nMaxTries < Constants.STD_RANDOMMAXTRIES)
     {
         nRandomResult = CryptographicBuffer.GenerateRandomNumber();
         nRandomResult = nRandomResult % ((uint)Model.RandomMax + 1);
         nMaxTries++;
     }
     ShowDice(nRandomResult);
     Model.Statistics.Add(new RandomResult(nRandomResult, 0));
 }
Ejemplo n.º 16
0
        private static uint getNextPreKeyId()
        {
            var query = conn.Table <PreKeyIndex>().Where(v => v.PreyKeyIndex == 1);

            if (query.Count() == 0)
            {
                return(CryptographicBuffer.GenerateRandomNumber() % Medium.MAX_VALUE);
            }
            else
            {
                var preKey = query.First();
                return(preKey.PreyKeyIndex);
            }
        }
Ejemplo n.º 17
0
        public async Task <IResult <bool> > LikeThreadMessageAsync(string threadId, string itemId)
        {
            try
            {
                var token = /* ExtensionHelper.GetThreadToken()*/ Guid.NewGuid().ToString();
//item_type=reaction&
//reaction_type=like&
//action=send_item&
//thread_ids=[340282366841710300949128148722678938640]&
//client_context=6687326311760832960&
//_csrftoken=tmqdvmqM1YjSauVdSOpIPnbCW3d2Dxxh&
//mutation_token=6687326311760832960&
//_uuid=fe3634e6-d3ec-4f01-943e-20381fdd9e19&
//node_type=item&
//reaction_status=created&
//item_id=29414953485080962978249978855555072&
//device_id=android-35b3eb8488e1e15c
                var data = new Dictionary <string, string>
                {
                    { "action", "send_item" },
                    { "item_type", "reaction" },
                    { "reaction_type", "like" },
                    { "node_type", "item" },
                    { "reaction_status", "created" },
                    { "thread_id", threadId },
                    { "client_context", token },
                    { "item_id", itemId },
                };
                var json          = JsonConvert.SerializeObject(data);
                var bytes         = Encoding.UTF8.GetBytes(json);
                var publishPacket = new PublishPacket(QualityOfService.AtLeastOnce, false, false)
                {
                    Payload   = ZlibHelper.Compress(bytes).AsBuffer(),
                    PacketId  = (ushort)CryptographicBuffer.GenerateRandomNumber(),
                    TopicName = "132"
                };
                await FbnsPacketEncoder.EncodePacket(publishPacket, _outboundWriter);

                return(Result.Success(true));
            }
            catch (SocketException socketException)
            {
                return(Result.Fail(socketException, default(bool), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                return(Result.Fail <bool>(exception));
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        ///     Register this client on the MQTT side stating what application this client is using.
        ///     The server will then return a token for registering over Instagram API side.
        /// </summary>
        /// <param name="ctx"></param>
        private async Task RegisterMqttClient()
        {
            var message = new Dictionary <string, string>
            {
                { "pkg_name", "com.instagram.android" },
                { "appid", "567067343352427" }
            };

            var json      = JsonConvert.SerializeObject(message);
            var jsonBytes = Encoding.UTF8.GetBytes(json);

            byte[] compressed;
            using (var compressedStream = new MemoryStream(jsonBytes.Length))
            {
                using (var zlibStream =
                           new ZlibStream(compressedStream, CompressionMode.Compress, CompressionLevel.Level9, true))
                {
                    zlibStream.Write(jsonBytes, 0, jsonBytes.Length);
                }
                compressed = new byte[compressedStream.Length];
                compressedStream.Position = 0;
                compressedStream.Read(compressed, 0, compressed.Length);
            }

            var publishPacket = new PublishPacket(QualityOfService.AtLeastOnce, false, false)
            {
                Payload   = compressed.AsBuffer(),
                PacketId  = (ushort)CryptographicBuffer.GenerateRandomNumber(),
                TopicName = ((byte)TopicIds.RegReq).ToString()
            };

            // Send PUBLISH packet then wait for PUBACK
            // Retry after TIMEOUT seconds
            if (!Running)
            {
                return;
            }
            try
            {
                await FbnsPacketEncoder.EncodePacket(publishPacket, _outboundWriter);

                WaitForPubAck();
            }
            catch (ObjectDisposedException)
            {
                // pass
            }
        }
Ejemplo n.º 19
0
        private void SetValue(T value)
        {
            lock (this)
            {
                _salt = CryptographicBuffer.GenerateRandom(CryptographicBuffer.GenerateRandomNumber( ) % 64 + 64);

                _hash.Append(_salt);

                _saltHashCode = _hash.GetValueAndReset( );

                _value = value;

                _hash.Append(ToIBuffer(value));
                _hash.Append(_salt);

                _hashCode = _hash.GetValueAndReset( );
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        ///     Register this client on the MQTT side stating what application this client is using.
        ///     The server will then return a token for registering over Instagram API side.
        /// </summary>
        /// <param name="ctx"></param>
        private void RegisterMqttClient(IChannelHandlerContext ctx)
        {
            var message = new Dictionary <string, string>
            {
                { "pkg_name", "com.instagram.android" },
                { "appid", "567067343352427" }
            };

            var json      = JsonConvert.SerializeObject(message);
            var jsonBytes = Encoding.UTF8.GetBytes(json);

            byte[] compressed;
            using (var compressedStream = new MemoryStream(jsonBytes.Length))
            {
                using (var zlibStream =
                           new ZlibStream(compressedStream, CompressionMode.Compress, CompressionLevel.Level9, true))
                {
                    zlibStream.Write(jsonBytes, 0, jsonBytes.Length);
                }
                compressed = new byte[compressedStream.Length];
                compressedStream.Position = 0;
                compressedStream.Read(compressed, 0, compressed.Length);
            }

            var publishPacket = new PublishPacket(QualityOfService.AtLeastOnce, false, false)
            {
                Payload   = Unpooled.CopiedBuffer(compressed),
                PacketId  = (int)CryptographicBuffer.GenerateRandomNumber(),
                TopicName = ((byte)TopicIds.RegReq).ToString()
            };

            // Send PUBLISH packet then wait for PUBACK
            // Retry after TIMEOUT seconds
            ctx.WriteAndFlushAsync(publishPacket);
            _waitingForPubAck = true;
            Task.Delay(TimeSpan.FromSeconds(TIMEOUT)).ContinueWith(retry =>
            {
                if (_waitingForPubAck)
                {
                    RegisterMqttClient(ctx);
                }
            });
        }
Ejemplo n.º 21
0
        private static int GetCryptographicSeed()
        {
#if WINDOWS_UWP
            return((int)CryptographicBuffer.GenerateRandomNumber());
#elif NETCORE
            using (var randomNumberGenerator = RandomNumberGenerator.Create())
            {
                byte[] buffer = new byte[4];
                randomNumberGenerator.GetBytes(buffer);
                return(BitConverter.ToInt32(buffer, 0));
            }
#else
            var    cryptoGlobal = new RNGCryptoServiceProvider();
            byte[] buffer       = new byte[4];
            // Fills an array of bytes with a cryptographically strong sequence of random values
            cryptoGlobal.GetBytes(buffer);
            return(BitConverter.ToInt32(buffer, 0));
#endif
        }
Ejemplo n.º 22
0
        private void HornLights(object o, object e)
        {
            if (_loop == 0)
            {
                Off(lp[rh]);
                Off(lp[lt]);
            }
            if (_loop < HornLoops)
            {
                Toggle(lp[lh]);
                Toggle(lp[rt]);
                Toggle(lp[rh]);
                Toggle(lp[lt]);
                Toggle(lp[ts]);
                Toggle(lp[ls]);
                _loop++;
            }


            if (_loop >= HornLoops)
            {
                horntimer.Stop();


                _loop = 0;

                On(lp[lh]);
                On(lp[rt]);
                On(lp[rh]);
                On(lp[lt]);

                randint = (int)(CryptographicBuffer.GenerateRandomNumber() % (songscount - 1));

                _mediaplayer.Source = sources[randint];

                _mediaplayer.AutoPlay = false;
                _mediaplayer.Play();

                songlength = sources[randint].Duration.Value;
                songloops  = (int)(songlength.TotalMilliseconds / SongFlashIntMS) - 1;
                songtimer.Start();
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// generates a random number between min & max
        /// </summary>
        /// <param name="min"></param>
        /// <param name="max"></param>
        /// <returns></returns>
        public uint GenerateRandomNumber(uint min, uint max)
        {
            if (min > max)
            {
                throw new ArgumentException("min must be strictly smaller than max");
            }
            var range = max - min + 1;

            Contract.Requires(min <= max);
            uint myVal = 0;

            do
            {
                myVal = CryptographicBuffer.GenerateRandomNumber();
            } while (!IsFair(myVal, range));
            myVal = myVal % range;
            Contract.Ensures(myVal >= min);
            Contract.Ensures(myVal <= max);
            return(myVal);
        }
Ejemplo n.º 24
0
        public async Task <IResult <bool> > ReactionMessageAsync(string threadId, string itemId, string emoji)
        {
            try
            {
                //{"action":"item_ack","status_code":"404","payload":{"client_context":"6687658745131972483","message":"target item is not supported"},"status":"fail"}

                //{"action":"item_ack","status_code":"400","payload":{"client_context":"6685052289622163080","message":"unknown reaction type"},"status":"fail"}
                var token = ExtensionHelper.GetThreadToken();
                var data  = new Dictionary <string, string>
                {
                    { "action", "send_item" },
                    { "item_type", "reaction" },
                    { "reaction_type", "like" },
                    { "node_type", "item" },
                    { "reaction_status", "created" },
                    { "thread_id", threadId },
                    { "client_context", token },
                    { "item_id", itemId },
                    { "emoji", emoji },
                };
                var json          = JsonConvert.SerializeObject(data);
                var bytes         = Encoding.UTF8.GetBytes(json);
                var publishPacket = new PublishPacket(QualityOfService.AtLeastOnce, false, false)
                {
                    Payload   = ZlibHelper.Compress(bytes).AsBuffer(),
                    PacketId  = (ushort)CryptographicBuffer.GenerateRandomNumber(),
                    TopicName = "132"
                };
                await FbnsPacketEncoder.EncodePacket(publishPacket, _outboundWriter);

                return(Result.Success(true));
            }
            catch (SocketException socketException)
            {
                return(Result.Fail(socketException, default(bool), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                return(Result.Fail <bool>(exception));
            }
        }
Ejemplo n.º 25
0
        // This project includes DISABLE_XAML_GENERATED_MAIN in the build properties,
        // which prevents the build system from generating the default Main method:
        //static void Main(string[] args)
        //{
        //    global::Windows.UI.Xaml.Application.Start((p) => new App());
        //}

        // This example code shows how you could implement the required Main method to
        // support multi-instance redirection. The minimum requirement is to call
        // Application.Start with a new App object. Beyond that, you may delete the
        // rest of the example code and replace it with your custom code if you wish.
        static void Main(string[] args)
        {
            //global::Windows.UI.Xaml.Application.Start((p) => new App());


            //// In some scenarios, the platform might indicate a recommended instance.
            //// If so, we can redirect this activation to that instance instead, if we wish.
            if (AppInstance.RecommendedInstance != null)
            {
                // ???
                AppInstance.RecommendedInstance.RedirectActivationTo();
            }
            else
            {
                // Define a key for this instance, based on some app-specific logic.
                // If the key is always unique, then the app will never redirect.
                // If the key is always non-unique, then the app will always redirect
                // to the first instance. In practice, the app should produce a key
                // that is sometimes unique and sometimes not, depending on its own needs.
                uint   number   = CryptographicBuffer.GenerateRandomNumber();
                string key      = number.ToString();// (number % 2 == 0) ? "even" : "odd";
                var    instance = AppInstance.FindOrRegisterInstanceForKey(key);

                if (instance.IsCurrentInstance)
                {
                    // If we successfully registered this instance, we can now just
                    // go ahead and do normal XAML initialization.
                    //global::Windows.UI.Xaml.Application.Start((p) => new App());


                    global::Windows.UI.Xaml.Application.Start(delegate(Windows.UI.Xaml.ApplicationInitializationCallbackParams p) { var hoge = new App(); hoge.Instance = instance; });
                }
                else
                {
                    // Some other instance has registered for this key, so we'll
                    // redirect this activation to that instance instead.
                    instance.RedirectActivationTo();
                }
            }
        }
 public uint RandomNumber()
 {
     return(CryptographicBuffer.GenerateRandomNumber());
 }
 public Task <uint> RandomNumberAsync()
 {
     return(Task.FromResult(CryptographicBuffer.GenerateRandomNumber()));
 }
Ejemplo n.º 28
0
 public int GetInt(int exclusiveCeiling)
 {
     return((int)(CryptographicBuffer.GenerateRandomNumber() % exclusiveCeiling));
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Generates a random password.
        /// </summary>
        /// <param name="minLength">
        /// Minimum password length.
        /// </param>
        /// <param name="maxLength">
        /// Maximum password length.
        /// </param>
        /// <returns>
        /// Randomly generated password.
        /// </returns>
        /// <remarks>
        /// The length of the generated password will be determined at
        /// random and it will fall with the range determined by the
        /// function parameters.
        /// </remarks>
        public static string Generate(int minLength,
                                      int maxLength)
        {
            // Make sure that input parameters are valid.
            if (minLength <= 0 || maxLength <= 0 || minLength > maxLength)
            {
                return(null);
            }

            // Create a local array containing supported password characters
            // grouped by types. You can remove character groups from this
            // array, but doing so will weaken the password strength.
            char[][] charGroups = new char[][]
            {
                PASSWORD_CHARS_LCASE.ToCharArray(),
                     PASSWORD_CHARS_UCASE.ToCharArray(),
                     PASSWORD_CHARS_NUMERIC.ToCharArray(),
                     PASSWORD_CHARS_SPECIAL.ToCharArray()
            };

            // Use this array to track the number of unused characters in each
            // character group.
            int[] charsLeftInGroup = new int[charGroups.Length];

            // Initially, all characters in each group are not used.
            for (int i = 0; i < charsLeftInGroup.Length; i++)
            {
                charsLeftInGroup[i] = charGroups[i].Length;
            }

            // Use this array to track (iterate through) unused character groups.
            int[] leftGroupsOrder = new int[charGroups.Length];

            // Initially, all character groups are not used.
            for (int i = 0; i < leftGroupsOrder.Length; i++)
            {
                leftGroupsOrder[i] = i;
            }

            // Because we cannot use the default randomizer, which is based on the
            // current time (it will produce the same "random" number within a
            // second), we will use a random number generator to seed the
            // randomizer.

            // Use a 4-byte array to fill it with random bytes and convert it then
            // to an integer value.
            byte[] randomBytes = new byte[4];

            // Generate 4 random bytes. AANGEPAST OMDAT DIT IN UWP NIET BESTAAT!
            //RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            //rng.GetBytes(randomBytes);

            // Convert 4 bytes into a 32-bit integer value. AANGEPAST BECAUSE UWP!
            int seed = (int)CryptographicBuffer.GenerateRandomNumber(); //Bron: https://msdn.microsoft.com/en-us/windows/uwp/security/create-random-numbers

            // Now, this is real randomization.
            Random random = new Random(seed);

            // This array will hold password characters.
            char[] password = null;

            // Allocate appropriate memory for the password.
            if (minLength < maxLength)
            {
                password = new char[random.Next(minLength, maxLength + 1)];
            }
            else
            {
                password = new char[minLength];
            }

            // Index of the next character to be added to password.
            int nextCharIdx;

            // Index of the next character group to be processed.
            int nextGroupIdx;

            // Index which will be used to track not processed character groups.
            int nextLeftGroupsOrderIdx;

            // Index of the last non-processed character in a group.
            int lastCharIdx;

            // Index of the last non-processed group.
            int lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;

            // Generate password characters one at a time.
            for (int i = 0; i < password.Length; i++)
            {
                // If only one character group remained unprocessed, process it;
                // otherwise, pick a random character group from the unprocessed
                // group list. To allow a special character to appear in the
                // first position, increment the second parameter of the Next
                // function call by one, i.e. lastLeftGroupsOrderIdx + 1.
                if (lastLeftGroupsOrderIdx == 0)
                {
                    nextLeftGroupsOrderIdx = 0;
                }
                else
                {
                    nextLeftGroupsOrderIdx = random.Next(0,
                                                         lastLeftGroupsOrderIdx);
                }

                // Get the actual index of the character group, from which we will
                // pick the next character.
                nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];

                // Get the index of the last unprocessed characters in this group.
                lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;

                // If only one unprocessed character is left, pick it; otherwise,
                // get a random character from the unused character list.
                if (lastCharIdx == 0)
                {
                    nextCharIdx = 0;
                }
                else
                {
                    nextCharIdx = random.Next(0, lastCharIdx + 1);
                }

                // Add this character to the password.
                password[i] = charGroups[nextGroupIdx][nextCharIdx];

                // If we processed the last character in this group, start over.
                if (lastCharIdx == 0)
                {
                    charsLeftInGroup[nextGroupIdx] =
                        charGroups[nextGroupIdx].Length;
                }
                // There are more unprocessed characters left.
                else
                {
                    // Swap processed character with the last unprocessed character
                    // so that we don't pick it until we process all characters in
                    // this group.
                    if (lastCharIdx != nextCharIdx)
                    {
                        char temp = charGroups[nextGroupIdx][lastCharIdx];
                        charGroups[nextGroupIdx][lastCharIdx] =
                            charGroups[nextGroupIdx][nextCharIdx];
                        charGroups[nextGroupIdx][nextCharIdx] = temp;
                    }
                    // Decrement the number of unprocessed characters in
                    // this group.
                    charsLeftInGroup[nextGroupIdx]--;
                }

                // If we processed the last group, start all over.
                if (lastLeftGroupsOrderIdx == 0)
                {
                    lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
                }
                // There are more unprocessed groups left.
                else
                {
                    // Swap processed group with the last unprocessed group
                    // so that we don't pick it until we process all groups.
                    if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)
                    {
                        int temp = leftGroupsOrder[lastLeftGroupsOrderIdx];
                        leftGroupsOrder[lastLeftGroupsOrderIdx] =
                            leftGroupsOrder[nextLeftGroupsOrderIdx];
                        leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;
                    }
                    // Decrement the number of unprocessed groups.
                    lastLeftGroupsOrderIdx--;
                }
            }

            // Convert password characters into a string and return the result.
            return(new string(password));
        }
Ejemplo n.º 30
0
        //--------------------------------------------------------Constructor:----------------------------------------------------------------\\
        #region --Constructors--


        #endregion
        //--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\
        #region --Set-, Get- Methods--
        /// <summary>
        /// Returns a secure random index for the <see cref="preKeys"/> list.
        /// </summary>
        public int GetRandomPreKeyIndex()
        {
            return((int)(CryptographicBuffer.GenerateRandomNumber() % preKeys.Count));
        }