Exemple #1
0
        /// <summary>
        /// 暗号化された文字列を復号化する
        /// </summary>
        public static string DecryptString(string str, string password)
        {
            var aes = new System.Security.Cryptography.AesCryptoServiceProvider();

            var passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);

            aes.Key = ResizeBytesArray(passwordBytes, aes.Key.Length);
            aes.IV  = ResizeBytesArray(passwordBytes, aes.IV.Length);

            var data        = System.Convert.FromBase64String(str);
            var stream      = new System.IO.MemoryStream(data);
            var decryptor   = aes.CreateDecryptor();
            var cryptStreem = new System.Security.Cryptography.CryptoStream(
                stream,
                decryptor,
                System.Security.Cryptography.CryptoStreamMode.Read
                );
            var reader = new System.IO.StreamReader(
                cryptStreem,
                System.Text.Encoding.UTF8
                );

            try {
                var result = reader.ReadToEnd();
                return(result);
            } finally {
                reader.Close();
                cryptStreem.Close();
                stream.Close();
            }
        }
        public static string aesDecryptBase64(string SourceStr, ulong Key)
        {
            string decrypt = "";

            try
            {
                var    aes    = new System.Security.Cryptography.AesCryptoServiceProvider();
                var    md5    = new System.Security.Cryptography.MD5CryptoServiceProvider();
                var    sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider();
                byte[] key    = sha256.ComputeHash(BitConverter.GetBytes(Key));
                byte[] iv     = md5.ComputeHash(BitConverter.GetBytes(Key));
                aes.Key = key;
                aes.IV  = iv;

                byte[] dataByteArray = Convert.FromBase64String(SourceStr);
                using (var ms = new System.IO.MemoryStream())
                {
                    using (var cs = new System.Security.Cryptography.CryptoStream(ms, aes.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        cs.Write(dataByteArray, 0, dataByteArray.Length);
                        cs.FlushFinalBlock();
                        decrypt = Encoding.UTF8.GetString(ms.ToArray());
                    }
                }
            }
            catch (Exception e)
            {
            }
            return(decrypt);
        }
Exemple #3
0
 private static String GetHttpsAgnostic(String url)
 {
     if (Environment.OSVersion.Platform == PlatformID.Unix)
     {
         Process proc = new System.Diagnostics.Process {
             StartInfo =
             {
                 FileName               = "/bin/bash",
                 Arguments              = $"-c 'curl -s {url}'",
                 UseShellExecute        = false,
                 RedirectStandardOutput = true
             }
         };
         proc.Start();
         return(proc.StandardOutput.ReadToEnd());
         //proc.WaitForExit();
     }
     else
     {
         System.Security.Cryptography.AesCryptoServiceProvider b = new System.Security.Cryptography.AesCryptoServiceProvider();
         ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
         using (HttpClient client = new HttpClient())
             using (HttpResponseMessage response = client.GetAsync(url).Result)
                 using (HttpContent content = response.Content) {
                     return(content.ReadAsStringAsync().Result);
                 }
     }
 }
Exemple #4
0
        public byte[] Encrypt(string plainText, out byte[] keyBytes, out byte[] ivBytes)
        {
            if (plainText == null || plainText.Length <= 0)
            {
                throw new ArgumentNullException("plainText");
            }

            System.IO.MemoryStream memoryStream;

            using (System.Security.Cryptography.AesCryptoServiceProvider csp = new System.Security.Cryptography.AesCryptoServiceProvider())
            {
                csp.GenerateKey();
                csp.GenerateIV();

                keyBytes = csp.Key;
                ivBytes  = csp.IV;
                //csp.CreateEncryptor

                // Create an encryptor to perform the stream transform.
                System.Security.Cryptography.ICryptoTransform cryptoTransformer = csp.CreateEncryptor(csp.Key, csp.IV);

                // Create the streams used for encryption.
                using (memoryStream = new System.IO.MemoryStream())
                    using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, cryptoTransformer, System.Security.Cryptography.CryptoStreamMode.Write))
                        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(cryptoStream))
                        {
                            sw.AutoFlush = true;
                            sw.Write(plainText);
                        }
            }

            return(memoryStream.ToArray());
        }
Exemple #5
0
        public string Decrypt(byte[] inputDataBytes, byte[] keyBytes, byte[] ivBytes)
        {
            if (inputDataBytes == null || inputDataBytes.Length <= 0)
            {
                throw new ArgumentNullException("plainText");
            }
            if (keyBytes == null || keyBytes.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }
            if (ivBytes == null || ivBytes.Length <= 0)
            {
                throw new ArgumentNullException("IV");
            }

            System.IO.MemoryStream memoryStream;

            using (System.Security.Cryptography.AesCryptoServiceProvider csp = new System.Security.Cryptography.AesCryptoServiceProvider())
            {
                csp.Key = keyBytes;
                csp.IV  = ivBytes;
                //csp.CreateEncryptor

                // Create an encryptor to perform the stream transform.
                System.Security.Cryptography.ICryptoTransform cryptoTransformer = csp.CreateDecryptor(csp.Key, csp.IV);

                // Create the streams used for encryption.
                using (memoryStream = new System.IO.MemoryStream(inputDataBytes))
                    using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, cryptoTransformer, System.Security.Cryptography.CryptoStreamMode.Read))
                        using (System.IO.StreamReader sr = new System.IO.StreamReader(cryptoStream))
                        {
                            return(sr.ReadToEnd());
                        }
            }
        }
Exemple #6
0
 public override void OnCreate()
 {
     base.OnCreate();
     RegisterActivityLifecycleCallbacks(this);
     System.Security.Cryptography.AesCryptoServiceProvider b = new System.Security.Cryptography.AesCryptoServiceProvider();
     //A great place to initialize Xamarin.Insights and Dependency Services!
 }
Exemple #7
0
        // ========================================
        // static field
        // ========================================
        public static string EncryptString(string str, string password)
        {
            var aes = new System.Security.Cryptography.AesCryptoServiceProvider();

            var data = System.Text.Encoding.UTF8.GetBytes(str);

            var passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);

            aes.Key = ResizeBytesArray(passwordBytes, aes.Key.Length);
            aes.IV  = ResizeBytesArray(passwordBytes, aes.IV.Length);

            var stream      = new System.IO.MemoryStream();
            var encryptor   = aes.CreateEncryptor();
            var cryptStream = new System.Security.Cryptography.CryptoStream(
                stream,
                encryptor,
                System.Security.Cryptography.CryptoStreamMode.Write
                );

            try {
                cryptStream.Write(data, 0, data.Length);
                cryptStream.FlushFinalBlock();
                var encrypted = stream.ToArray();
                return(System.Convert.ToBase64String(encrypted));
            } finally {
                cryptStream.Close();
                stream.Close();
            }
        }
        public override void OnCreate()
        {
            try
            {
                base.OnCreate();

                Instance = this;

                //A great place to initialize Xamarin.Insights and Dependency Services!
                RegisterActivityLifecycleCallbacks(this);

                Instance = this;

                Client client = new Client(AppSettings.Cert);
                Console.WriteLine(client);

                if (AppSettings.TurnSecurityProtocolType3072On)
                {
                    ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                    HttpClient clientHttp = new HttpClient(new Xamarin.Android.Net.AndroidClientHandler());
                    Console.WriteLine(clientHttp);
                    ServicePointManager.Expect100Continue = true;
                    ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13 | SecurityProtocolType.Ssl3;
                }

                if (AppSettings.TurnTrustFailureOnWebException)
                {
                    //If you are Getting this error >>> System.Net.WebException: Error: TrustFailure /// then Set it to true
                    ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
                    System.Security.Cryptography.AesCryptoServiceProvider b = new System.Security.Cryptography.AesCryptoServiceProvider();
                    Console.WriteLine(b);
                }

                //OneSignal Notification
                //======================================
                OneSignalNotification.RegisterNotificationDevice();

                //Init Settings
                SharedPref.Init();

                ClassMapper.SetMappers();

                //App restarted after crash
                AndroidEnvironment.UnhandledExceptionRaiser += AndroidEnvironmentOnUnhandledExceptionRaiser;
                AppDomain.CurrentDomain.UnhandledException  += CurrentDomainOnUnhandledException;
                TaskScheduler.UnobservedTaskException       += TaskSchedulerOnUnobservedTaskException;

                FirebaseApp.InitializeApp(this);
                Methods.Path.Chack_MyFolder();

                Methods.AppLifecycleObserver appLifecycleObserver = new Methods.AppLifecycleObserver();
                ProcessLifecycleOwner.Get().Lifecycle.AddObserver(appLifecycleObserver);
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
Exemple #9
0
 /// <summary>
 /// Creates the CryptoServiceProvider based on the PBKDF2.
 /// </summary>
 /// <param name="inPBKDF2">Input PBKDF2</param>
 /// <returns>CSP</returns>
 private System.Security.Cryptography.AesCryptoServiceProvider createCSP(System.Security.Cryptography.Rfc2898DeriveBytes inPBKDF2)
 {
     inPBKDF2.Reset();
     csp         = new System.Security.Cryptography.AesCryptoServiceProvider();
     csp.Mode    = this.cipherMode;
     csp.Padding = this.paddingMode;
     csp.Key     = inPBKDF2.GetBytes(csp.KeySize / 8);
     csp.IV      = inPBKDF2.GetBytes(csp.BlockSize / 8);
     return(csp);
 }
Exemple #10
0
        //public const string server_address = "http://192.168.1.2/";

        public static string Auth(string s, actionType type)
        {
            System.Security.Cryptography.AesCryptoServiceProvider AES = new System.Security.Cryptography.AesCryptoServiceProvider();

            System.Net.ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;

            string Out = String.Empty;

            WebRequest req = WebRequest.Create(server_address + "server/web/log");

            req.Method      = "POST";
            req.ContentType = "application/json";
            WebResponse resp;

            try {
                byte[] sentData = Encoding.GetEncoding(1251).GetBytes(s);
                req.ContentLength = sentData.Length;
                Stream sendStream = req.GetRequestStream();                                     //System.Net.WebException: Error: NameResolutionFailure
                sendStream.Write(sentData, 0, sentData.Length);
                sendStream.Close();

                resp = req.GetResponse();

                if (type == actionType.auth)
                {
                    cookie = resp.Headers["Set-Cookie"];
                }

                Stream       ReceiveStream = resp.GetResponseStream();
                StreamReader sr            = new StreamReader(ReceiveStream, Encoding.UTF8);

                Char[] read  = new Char[256];
                int    count = sr.Read(read, 0, 256);


                while (count > 0)
                {
                    String str = new String(read, 0, count);
                    Out  += str;
                    count = sr.Read(read, 0, 256);
                }
            }
            catch (System.Net.WebException e)
            {
                Debug.WriteLine("ReceiveError");
                return("-1");
            }
            catch (System.Net.Sockets.SocketException e1)
            {
                Debug.WriteLine("Network is unreachable");
                return("-1");
            }

            return(Out);
        }
Exemple #11
0
        public static HttpWebRequest CreateRequest(string url)
        {
            //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => { return true; });
            ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
            System.Security.Cryptography.AesCryptoServiceProvider b = new System.Security.Cryptography.AesCryptoServiceProvider();

            Uri            uri        = new Uri(url);
            HttpWebRequest webRequest = WebRequest.Create(uri) as HttpWebRequest;

            webRequest.UserAgent = USER_AGENT;
            return(webRequest);
        }
    public static string Decrypt_Aes(this object value, string aesKey, string aesIV)
    {
        byte[] cipherText = GetBytes(value as string);
            byte[] Key = GetBytes(aesKey);
            byte[] IV = GetBytes(aesIV);
            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
                throw new ArgumentNullException("cipherText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            // Create an AesCryptoServiceProvider object
            // with the specified key and IV.
            using (System.Security.Cryptography.AesCryptoServiceProvider aesAlg = new System.Security.Cryptography.AesCryptoServiceProvider())
            {
                aesAlg.Key = Key;
                aesAlg.IV = IV;

                // Create a decrytor to perform the stream transform.
                System.Security.Cryptography.ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }

            }

            return plaintext;
    }
Exemple #13
0
        //-------------------------------------------------

        public static string AesDecrypt(string password, string base64)
        {
            // Turn input string into a byte array.
            var input = System.Convert.FromBase64String(base64);
            // Create an instance of the Rijndael class.
            var cipher = new System.Security.Cryptography.AesCryptoServiceProvider();
            // Calculate salt to make it harder to guess key by using a dictionary attack.
            var passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);
            var hmac          = new System.Security.Cryptography.HMACSHA1(passwordBytes);
            var salt          = hmac.ComputeHash(passwordBytes);
            // Generate Secret Key from the password and salt.
            // Note: Set number of iterations to 10 in order for JavaScript example to work faster.
            var secretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(passwordBytes, salt, 10);
            // Create a encryptor from the existing SecretKey bytes by using
            // 32 bytes (256 bits) for the secret key and
            // 16 bytes (128 bits) for the initialization vector (IV).
            var key = secretKey.GetBytes(32);
            var iv  = secretKey.GetBytes(16);
            // Get cryptor as System.Security.Cryptography.ICryptoTransform class.
            var cryptor = cipher.CreateDecryptor(key, iv);
            // Create new Input.
            var inputBuffer = new System.Byte[input.Length];

            // Copy data bytes to input buffer.
            System.Buffer.BlockCopy(input, 0, inputBuffer, 0, inputBuffer.Length);
            // Create a MemoryStream to hold the output bytes.
            var stream = new System.IO.MemoryStream();
            // Create a CryptoStream through which we are going to be processing our data.
            var mode         = System.Security.Cryptography.CryptoStreamMode.Write;
            var cryptoStream = new System.Security.Cryptography.CryptoStream(stream, cryptor, mode);

            // Start the decrypting process.
            cryptoStream.Write(inputBuffer, 0, inputBuffer.Length);
            // Finish decrypting.
            cryptoStream.FlushFinalBlock();
            // Convert data from a memoryStream into a byte array.
            var outputBuffer = stream.ToArray();

            // Close both streams.
            stream.Close();
            //cryptoStream.Close();
            // Convert encrypted data into a base64-encoded string.
            var s = System.Text.Encoding.UTF8.GetString(outputBuffer);

            return(s);
        }
Exemple #14
0
 public static byte[] AESDecrypt(byte[] input)
 {
     using (var aes = new System.Security.Cryptography.AesCryptoServiceProvider())
     {
         aes.Key = aeskey;
         aes.IV  = aesvector;
         using (var ms = new System.IO.MemoryStream())
         {
             var cs = new System.Security.Cryptography.CryptoStream(ms, aes.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
             if (cs == null)
             {
                 return(null);
             }
             cs.Write(input, 0, input.Length);
             cs.FlushFinalBlock();
             return(ms.ToArray());
         }
     }
 }
Exemple #15
0
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(bundle);

            ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
            System.Security.Cryptography.AesCryptoServiceProvider b = new System.Security.Cryptography.AesCryptoServiceProvider();

            global::Xamarin.Forms.Forms.Init(this, bundle);
            try
            {
                LoadApplication(new App());
            }
            catch (System.Exception ex)
            {
                throw;
            }
        }
Exemple #16
0
        /// <summary>
        /// Construct a keyed universal hash function.
        ///
        /// An instance of a universal hash function needs to store on the order of RandomKeyVectorLengthInBytes values upon construction,
        /// so it is best not to initialize this function for large strings (e.g., those over 32k).
        ///
        /// </summary>
        /// <param name="keyOf16Or24Or32Bytes">A key that should not be known to those who might try to create collisions, provided as an array of 16, 24, or 32 bytes.</param>
        /// <param name="randomKeyVectorLengthInBytes">The length of the random key vector used for hashing.  Should be twice the length of the longest value you expect to hash,
        /// unless you hash values bigger than you would want to keep in memory.  If hashing a value longer than this, the universal hash properties may not hold.</param>
        public UniversalHashFunction(byte[] keyOf16Or24Or32Bytes, int randomKeyVectorLengthInBytes = 256)
        {
            int numberOfRandomBytesToGenerate = SetVectorLengthAndGetNumberOfRandomBytesNeeded(randomKeyVectorLengthInBytes);

            // Generate enough random bytes to fill the RandomKeyVector and 4 extra for the InitialRandomKey
            using (System.Security.Cryptography.AesCryptoServiceProvider aes = new System.Security.Cryptography.AesCryptoServiceProvider())
            {
                aes.Key  = keyOf16Or24Or32Bytes;
                aes.IV   = new byte[16];
                aes.Mode = System.Security.Cryptography.CipherMode.CBC;

                // Encrypt a null message with the key using CBC and InitializationVector=0
                byte[] pseudoRandomBytes;
                using (System.IO.MemoryStream ciphertext = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ciphertext, aes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        if (numberOfRandomBytesToGenerate % 16 != 0)
                        {
                            // Round to next 128-bit boundary since we're using AES 128-bit blocks to generate randomness
                            numberOfRandomBytesToGenerate += 16 - (numberOfRandomBytesToGenerate % 16);
                        }
                        cs.Write(new byte[numberOfRandomBytesToGenerate], 0, numberOfRandomBytesToGenerate);
                        // Ensure all bytes are flushed.
                    }
                    pseudoRandomBytes = ciphertext.ToArray();
                }

                // Create the random key vector and fill it with random bytes
                _randomKeyVector = new ulong[randomKeyVectorLengthInBytes / 8];
                for (int i = 0; i < _randomKeyVector.Length; i++)
                {
                    _randomKeyVector[i] = BitConverter.ToUInt64(pseudoRandomBytes, i * 8);
                }
                // Fill the initial random key with the last remaining 8 bytes
                _initialRandomKey = BitConverter.ToUInt64(pseudoRandomBytes, randomKeyVectorLengthInBytes);
            }
        }
Exemple #17
0
        byte[] getstandardkey()
        {
            System.Security.Cryptography.AesCryptoServiceProvider helper =
                new System.Security.Cryptography.AesCryptoServiceProvider();
            helper.GenerateKey();
            if (File.Exists("dispenser.bin") == false)
            {
                File.WriteAllBytes("dispenser.bin", helper.Key);
            }
            byte[] keyend = File.ReadAllBytes("dispenser.bin");
            byte[] sentryFile;
            if (File.Exists("sentry.bin"))
            {
                sentryFile = File.ReadAllBytes("sentry.bin");
            }
            else
            {
                byte[] dummysent = new byte[18];
                rnd.NextBytes(dummysent);
                File.WriteAllBytes("sentry.bin", dummysent);
                sentryFile = dummysent;
            }
            byte[] sentryHash = CryptoHelper.SHAHash(sentryFile);
            byte[] fullkey    = new byte[helper.Key.Length];
            int    y          = 0;

            while (y < sentryHash.Length)
            {
                fullkey[y] = sentryHash[y];
                y          = y + 1;
            }
            while (y < fullkey.Length)
            {
                fullkey[y] = keyend[y - 18];
                y          = y + 1;
            }
            return(fullkey);
        }
Exemple #18
0
        private string Encrypt256(string text)
        {
            // AesCryptoServiceProvider
            System.Security.Cryptography.AesCryptoServiceProvider aes = new System.Security.Cryptography.AesCryptoServiceProvider();
            aes.BlockSize = 128;
            aes.KeySize = 256;
            aes.IV = System.Text.Encoding.UTF8.GetBytes(AesIV256);
            aes.Key = System.Text.Encoding.UTF8.GetBytes(AesKey256);
            aes.Mode = System.Security.Cryptography.CipherMode.CBC;
            aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;

            // Convert string to byte array
            byte[] src = System.Text.Encoding.Unicode.GetBytes(text);

            // encryption
            using (System.Security.Cryptography.ICryptoTransform encrypt = aes.CreateEncryptor())
            {
                byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);

                // Convert byte array to Base64 strings
                return Convert.ToBase64String(dest);
            }
        }
    public static string Encrypt_Aes(this object value, string aesKey, string aesIV)
    {
        string plainText = value as string;
            byte[] Key = GetBytes(aesKey);
            byte[] IV = GetBytes(aesIV);
            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");
            byte[] encrypted;
            // Create an AesCryptoServiceProvider object
            // with the specified key and IV.
            using (System.Security.Cryptography.AesCryptoServiceProvider aesAlg = new System.Security.Cryptography.AesCryptoServiceProvider())
            {
                aesAlg.Key = Key;
                aesAlg.IV = IV;

                // Create a decrytor to perform the stream transform.
                System.Security.Cryptography.ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {

                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }

            return encrypted.GetString();
    }
Exemple #20
0
        static void Main(string[] args)
        {
            string token = System.Environment.GetEnvironmentVariable("TOKEN");

            if (token == null)
            {
                Console.WriteLine("Enter a token:");
                token = Console.ReadLine();
            }

            System.Net.ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
            System.Security.Cryptography.AesCryptoServiceProvider b = new System.Security.Cryptography.AesCryptoServiceProvider();

            Console.WriteLine("Before ctor");
            TelegramBotClient Bot = new TelegramBotClient(token);

            Console.WriteLine("After ctor");


            Bot.OnMessage      += BotOnMessageReceived;
            Bot.OnReceiveError += BotOnReceiveError;
            //Bot.OnUpdate +=

            var me = Bot.GetMeAsync().Result;

            System.Console.WriteLine("Hello my name is " + me.FirstName);

            Console.WriteLine("Bot before start receiving");
            Bot.StartReceiving();
            Console.WriteLine("Bot after start receiving");

            // для heroku

            /*
             * int port = 1234;
             *
             * var threadServer = new Thread(
             * ()=>
             *      {
             *              while ( true )
             *              {
             *                      try
             *                      {
             *                              port = Int32.Parse( System.Environment.GetEnvironmentVariable( "PORT" ) );
             *                      }
             *                      catch ( Exception )
             *                      {
             *                              continue;
             *                      }
             *
             *                      TcpListener server = new TcpListener( IPAddress.Parse( "127.0.0.1" ), port );
             *                      server.Start();
             *                      Thread.Sleep( 3000 );
             *                      server.Stop();
             *              }
             *      }
             * );
             * threadServer.Start();
             */
            while (true)
            {
                string line = Console.ReadLine();
                if (line == "exit")
                {
                    break;
                }
            }

            Bot.StopReceiving();

            //threadServer.Abort();
        }
        private void SendEvent()
        {
            string serviceBusNamespace = AppConfig.serviceBusNamespace;
            string eventHubName = AppConfig.eventHubName;
            string publisherName = AppConfig.publisherName;
            string sas = AppConfig.sas;

            Uri uri = new Uri("https://" + serviceBusNamespace +
                                        ".servicebus.windows.net/" + eventHubName +
                                        "/publishers/" + publisherName + "/messages");

            WebClient wc = new WebClient();
            //Next 2 lines are a HACK to work around a MONO bug when posting
            System.Net.ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
            System.Security.Cryptography.AesCryptoServiceProvider b = new System.Security.Cryptography.AesCryptoServiceProvider();

            wc.Headers[HttpRequestHeader.ContentType] = "application/atom+xml;type=entry;charset=utf-8";
            wc.Headers[HttpRequestHeader.Authorization] = sas;
            //HACK:
            System.Random rnd = new System.Random();
            string temp = rnd.Next(1, 100).ToString();

            int ParkedCount;
            int VehicleCount;
            getVehicleCounts(out ParkedCount, out VehicleCount);

            decimal income;
            decimal expenses;
            getEconomyData(out income, out expenses);

            SmartCityEvent scEvent = new SmartCityEvent
            {
                gameTime = this.gameTime,
                cityName = cityName,
                parkedCount = ParkedCount,
                vehicleCount = VehicleCount,
                income = income,
                expenses = expenses
            };

            //UnityEngine.Debug.Log("Starting to send Azure event");
            try {
                string scEventJson = serializeJson(scEvent);
                //string scEventJson = "test";
                Debug.Log(scEventJson);
                //string postString = "{id:\"" + cityName + "\",parkedCount:\"" + ParkedCount + "\",vehicleCount:\"" + VehicleCount + "\"}";
                //wc.UploadString(uri, "POST", "{id:\"" + cityName + "\",temp:\"" + temp + "\"}");
                wc.UploadString(uri, "POST", scEventJson);
                Debug.Log("POST: " + scEventJson);
            }
            catch(Exception ex )
            {
                UnityEngine.Debug.LogError(ex.Message);
            }
            //UnityEngine.Debug.Log("Completed send to Azure event");
        }
        protected override void OnCreate(Bundle bundle)
        {
            try
            {
                FormsAppCompatActivity.ToolbarResource   = Resource.Layout.Toolbar;
                FormsAppCompatActivity.TabLayoutResource = Resource.Layout.Tabs;

                base.OnCreate(bundle);

                if (Settings.BuginAndroidAutoresize)
                {
                    this.Window.AddFlags(WindowManagerFlags.Fullscreen);
                    this.Window.AddFlags(WindowManagerFlags.KeepScreenOn);
                    Window.SetSoftInputMode(SoftInput.AdjustResize);
                    if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
                    {
                        // Bug in Android 5+, this is an adequate workaround
                        AndroidBug5497WorkaroundForXamarinAndroid.assistActivity(this, WindowManager);
                    }
                }

                if (Settings.TurnFullScreenOn)
                {
                    this.Window.AddFlags(WindowManagerFlags.Fullscreen);
                    this.Window.AddFlags(WindowManagerFlags.KeepScreenOn);
                }

                if (Settings.TurnSecurityProtocolType3072On)
                {
                    ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                    HttpClient client = new HttpClient(new Xamarin.Android.Net.AndroidClientHandler());
                }

                if (Settings.TurnTrustFailureOn_WebException)
                {
                    //If you are Getting this error >>> System.Net.WebException: Error: TrustFailure /// then Set it to true
                    System.Net.ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
                    System.Security.Cryptography.AesCryptoServiceProvider b = new System.Security.Cryptography.AesCryptoServiceProvider();
                }

                CachedImageRenderer.Init();
                var ignore = new CircleTransformation();

                var assembliesToInclude = new List <Assembly>()
                {
                    typeof(CachedImage).GetTypeInfo().Assembly,
                    typeof(CachedImageRenderer).GetTypeInfo().Assembly
                };
                AndroidClipboardManager = (ClipboardManager)GetSystemService(ClipboardService);

                var container = new SimpleContainer();
                container.Register <IDevice>(t => AndroidDevice.CurrentDevice);
                container.Register <IGeolocator, Geolocator>();
                Resolver.ResetResolver();
                Resolver.SetResolver(container.GetResolver());
                CrossMedia.Current.Initialize();
                ImageCircleRenderer.Init();



                UserDialogs.Init(this);
                global::Xamarin.Forms.Forms.Init(this, bundle);

                AndroidAppLinks.Init(this);

                var data = Intent?.Data?.EncodedAuthority.ToString();

                //Uri data = getIntent().getData();
                //String scheme = data.getScheme(); // "http"
                //String host = data.getHost(); // "twitter.com"
                //List < String > params = data.getPathSegments();
                //String first = params.get(0); // "status"
                //String second = params.get(1); // "1234"



                LoadApplication(new App());
            }
            catch (Exception ex)
            {
            }
        }
        /// <summary>
        /// Construct a keyed universal hash function.
        /// 
        /// An instance of a universal hash function needs to store on the order of RandomKeyVectorLengthInBytes values upon construction,
        /// so it is best not to initialize this function for large strings (e.g., those over 32k).
        /// 
        /// </summary>
        /// <param name="keyOf16Or24Or32Bytes">A key that should not be known to those who might try to create collisions, provided as an array of 16, 24, or 32 bytes.</param>
        /// <param name="randomKeyVectorLengthInBytes">The length of the random key vector used for hashing.  Should be twice the length of the longest value you expect to hash,
        /// unless you hash values bigger than you would want to keep in memory.  If hashing a value longer than this, the universal hash properties may not hold.</param>
        public UniversalHashFunction(byte[] keyOf16Or24Or32Bytes, int randomKeyVectorLengthInBytes = 256)
        {
            int numberOfRandomBytesToGenerate = SetVectorLengthAndGetNumberOfRandomBytesNeeded(randomKeyVectorLengthInBytes);

            // Generate enough random bytes to fill the RandomKeyVector and 4 extra for the InitialRandomKey
            using (System.Security.Cryptography.AesCryptoServiceProvider aes = new System.Security.Cryptography.AesCryptoServiceProvider())
            {
                aes.Key = keyOf16Or24Or32Bytes;
                aes.IV = new byte[16];
                aes.Mode = System.Security.Cryptography.CipherMode.CBC;

                // Encrypt a null message with the key using CBC and InitializationVector=0
                byte[] pseudoRandomBytes;
                using (System.IO.MemoryStream ciphertext = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ciphertext, aes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        if (numberOfRandomBytesToGenerate % 16 != 0)
                        {
                            // Round to next 128-bit boundary since we're using AES 128-bit blocks to generate randomness
                            numberOfRandomBytesToGenerate += 16 - (numberOfRandomBytesToGenerate % 16);
                        }
                        cs.Write(new byte[numberOfRandomBytesToGenerate], 0, numberOfRandomBytesToGenerate);
                        // Ensure all bytes are flushed.
                    }
                    pseudoRandomBytes = ciphertext.ToArray();
                }

                // Create the random key vector and fill it with random bytes
                _randomKeyVector = new ulong[randomKeyVectorLengthInBytes / 8];
                for (int i = 0; i < _randomKeyVector.Length; i++)
                    _randomKeyVector[i] = BitConverter.ToUInt64(pseudoRandomBytes, i * 8);
                // Fill the initial random key with the last remaining 8 bytes
                _initialRandomKey = BitConverter.ToUInt64(pseudoRandomBytes, randomKeyVectorLengthInBytes);
            }
        }
Exemple #24
0
        protected override void OnCreate(Bundle bundle)
        {
            try
            {
                FormsAppCompatActivity.ToolbarResource   = Resource.Layout.Toolbar;
                FormsAppCompatActivity.TabLayoutResource = Resource.Layout.Tabbar;

                base.OnCreate(bundle);


                if (Settings.TurnFullScreenOn)
                {
                    this.Window.AddFlags(WindowManagerFlags.Fullscreen);
                    this.Window.AddFlags(WindowManagerFlags.KeepScreenOn);
                }

                if (Settings.TurnSecurityProtocolType3072On)
                {
                    ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                    HttpClient client = new HttpClient(new Xamarin.Android.Net.AndroidClientHandler());
                }

                if (Settings.TurnTrustFailureOn_WebException)
                {
                    //If you are Getting this error >>> System.Net.WebException: Error: TrustFailure /// then Set it to true
                    System.Net.ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
                    System.Security.Cryptography.AesCryptoServiceProvider b = new System.Security.Cryptography.AesCryptoServiceProvider();
                }

                //Methods =>> Copy the text
                AndroidClipboardManager = (ClipboardManager)GetSystemService(ClipboardService);

                CachedImageRenderer.Init();
                var ignore = new CircleTransformation();

                var assembliesToInclude = new List <Assembly>()
                {
                    typeof(CachedImage).GetTypeInfo().Assembly,
                    typeof(CachedImageRenderer).GetTypeInfo().Assembly
                };
                SegmentedControlRenderer.Init();
                PullToRefreshLayoutRenderer.Init();
                FFImageLoading.Forms.Droid.CachedImageRenderer.Init();
                global::Xamarin.Forms.Forms.Init(this, bundle);

                try
                {
                    var  activity      = Xamarin.Forms.Forms.Context;
                    File httpCacheDir  = new File(activity.CacheDir, "http");
                    long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
                    HttpResponseCache.Install(httpCacheDir, httpCacheSize);
                }
                catch (IOException ce)
                {
                }

                UserDialogs.Init(this);

                MobileAds.Initialize(ApplicationContext, Settings.Ad_Unit_ID);

                FormsWebViewRenderer.Initialize();
                LoadApplication(new App());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }