public virtual float GetBestScoreForLevel(int lvlNr, bool checkUserID)
    {
        if (MFPClassic.Hook.devMode)
        {
            return(0);
        }

        float num1 = 0.0f;

        for (float num2 = new float(); (double)num2 <= 2.0; ++num2)
        {
            int num3 = SavedData.GetInt(CryptoString.Encrypt(RuntimeServices.op_Addition(RuntimeServices.op_Addition(RuntimeServices.op_Addition("lvlScore", (object)lvlNr), "diff"), (object)num2)));
            if ((double)num3 > (double)num1)
            {
                if (checkUserID)
                {
                    string str = SavedData.GetString(CryptoString.Encrypt(RuntimeServices.op_Addition(RuntimeServices.op_Addition(RuntimeServices.op_Addition(RuntimeServices.op_Addition("lvlScore", (object)lvlNr), "diff"), (object)num2), "ID")));
                    if (this.userID == "0" && str != "-1" && str != "-999" || str == this.userID)
                    {
                        num1 = (float)num3;
                    }
                }
                else
                {
                    num1 = (float)num3;
                }
            }
        }
        return(num1);
    }
Esempio n. 2
0
        public void SymmetricEncryptor_HeavyUsage()
        {
            CryptoRandomizer random         = new CryptoRandomizer();
            const int        Iterations     = 100;
            const int        MaxMemoryBlock = 100000;


            for (int i = 0; i < Iterations; i++)
            {
                int    blockSize = random.Next(MaxMemoryBlock);
                byte[] buffer    = new ByteGenerator().GenerateBytes(blockSize);
                string key       = CryptoString.GenerateRandomText(1000);

                byte[] decryptedBuffer;
                byte[] encryptedBuffer;

                using (SymmetricEncryptor encryptor = new SymmetricEncryptor())
                {
                    //Encrypt
                    encryptedBuffer = encryptor.EncryptBytes(buffer, key);

                    // Decrypt
                    decryptedBuffer = encryptor.DecryptBytes(encryptedBuffer, key);
                }                 // IDispose - Closes and clears the keys in memory

                // Assert - Check to make sure the bytes are all the same
                Assert.IsTrue(buffer.SequenceEqual(decryptedBuffer));
            }
        }
Esempio n. 3
0
        public void PasswordHasher_BasicUsage()
        {
            Hasher sha256 = new Hasher(SHA256.Create());

            // Create password -> SecureString -> CryptpString
            string       password       = "******";
            SecureString securePassword = CryptoString.StringToSecureString(password);
            CryptoString cryptoPassword = new CryptoString(securePassword);

            // Create the Hash
            PasswordHasher hasher = new PasswordHasher();
            string         hash   = hasher.PasswordHash(cryptoPassword);

            // FAIL - BAD Hash
            string badHash = sha256.Hash("randomhash203984vb5230984vb230984tb7v23b098tu13908tu31908vn");

            Assert.IsFalse(hasher.PasswordCheck(cryptoPassword, badHash));

            // FAIL - BAD Password
            CryptoString badPassword = new CryptoString(CryptoString.StringToSecureString("BADPASSWORD"));

            Assert.IsFalse(hasher.PasswordCheck(badPassword, hash));

            // SUCCESS - GOOD Password and Hash
            Assert.IsTrue(hasher.PasswordCheck(cryptoPassword, hash));
        }
Esempio n. 4
0
        /// <summary>
        /// Generazione del token di autenticazione per l'utente specificato
        /// </summary>
        /// <param name="userId">User id dell'utente proprietario del token</param>
        /// <param name="tokenType">Tipo di token da generare</param>
        /// <param name="milliseconds">Durata del token espressa in millisecondi</param>
        /// <param name="keyLength">Lunghezza della chiave espressa in numero di caratteri</param>
        /// <param name="initializationVectorLength">Lunghezza dell'initialization vector espressa in numero di caratteri</param>
        /// <returns>Token criptato</returns>
        public override string Generate(string userId, AuthTokenManager.TokenTypeEnum tokenType, double milliseconds, AuthTokenManager.KeyLengthEnum keyLength, AuthTokenManager.KeyLengthEnum initializationVectorLength)
        {
            // Chiave privata, vettore di inizializzazione e la userid pulita
            String key, initializationVector, cleanedUserId;

            // Pulizia dello user id
            cleanedUserId = userId.Trim().ToUpper();

            // Decifratura lunghezza della chiave e dell'initialization vector
            int kLength  = this.DecodeKeyLength(keyLength);
            int ivLength = this.DecodeKeyLength(initializationVectorLength);

            // Generazione della chiavi
            key = KeyGeneratorHelper.BetterRandomString(kLength);
            initializationVector = KeyGeneratorHelper.BetterRandomString(ivLength);

            try
            {
                CryptoString crypto       = new CryptoString(key, initializationVector);
                string       encodedValue = crypto.Encrypt(String.Format(ENCRYPTED_VALUE_FORMAT, cleanedUserId, GetSessionId(), this.GetActualDateFromDB(), tokenType, this.GetExpirationDate(tokenType, milliseconds)));

                // Salvataggio token su db
                this.SaveToken(key, encodedValue, initializationVector, cleanedUserId);

                return(string.Format("{0}{1}", TOKEN_PREFIX, encodedValue));
            }
            catch (Exception ex)
            {
                throw new EncryptionException(ex);
            }
        }
    public virtual float GetBestTimeForLevel(int lvlNr)
    {
        float num1 = 9999999f;

        for (float num2 = new float(); (double)num2 <= 2.0; ++num2)
        {
            float num3 = SavedData.GetFloat(CryptoString.Encrypt(RuntimeServices.op_Addition(RuntimeServices.op_Addition(RuntimeServices.op_Addition("lvlTime", (object)lvlNr), "diff"), (object)num2)));
            if ((double)num3 != 0.0 && (double)num3 < (double)num1)
            {
                num1 = num3;
            }
        }
        return(num1);
    }
        /// <summary>
        /// Hashes a Password and returns a hash fingerprint
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public string PasswordHash(CryptoString password)
        {
            Hasher hasher = new Hasher();
            string pepper;
            string hash;

            // Generate Pepper
            pepper = new string(Enumerable.Repeat(Options.PepperChars, 1).Select(s => s[random.Next(s.Length)]).ToArray());

            // Create your hash
            hash = hasher.SecureHash(CryptoString.SecureStringToString(password.GetSecureString()) + Options.Salt + pepper, SecureHashDelay);

            return(hash);
        }
Esempio n. 7
0
        public void TestCryptoString()
        {
            string key = CryptoString.MakeKey();
            string iv  = CryptoString.MakeIV();

            string test = "Test String";

            CryptoString cs = new CryptoString(key, iv);

            string crypto = cs.Encrypt(test);
            string plain  = cs.Decrypt(crypto);

            Assert.AreEqual(test, plain);
        }
Esempio n. 8
0
        public void PasswordHasher_BasicUsageWiki()
        {
// Create password -> SecureString -> CryptpString
            string         password       = "******";
            PasswordHasher hasher         = new PasswordHasher();
            SecureString   securePassword = CryptoString.StringToSecureString(password);
            CryptoString   cryptoPassword = new CryptoString(securePassword);

// Create the Hash
            string hash = hasher.PasswordHash(cryptoPassword);

// Check the password against the hash, salt and pepper
            bool valid = hasher.PasswordCheck(cryptoPassword, hash);
        }
Esempio n. 9
0
        /// <summary>
        /// Ripristino del token di autenticazione per l'utente specificato
        /// </summary>
        /// <param name="userId">Identificativo dell'utente proprietario del token</param>
        /// <param name="token">Token criptato</param>
        /// <returns>Token decriptato</returns>
        public override string Restore(string userId, string token)
        {
            if (IsAuthToken(token))
            {
                // Pulizia del token
                String cleanedToken = token.Replace(TOKEN_PREFIX, String.Empty);

                // Pulizia e della user id
                String cleanedUserId = userId.Trim().ToUpper();

                // Recupero delle informazioni di encryption dal DB
                CryptoString crypto = this.LoadToken(cleanedToken);

                String decryptedValue = String.Empty;
                try
                {
                    decryptedValue = crypto.Decrypt(cleanedToken);
                }
                catch (Exception ex)
                {
                    throw new DecryptionException(ex);
                }

                // Spacchettamento del token
                Dictionary <String, String> keyValuePairs = GetTokenKeyValuePairs(decryptedValue);

                // Controllo della validità del token
                bool expired = this.IsExpiredToken(keyValuePairs[TOKENEXPIRATIONDATE]);

                // Se il token è scaduto, viene cancellato il record dalla tabella
                if (expired)
                {
                    this.RemoveTokenFromDB(cleanedToken);
                }

                if (String.Compare(cleanedUserId, keyValuePairs[UID], true) == 0 && (!expired || this.DecodeTokenType(keyValuePairs[TOKENTYPE]) == AuthTokenManager.TokenTypeEnum.OneTime))
                {
                    return(keyValuePairs[SESSIONID]);
                }
                else
                {
                    throw new NoAuthenticationTokenForUserException(userId);
                }
            }
            else
            {
                throw new AuthenticationTokenNotValidException();
            }
        }
 public virtual void CheckForBrokenScores()
 {
     for (int index = new int(); index <= 52; ++index)
     {
         for (float num1 = new float(); (double)num1 <= 2.0; ++num1)
         {
             int num2 = SavedData.GetInt(CryptoString.Encrypt(RuntimeServices.op_Addition(RuntimeServices.op_Addition(RuntimeServices.op_Addition("lvlScore", (object)index), "diff"), (object)num1)));
             if (num2 >= 9999999 || num2 < 0)
             {
                 MonoBehaviour.print((object)RuntimeServices.op_Addition("BROKEN SCORE DETECTED: ", (object)num2));
                 SavedData.SetInt(CryptoString.Encrypt(RuntimeServices.op_Addition(RuntimeServices.op_Addition(RuntimeServices.op_Addition("lvlScore", (object)index), "diff"), (object)num1)), 0);
             }
         }
     }
 }
Esempio n. 11
0
        public void TestCryptoGetters()
        {
            string key = CryptoString.MakeKey();
            string iv  = CryptoString.MakeIV();

            CryptoString cs = new CryptoString
            {
                Key = key,
                IV  = iv
            };

            string key2 = cs.Key;
            string iv2  = cs.IV;

            Assert.AreEqual(key, key2);
            Assert.AreEqual(iv, iv2);
        }
Esempio n. 12
0
        public void TestCryptoStringDefaultConstructor()
        {
            string key = CryptoString.MakeKey();
            string iv  = CryptoString.MakeIV();

            string test = "Test String";

            CryptoString cs = new CryptoString
            {
                Key = key,
                IV  = iv
            };

            string crypto = cs.Encrypt(test);
            string plain  = cs.Decrypt(crypto);

            Assert.AreEqual(test, plain);
        }
Esempio n. 13
0
        public void TestCryptoStringNoKeyEncrypt()
        {
            string test = "Test String";

            CryptoString cs = new CryptoString();

            try
            {
                string crypto = cs.Encrypt(test);
                string plain  = cs.Decrypt(crypto);

                Assert.Fail("Should have thrown an exception");
            }
            catch (Exception ex)
            {
                Assert.AreEqual("savedKey and savedIV must be non-null.", ex.Message);
            }
        }
 public virtual void Update()
 {
     if (this.simulateMousePos)
     {
         this.fakeMousePos  += new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y")) * (0.005f + this.simulateMousePosSensitivity) * 68f * (Mathf.Round((float)(Screen.width + Screen.height)) / 2f / 1500f);
         this.fakeMousePos.x = Mathf.Clamp(this.fakeMousePos.x, 0.0f, (float)Screen.width);
         this.fakeMousePos.y = Mathf.Clamp(this.fakeMousePos.y, 0.0f, (float)Screen.height);
     }
     if (!this.allowLeaderboard || !this.uploadAllScores)
     {
         return;
     }
     if (this.curUploadAllScores <= 52)
     {
         if (!this.OkToUploadScore())
         {
             return;
         }
         string empty = string.Empty;
         for (float num1 = new float(); (double)num1 <= 2.0; ++num1)
         {
             if (SavedData.GetString(CryptoString.Encrypt(RuntimeServices.op_Addition(RuntimeServices.op_Addition(RuntimeServices.op_Addition(RuntimeServices.op_Addition("lvlScore", (object)this.curUploadAllScores), "diff"), (object)num1), "ID"))) == "-999")
             {
                 int num2 = empty == "-999" ? 1 : 0;
             }
         }
         string leaderboardName = this.GetLeaderboardName(this.curUploadAllScores, string.Empty, false);
         if (leaderboardName != string.Empty)
         {
             float num1 = new float();
             float num2 = !this.speedrunnerLeaderboard ? this.GetBestScoreForLevel(this.curUploadAllScores, true) : this.GetBestTimeForLevel(this.curUploadAllScores) * 1000f;
             if ((double)num2 > 0.0 && (double)num2 < 9999999.0)
             {
                 this.steamLeaderboardsScript.DoUploadScore((int)num2, leaderboardName);
                 MFPClassic.MFPEditorUtils.Log("Uploading leaderboard score for:" + leaderboardName);
             }
         }
         ++this.curUploadAllScores;
     }
     else
     {
         this.uploadAllScores = false;
     }
 }
Esempio n. 15
0
        public IList GetPersonOnJob(string sUserCode, string sPassWord, string sOperationJobId)
        {
            PersonOnJob o;

            ObjectQuery oQuery        = new ObjectQuery();
            string      sTempPassWord = string.Empty;

            if (string.IsNullOrEmpty(sPassWord))
            {
                sPassWord = "";
            }
            sTempPassWord = CryptoString.Encrypt(sPassWord, sPassWord);
            //oQuery.AddCriterion(Expression.Eq("StandardPerson.Password", sPassWord));
            oQuery.AddCriterion(Expression.Eq("StandardPerson.Code", sUserCode));
            oQuery.AddCriterion(Expression.Eq("OperationJob.Id", sOperationJobId));
            oQuery.AddCriterion(Expression.Eq("State", 1));
            oQuery.AddFetchMode("OperationJob", FetchMode.Eager);
            oQuery.AddFetchMode("StandardPerson", FetchMode.Eager);
            oQuery.AddFetchMode("OperationJob.OperationOrg", FetchMode.Eager);
            IList lstResult = dao.ObjectQuery(typeof(PersonOnJob), oQuery);

            for (int i = lstResult.Count - 1; i > -1; i--)
            {
                PersonOnJob oPersonOnJob = lstResult[i] as PersonOnJob;
                if (oPersonOnJob.StandardPerson != null)
                {
                    if (string.Equals(oPersonOnJob.StandardPerson.Password, sTempPassWord) || string.Equals(oPersonOnJob.StandardPerson.Password, sPassWord))
                    {
                        continue;
                    }
                    else if (string.IsNullOrEmpty(oPersonOnJob.StandardPerson.Password) && string.IsNullOrEmpty(sTempPassWord))
                    {
                        continue;
                    }
                    else
                    {
                        lstResult.RemoveAt(i);
                    }
                }
            }
            return(lstResult);
        }
        public void CryptoString_TestUtilityMethods()
        {
            string password = "******";
            int    length   = 100;

            string random = CryptoString.GenerateRandomText(length);

            Assert.IsTrue(random.Length > (length / 2));

            string byteString = CryptoString.BytesToString(new ByteGenerator().GenerateBytes(length));

            Assert.IsTrue(byteString.Length > 0);


            // String conversions
            SecureString secureString   = CryptoString.StringToSecureString(password);
            string       unsecureString = CryptoString.SecureStringToString(secureString);

            Assert.IsTrue(password.Equals(unsecureString));
        }
        public void CryptoCredential_ConfirmPropertiesSet()
        {
            // Create Credentials
            CryptoString      passphrase  = new CryptoString("My Passphrase");
            int               pin         = 1234;
            CryptoCredentials credentials = new CryptoCredentials();

            // Assign Credentials and ensure the 'Use' properties get updated
            Assert.IsFalse(credentials.UsePassphrase);
            credentials.Passphrase = passphrase;
            Assert.IsTrue(credentials.UsePassphrase);

            Assert.IsFalse(credentials.UsePin);
            credentials.Pin = pin;
            Assert.IsTrue(credentials.UsePin);

            string key = credentials.Key;

            Assert.IsTrue(Hasher.IsHashValid(key));
        }
        public void CryptoString_BasicUsuage()
        {
            string       password     = "******";
            SecureString secureString = CryptoString.StringToSecureString(password);             // Only used for test
            string       decryptedString;

            CryptoString crypto = new CryptoString(secureString);

            // Make sure the ToString DOES NOT return the string
            decryptedString = crypto.ToString();
            Assert.IsFalse(decryptedString.Equals(password));

            // Use this only if SecureString is not accepted
            string useString = CryptoString.SecureStringToString(crypto.GetSecureString());

            ////////////////////////////////////////////
            // You can now use the useString variable
            ////////////////////////////////////////////
            // When you done fill the variable full of random Text
            // NOTE: Not totally secure, but an added level of obsfucation
            useString = CryptoString.GenerateRandomText(10000);
        }
    public virtual void DoVersionCheck()
    {
        MonoBehaviour.print((object)"Checking build number...");
        float num1 = SavedData.GetFloat(CryptoString.Encrypt("BuildVersionNumber"));

        if ((double)this.currentBuildVersionNumber == 0.0 || (double)num1 == (double)this.currentBuildVersionNumber || ((double)num1 == 1.01999998092651 || (double)this.currentBuildVersionNumber != 1.02999997138977))
        {
            return;
        }
        for (int index = new int(); index <= 52; ++index)
        {
            for (float num2 = new float(); (double)num2 <= 2.0; ++num2)
            {
                if (SavedData.HasKey(CryptoString.Encrypt(RuntimeServices.op_Addition(RuntimeServices.op_Addition(RuntimeServices.op_Addition(RuntimeServices.op_Addition("lvlScore", (object)index), "diff"), (object)num2), "ID"))))
                {
                    SavedData.SetString(CryptoString.Encrypt(RuntimeServices.op_Addition(RuntimeServices.op_Addition(RuntimeServices.op_Addition(RuntimeServices.op_Addition("lvlScore", (object)index), "diff"), (object)num2), "ID")), "-1");
                }
            }
        }
        SavedData.SetFloat(CryptoString.Encrypt("BuildVersionNumber"), this.currentBuildVersionNumber);
        MonoBehaviour.print((object)"Save from older build. Disabling auto-score-upload for saved scores on boot.");
    }
Esempio n. 20
0
        /// <summary>
        /// Funzione per la rimozione del token specificato
        /// </summary>
        /// <param name="userId">Id dell'utente proprietario del token</param>
        /// <param name="token">Token da eliminare</param>
        public override void RemoveToken(String userId, String token)
        {
            if (IsAuthToken(token))
            {
                // Pulizia del token
                String cleanedToken = token.Replace(TOKEN_PREFIX, String.Empty);

                // Recupero delle informazioni di encryption dal DB
                CryptoString crypto = this.LoadToken(cleanedToken);

                string decryptedValue = string.Empty;

                try
                {
                    decryptedValue = crypto.Decrypt(cleanedToken);
                }
                catch (Exception ex)
                {
                    throw new DecryptionException(ex);
                }

                // Spacchettamento delle informazioni
                Dictionary <string, string> keyValuePairs = GetTokenKeyValuePairs(decryptedValue);

                // Se user id passato per parametro e user id presente nel token non corrispondono, non si può procedere
                if (!userId.Trim().ToUpper().Equals(keyValuePairs[UID]))
                {
                    throw new NoAuthenticationTokenForUserException(userId);
                }

                // Rimozione del token dal DB
                this.RemoveTokenFromDB(cleanedToken);
            }
            else
            {
                throw new AuthenticationTokenNotValidException();
            }
        }
        public void CryptoDataFile_EncryptedEntireFileTest()
        {
            string       passphraseString = "My Passphrase";
            CryptoString passphrase       = new CryptoString(CryptoString.StringToSecureString(passphraseString));

            CryptoCredentials credentials = new CryptoCredentials
            {
                Passphrase = passphrase,
            };

            string dataFileName = "EncryptedFile.bin";
            string fileContent  = "My Test Content";


            using (AutoDeleteFiles autoDeleteFile = new AutoDeleteFiles(dataFileName))
            {
                // Save some data
                CryptoDataFile dataFile = new CryptoDataFile(dataFileName);
                byte[]         content1 = Encoding.UTF8.GetBytes(fileContent);
                dataFile.Credentials = credentials;
                dataFile.EncryptFile = true;
                dataFile.Content     = content1;
                dataFile.Save();
                byte[] fileBytes1 = dataFile.SaveToBytes();

                // Now load the data and compare
                CryptoDataFile dataLoader = new CryptoDataFile(dataFileName);
                dataLoader.Credentials = credentials;
                dataLoader.EncryptFile = true;
                dataLoader.Load();
                dataLoader.LoadFromBytes(fileBytes1);
                byte[] content2 = dataLoader.Content;


                Assert.IsTrue(content1.SequenceEqual(content2));
                Assert.IsTrue(dataFile.Content.SequenceEqual(dataLoader.Content));
            }
        }
        /// <summary>
        /// Checks a password against its hash to validate if it matches. The check automagically handles incorporating the Salt and even checks
        /// against all the Pepper value as well. As a User you just pass in the password and Hash and let the method do the work for you.
        /// </summary>
        /// <param name="password"></param>
        /// <param name="hash"></param>
        /// <returns></returns>
        public bool PasswordCheck(CryptoString password, string hash)
        {
            Hasher hasher     = new Hasher();
            bool   isValid    = false;
            int    iterations = 0;

            foreach (var c in Options.PepperChars.ToArray())
            {
                iterations++;
                string attemptPassword = password + Options.Salt + c;
                string attemptHash     = hasher.SecureHash(CryptoString.SecureStringToString(password.GetSecureString()) + Options.Salt + c, SecureHashDelay);

                // Check if you got a hit
                if (hash.Equals(attemptHash))
                {
                    // You got a hit so the Password is Valid
                    isValid = true;
                    Debug.WriteLine($"Found a hit after {iterations} iterations.");
                    break;
                }
            }
            return(isValid);
        }
Esempio n. 23
0
 /// <summary>
 /// 获取身份验证的Value
 /// </summary>
 /// <returns></returns>
 public static string GetAuthMenuIdEncryptValue(string key)
 {
     return(CryptoString.Encrypt(key, key));
 }