public static SqlString GenerateSalt(int length)
 {
     byte[] array = new byte[length];
     RNGCryptoServiceProvider rNGCryptoServiceProvider = new RNGCryptoServiceProvider();
     rNGCryptoServiceProvider.GetBytes(array);
     return new SqlString(Convert.ToBase64String(array));
 }
 public string CreateSalt(int size)
 {
     size = 5;
     RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
     byte[] buff = new byte[size];
     rng.GetBytes(buff);
     return Convert.ToBase64String(buff);
 }
Exemple #3
0
    /// <summary>
    /// 高斯密钥 获取 伪随机数种子
    /// 从而确保伪随机数的随机性
    /// </summary>
    /// <returns></returns>
    private int GetSeed()
    {
        byte[] bytes = new byte[4];
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        rng.GetBytes(bytes);

        return BitConverter.ToInt32(bytes, 0);
    }
 internal static byte[] GenerateSaltInternal(int byteLength = SaltSize)
 {
     byte[] buf = new byte[byteLength];
     using (var rng = new RNGCryptoServiceProvider())
     {
         rng.GetBytes(buf);
     }
     return buf;
 }
Exemple #5
0
        public static string GenerateSalt(int byteLength = SaltSize)
        {
            byte[] Buff = new byte[byteLength];
            using (var Prng = new RNGCryptoServiceProvider())
            {
                Prng.GetBytes(Buff);
            }

            return Convert.ToBase64String(Buff);
        }
Exemple #6
0
    public static string CreateSalt(int size)
    {
        //Generate a cryptographic random number.
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        byte[] buff = new byte[size];
        rng.GetBytes(buff);

        // Return a Base64 string representation of the random number.
        return Convert.ToBase64String(buff);
    }
    public static string CreateHash(string password)
    {
        RNGCryptoServiceProvider csprng = new RNGCryptoServiceProvider();
        byte[] salt = new byte[SALT_BYTE_SIZE];
        csprng.GetBytes(salt);

        byte[] hash = PBKDF2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
        return PBKDF2_ITERATIONS + ":" +
            Convert.ToBase64String(salt) + ":" +
            Convert.ToBase64String(hash);
    }
    public PasswordGenerator()
    {
        this.Minimum = DefaultMinimum;
        this.Maximum = DefaultMaximum;
        this.ConsecutiveCharacters = false;
        this.RepeatCharacters = true;
        this.ExcludeSymbols = false;
        this.Exclusions = null;

        rng = new RNGCryptoServiceProvider();
    }
        public static void GetNonZeroBytes()
        {
            using (var rng = new RNGCryptoServiceProvider())
            {
                Assert.Throws<ArgumentNullException>("data", () => rng.GetNonZeroBytes(null));

                // Array should not have any zeros
                byte[] rand = new byte[65536];
                rng.GetNonZeroBytes(rand);
                Assert.Equal(-1, Array.IndexOf<byte>(rand, 0));
            }
        }
Exemple #10
0
 public static string CreateMachineKey(int length)
 {
     RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
     byte[] random = new byte[length/2]; 
     rng.GetBytes(random);
     StringBuilder machineKey = new StringBuilder(length);
     for (int i = 0; i < random.Length; i++)
     {
         machineKey.Append(String.Format("{0:X2}", random[i]));
     }
     return machineKey.ToString();
 }
    public static string CreateSalt(int size)
    {
        // Taken from: http://stackoverflow.com/questions/2138429/hash-and-salt-passwords-in-c-sharp

        //Generate a cryptographic random number.
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        byte[] buff = new byte[size];
        rng.GetBytes(buff);

        // Return a Base64 string representation of the random number.
        return Convert.ToBase64String(buff);
    }
Exemple #12
0
    /// <summary>
    /// Creates a salted PBKDF2 hash of the password.
    /// </summary>
    /// <param name="password">The password to hash.</param>
    /// <returns>The hash of the password.</returns>
    public static string CreateHash(string password)
    {
        // Generate a random salt
        RNGCryptoServiceProvider csprng = new RNGCryptoServiceProvider();
        byte[] salt = new byte[SALT_BYTE_SIZE];
        csprng.GetBytes(salt);

        // Hash the password and encode the parameters
        byte[] hash = PBKDF2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
        return PBKDF2_ITERATIONS + ":" +
            Convert.ToBase64String(salt) + ":" +
            Convert.ToBase64String(hash);
    }
 IList<GameObject> Shuffle(IList<GameObject> list)
 {
     RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
     int n = list.Count;
     while (n > 1)
     {
         byte[] box = new byte[1];
         do provider.GetBytes(box);
         while (!(box[0] < n * (Byte.MaxValue / n)));
         int k = (box[0] % n);
         n--;
         GameObject value = list[k];
         list[k] = list[n];
         list[n] = value;
     }
     return list;
 }
Exemple #14
0
 public static string GetPassword(int size)
 {
     char[] chars = new char[65];
     chars =
     "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890@&$".ToCharArray();
     byte[] data = new byte[1];
     RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
     crypto.GetNonZeroBytes(data);
     data = new byte[size];
     crypto.GetNonZeroBytes(data);
     StringBuilder password = new StringBuilder(size);
     foreach (byte b in data)
     {
         password.Append(chars[b % (chars.Length)]);
     }
     return password.ToString();
 }
Exemple #15
0
 public static string GetUniqueId(int size)
 {
     char[] chars = new char[62];
     chars =
     "1234567890".ToCharArray();
     byte[] data = new byte[1];
     RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
     crypto.GetNonZeroBytes(data);
     data = new byte[size];
     crypto.GetNonZeroBytes(data);
     StringBuilder id = new StringBuilder(size);
     foreach (byte b in data)
     {
         id.Append(chars[b % (chars.Length)]);
     }
     return id.ToString();
 }
 public static string GetUniqueKey(int maxSize)
 {
     char[] chars = new char[62];
     chars =
     "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW XYZ1234567890".ToCharArray();
     byte[] data = new byte[1];
     RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
     crypto.GetNonZeroBytes(data);
     data = new byte[maxSize];
     crypto.GetNonZeroBytes(data);
     StringBuilder result = new StringBuilder(maxSize);
     foreach (byte b in data)
     {
         result.Append(chars[b % (chars.Length - 1)]);
     }
     return result.ToString();
 }
Exemple #17
0
    public int NextRandom(bool allowNegative)
    {
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] bytes = new byte[4];
            rng.GetNonZeroBytes(bytes);

            int number = BitConverter.ToInt32(bytes, 0);
            if (!allowNegative)
            {
                if (number < 0)
                {
                    number = -number;
                }
            }

            return number;
    }
            /**
             * This function generates random string of the given input length.
             *
             * @param _plainText
             *            Plain text to be encrypted
             * @param _key
             *            Encryption Key. You'll have to use the same key for decryption
             * @return returns encrypted (cipher) text
             */
            internal static string GenerateRandomIV(int length)
            {
                char[] _iv = new char[length];
                byte[] randomBytes = new byte[length];

                using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
                {
                    rng.GetBytes(randomBytes);
                }

                for (int i = 0; i < _iv.Length; i++)
                {
                    int ptr = randomBytes[i] % CharacterMatrixForRandomIVStringGeneration.Length;
                    _iv[i] = CharacterMatrixForRandomIVStringGeneration[ptr];
                }

                return new string(_iv);
            }
    public static Boolean Test()
    {
        Boolean bRes = true;

		RSAPKCS1KeyExchangeFormatter pcef1 = new RSAPKCS1KeyExchangeFormatter(RSA.Create());
		RSAPKCS1KeyExchangeDeformatter pced1 = new RSAPKCS1KeyExchangeDeformatter(RSA.Create());
		Console.WriteLine("pcef1 parameters: " + pcef1.Parameters + "\npced1 parameters: " + pced1.Parameters);

		bRes = TestKeyExchange(pcef1, pced1, false) && bRes;

		RSA rsa = RSA.Create();
		RandomNumberGenerator rng = new RNGCryptoServiceProvider();
		RSAPKCS1KeyExchangeFormatter pcef2 = new RSAPKCS1KeyExchangeFormatter();
		RSAPKCS1KeyExchangeDeformatter pced2 = new RSAPKCS1KeyExchangeDeformatter(rsa);
		RSA rsa1 = RSA.Create();
		rsa1.ImportParameters(rsa.ExportParameters(false));
		pcef2.SetKey(rsa1);
		pcef2.Rng = rng;
		pced2.RNG = rng;
		Console.WriteLine("pcef2 parameters: " + pcef2.Parameters + "\npced2 parameters: " + pced2.Parameters);

		bRes = TestKeyExchange(pcef2, pced2, true) && bRes;

		RSAOAEPKeyExchangeFormatter ocef1 = new RSAOAEPKeyExchangeFormatter(RSA.Create());
		RSAOAEPKeyExchangeDeformatter oced1 = new RSAOAEPKeyExchangeDeformatter(RSA.Create());
		Console.WriteLine("ocef1 parameters: " + ocef1.Parameters + "\noced1 parameters: " + oced1.Parameters);

		bRes = TestKeyExchange(ocef1, oced1, false) && bRes;

		rsa = RSA.Create();
		rng = new RNGCryptoServiceProvider();
		RSAOAEPKeyExchangeFormatter ocef2 = new RSAOAEPKeyExchangeFormatter();
		RSAOAEPKeyExchangeDeformatter oced2 = new RSAOAEPKeyExchangeDeformatter(rsa);
		rsa1 = RSA.Create();
		rsa1.ImportParameters(rsa.ExportParameters(false));
		ocef2.SetKey(rsa1);
		ocef2.Rng = rng;
//		oced2.RNG = rng;
		Console.WriteLine("ocef2 parameters: " + ocef2.Parameters + "\noced2 parameters: " + oced2.Parameters);

		bRes = TestKeyExchange(ocef2, oced2, true) && bRes;

        return bRes;
    }
 // This method simulates a roll of the dice. The input parameter is the
 // number of sides of the dice.
 public static byte RollDice(byte numberSides)
 {
     if (numberSides <= 0)
         throw new ArgumentOutOfRangeException("numberSides");
     // Create a new instance of the RNGCryptoServiceProvider.
     RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
     // Create a byte array to hold the random value.
     byte[] randomNumber = new byte[1];
     do
     {
         // Fill the array with a random value.
         rngCsp.GetBytes(randomNumber);
     }
     while (!IsFairRoll(randomNumber[0], numberSides));
     // Return the random number mod the number
     // of sides.  The possible values are zero-
     // based, so we add one.
     return (byte)((randomNumber[0] % numberSides) + 1);
 }
Exemple #21
0
 public static string GenerateRandomId()
 {
     int maxSize = 36;
     char[] chars = new char[62];
     string a;
     a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
     chars = a.ToCharArray();
     int size = maxSize;
     byte[] data = new byte[1];
     RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
     crypto.GetNonZeroBytes(data);
     size = maxSize;
     data = new byte[size];
     crypto.GetNonZeroBytes(data);
     StringBuilder result = new StringBuilder(size);
     foreach (byte b in data)
     { result.Append(chars[b % (chars.Length - 1)]); }
     return result.ToString();
 }
Exemple #22
0
 public void gen_pwd()
 {
     int maxSize = 10;
     char[] chars = new char[62];
     string a = "abcdefghijklmno~@#$%^&*()+pqrstuvwxyz0123456789";
     chars = a.ToCharArray();
     int size = maxSize;
     byte[] data = new byte[1];
     RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
     crypto.GetNonZeroBytes(data);
     size = maxSize;
     data = new byte[size];
     crypto.GetNonZeroBytes(data);
     StringBuilder result = new StringBuilder(size);
     foreach (byte b in data)
     {
         result.Append(chars[b % (chars.Length - 1)]);
     }
     pwdd = result.ToString();
 }
Exemple #23
0
	public static int GetRandomIntBetween(int minValue, int maxValue)
	{
		// Make maxValue inclusive.
		//maxValue++;
		
		var rng = new RNGCryptoServiceProvider();
		var uint32Buffer = new byte[4];
		long diff = maxValue - minValue;
		
		while (true)
		{
			rng.GetBytes(uint32Buffer);
			uint rand = BitConverter.ToUInt32(uint32Buffer, 0);
			const long max = (1 + (long)int.MaxValue);
			long remainder = max % diff;
			if (rand < max - remainder)
			{
				return (int)(minValue + (rand % diff));
			}
		}
	}
        public static void DifferentSequential_10()
        {
            // Ensure that the RNG doesn't produce a stable set of data.
            byte[] first = new byte[10];
            byte[] second = new byte[10];

            using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(first);
                rng.GetBytes(second);
            }

            // Random being random, there is a chance that it could produce the same sequence.
            // The smallest test case that we have is 10 bytes.
            // The probability that they are the same, given a Truly Random Number Generator is:
            // Pmatch(byte0) * Pmatch(byte1) * Pmatch(byte2) * ... * Pmatch(byte9)
            // = 1/256 * 1/256 * ... * 1/256
            // = 1/(256^10)
            // = 1/1,208,925,819,614,629,174,706,176
            Assert.NotEqual(first, second);
        }
    public static void HashWithSalt(
        string plaintext, ref string salt, out string hash)
    {
        const int SALT_BYTE_COUNT = 16;
        if (salt == null || salt == "")
        {
            byte[] saltBuf = new byte[SALT_BYTE_COUNT];
            RNGCryptoServiceProvider rng =
                new RNGCryptoServiceProvider();
            rng.GetBytes(saltBuf);

            StringBuilder sb =
                new StringBuilder(saltBuf.Length);
            for (int i = 0; i < saltBuf.Length; i++)
                sb.Append(string.Format("{0:X2}", saltBuf[i]));
            salt = sb.ToString();
        }

        hash = FormsAuthentication.
            HashPasswordForStoringInConfigFile(
            salt + plaintext, DefCryptoAlg);
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        byte[] arr = new byte[24];
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        rng.GetBytes(arr);
        System.Text.StringBuilder machineKey = new System.Text.StringBuilder(24);
        for (int i = 0; i < arr.Length; i++)
        {
            machineKey.Append(String.Format("{0:X2}", arr[i]));
        }
        Page.Response.Write(machineKey.ToString());



        Page.Response.Write(WebConfigurationManager.AppSettings["topic"] + "<br />");
        Page.Response.Write(WebConfigurationManager.ConnectionStrings["NorthwindConnection"] + "<br />");
        Page.Response.Write(WebConfigurationManager.GetSection("connectionStrings") + "<br />");
        CompilationSection cs = (CompilationSection)WebConfigurationManager.GetSection("system.web/compilation");
        foreach (AssemblyInfo item in cs.Assemblies)
        {
            Response.Write(item.Assembly + "<br /");
        }
    }
Exemple #27
0
 public CryptoService(IConfiguration configuration)
 {
     serverKey = configuration.GetValue <string>("ServerKey");
     rng       = new RNGCryptoServiceProvider();
 }
 public CryptographyController()
 {
     //加密随机数生成器创建加密型强随机值。
     RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
 }
Exemple #29
0
 public RngWrapper()
 {
     this._wrapped = new RNGCryptoServiceProvider();
 }
Exemple #30
0
 public RngWrapper(byte[] rgb)
 {
     this._wrapped = new RNGCryptoServiceProvider(rgb);
 }
        private static async Task LoginAsync(IChannelHandlerContext context, string username, string password,
                                             string hwid, string secretkey)
        {
            // This var is used for sending the unban date to the launcher
            var unbandate = DateTimeOffset.Now;

            try
            {
                var endpoint = new IPEndPoint(((IPEndPoint)context.Channel.RemoteAddress).Address.MapToIPv4(),
                                              ((IPEndPoint)context.Channel.RemoteAddress).Port);
                if (username.Length >= 20)
                {
                    Logger.Error("Login & Password to long for {0}", endpoint);
                    var check = new CCMessage();
                    check.Write(false);
                    check.Write("Username is more than 20 chars");
                    RmiSend(context, 16, check);
                    return;
                }

                if (hwid == string.Empty)
                {
                    Logger.Error("No HWID found on endpoint {0}", endpoint);
                    var check = new CCMessage();
                    check.Write(false);
                    check.Write("Cannot Generate HWID");
                    RmiSend(context, 16, check);
                    return;
                }


                if (Config.Instance.AuthAPI.BlockedHWIDS.Contains(hwid))
                {
                    Logger.Error("Hwid ban(conf): {0}, Address: {1}", hwid, endpoint);
                    goto hwidban;
                }

                if (Config.Instance.LauncherCheck)
                {
                    // Launcher Check
                    if (secretkey != Config.Instance.LauncherCheckKey)
                    {
                        Logger.Error("Wrong Launcher => User: "******" hwid: " + hwid + " from " + endpoint);
                        var keycheck = new CCMessage();
                        keycheck.Write(false);
                        keycheck.Write("Invalid Launcher");
                        RmiSend(context, 16, keycheck);
                        return;
                    }
                }

                using (var db = AuthDatabase.Open())
                {
                    Logger.Information("AuthAPI login from {0}, HWID: {1}", endpoint, hwid);


                    if (username.Length < 4 || password.Length < 4)
                    {
                        Logger.Error("Too short credentials for {username} / {endpoint}", username, endpoint);
                        var lengtherr = new CCMessage();
                        lengtherr.Write(false);
                        lengtherr.Write("Invalid length of username/password");
                        RmiSend(context, 16, lengtherr);
                        return;
                    }

                    if (!Namecheck.IsNameValid(username))
                    {
                        Logger.Error("Invalid username for {username} / {endpoint}", username, endpoint);
                        var nickerr = new CCMessage();
                        nickerr.Write(false);
                        nickerr.Write("Username contains invalid characters");
                        RmiSend(context, 16, nickerr);
                        return;
                    }

                    var result = await db.FindAsync <AccountDto>(statement => statement
                                                                 .Where($"{nameof(AccountDto.Username):C} = @{nameof(username)}")
                                                                 .Include <BanDto>(join => join.LeftOuterJoin())
                                                                 .WithParameters(new { Username = username }));

                    var account = result.FirstOrDefault();

                    var hwidResult = await db.FindAsync <HwidBanDto>(statement => statement
                                                                     .Where($"{nameof(HwidBanDto.Hwid):C} = @{nameof(hwid)}")
                                                                     .WithParameters(new { Hwid = hwid }));

                    if (hwidResult?.Any() ?? false)
                    {
                        Logger.Error("Hwid ban(db): {0}, Address: {1}", hwid, endpoint);
                        goto hwidban;
                    }

                    if (account == null &&
                        (Config.Instance.NoobMode || Config.Instance.AutoRegister))
                    {
                        account = new AccountDto {
                            Username = username
                        };

                        var newSalt = new byte[24];
                        using (var csprng = new RNGCryptoServiceProvider())
                        {
                            csprng.GetBytes(newSalt);
                        }

                        var hash = new byte[24];
                        using (var pbkdf2 = new Rfc2898DeriveBytes(password, newSalt, 24000))
                        {
                            hash = pbkdf2.GetBytes(24);
                        }

                        account.Password = Convert.ToBase64String(hash);
                        account.Salt     = Convert.ToBase64String(newSalt);

                        await db.InsertAsync(account);
                    }

                    var salt = Convert.FromBase64String(account?.Salt ?? "");

                    var passwordGuess =
                        new Rfc2898DeriveBytes(password, salt, 24000).GetBytes(24);
                    var actualPassword =
                        Convert.FromBase64String(account?.Password ?? "");

                    var difference =
                        (uint)passwordGuess.Length ^ (uint)actualPassword.Length;

                    for (var i = 0;
                         i < passwordGuess.Length && i < actualPassword.Length;
                         i++)
                    {
                        difference |= (uint)(passwordGuess[i] ^ actualPassword[i]);
                    }

                    if ((difference != 0 ||
                         string.IsNullOrWhiteSpace(account?.Password ?? "")) &&
                        !Config.Instance.NoobMode)
                    {
                        Logger.Error("Wrong credentials for {username} / {endpoint}", username, endpoint);
                        goto wrong;
                    }

                    if (account != null)
                    {
                        var now = DateTimeOffset.Now.ToUnixTimeSeconds();
                        var ban = account.Bans.FirstOrDefault(b => b.Date + (b.Duration ?? 0) > now);
                        if (ban != null)
                        {
                            var unbanDate = DateTimeOffset.FromUnixTimeSeconds(ban.Date + (ban.Duration ?? 0));
                            unbandate = DateTimeOffset.FromUnixTimeSeconds(ban.Date + (ban.Duration ?? 0));
                            Logger.Error("{user} is banned until {until}", account.Username, unbanDate);
                            goto ban;
                        }

                        account.LoginToken = AuthHash
                                             .GetHash256(
                            $"{context.Channel.RemoteAddress}-{account.Username}-{account.Password}-{endpoint.Address.MapToIPv4()}")
                                             .ToLower();
                        account.LastLogin = $"{DateTimeOffset.UtcNow:yyyyMMddHHmmss}";
                        account.AuthToken = string.Empty;
                        account.newToken  = string.Empty;
                        await db.UpdateAsync(account);

                        var history = new AuthHistoryDto
                        {
                            Account   = account,
                            AccountId = account.Id,
                            Date      = DateTimeOffset.Now.ToUnixTimeSeconds(),
                            HWID      = hwid
                        };

                        await db.InsertAsync(history);

                        var ack = new CCMessage();
                        ack.Write(true);
                        ack.Write(account.LoginToken);
                        RmiSend(context, 16, ack);
                    }

                    Logger.Information("AuthAPI login success for {username}", username);
                    return;
                }
            }
            catch (Exception e)
            {
                Logger.Error(e.ToString());
                goto error;
            }

wrong:
            {
                var error = new CCMessage();
                error.Write(false);
                error.Write("Invalid username or password");
                RmiSend(context, 16, error);
            }

error:
            {
                var error = new CCMessage();
                error.Write(false);
                error.Write("Login error");
                RmiSend(context, 16, error);
            }

ban:
            {
                var error = new CCMessage();
                error.Write(false);
                error.Write("Account is banned until " + unbandate);
                RmiSend(context, 16, error);
            }

hwidban:
            {
                var error = new CCMessage();
                error.Write(false);
                error.Write("You have been blocked");
                RmiSend(context, 16, error);
            }
        }
Exemple #32
0
        static void Main(string[] args)
        {
            Stopwatch stopwatch = new Stopwatch();

            using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
            {
                stopwatch.Start();
                byte[] data = new byte[4];

                for (int i = 0; i < 10; i++)
                {
                    rng.GetBytes(data);

                    int value = BitConverter.ToInt32(data, 0);
                    Console.WriteLine("the value of RNGCryptoServiceProvider byte is " + value);
                    Console.WriteLine("the value of RNGCryptoServiceProvider base62 is" + Convert.ToBase64String(data));
                }
            }
            stopwatch.Stop();
            Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed.TotalMilliseconds);
            Console.WriteLine("----------------------------------------------------");

            var rand = new Random();

            {
                byte[] data = new byte[4];
                stopwatch.Start();
                var bytes = new byte[4];

                for (int i = 0; i < 10; i++)
                {
                    rand.NextBytes(bytes);


                    int value = BitConverter.ToInt32(bytes, 0);
                    Console.WriteLine("the value of Rand byte is " + value);
                    Console.WriteLine("the value of Rand base62 is " + Convert.ToBase64String(bytes));
                }
            }
            stopwatch.Stop();
            Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed.TotalMilliseconds);
            Console.ReadKey();


            Console.WriteLine("------------Press enter for Encryption---------------");


            Console.WriteLine("type a message to encrypt it.");
            string message = Console.ReadLine();

            Console.Write(Encrypter.Encrypt(message));



            Console.WriteLine("\n------------Press enter for decryption---------------");


            Console.WriteLine("type a message to decrypt it.");
            string demessage = Console.ReadLine();

            Console.Write(Encrypter.Dencrypt(demessage));



            Console.ReadKey();
        }
Exemple #33
0
        private void SaveSettings()
        {
            if (checkBoxChangeStaticInfo.Checked != Settings.Default.ChangeStaticInfo)
            {
                EntryOrGuidAndSourceType originalEntryOrGuidAndSourceType = ((MainForm)Owner).userControl.originalEntryOrGuidAndSourceType;
                ((MainForm)Owner).userControl.textBoxEntryOrGuid.Text          = originalEntryOrGuidAndSourceType.entryOrGuid.ToString();
                ((MainForm)Owner).userControl.comboBoxSourceType.SelectedIndex = ((MainForm)Owner).userControl.GetIndexBySourceType(originalEntryOrGuidAndSourceType.sourceType);
            }

            bool showTooltipsStaticly = Settings.Default.ShowTooltipsStaticly;
            bool generateComments     = Settings.Default.GenerateComments;
            bool phaseHighlighting    = false;// Settings.Default.PhaseHighlighting;

            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

            byte[] buffer = new byte[1024];

            rng.GetBytes(buffer);
            string salt = BitConverter.ToString(buffer);

            rng.Dispose();
            string decryptedPassword = textBoxPassword.Text;

            SAI_Editor_Manager.Instance.connString          = new MySqlConnectionStringBuilder();
            SAI_Editor_Manager.Instance.connString.Server   = textBoxHost.Text;
            SAI_Editor_Manager.Instance.connString.UserID   = textBoxUsername.Text;
            SAI_Editor_Manager.Instance.connString.Port     = CustomConverter.ToUInt32(textBoxPort.Text);
            SAI_Editor_Manager.Instance.connString.Database = textBoxWorldDatabase.Text;

            if (textBoxPassword.Text.Length > 0)
            {
                SAI_Editor_Manager.Instance.connString.Password = textBoxPassword.Text;
            }

            Settings.Default.UseWorldDatabase = radioButtonConnectToMySql.Checked;
            Settings.Default.Save();

            bool newConnectionSuccesfull = false;

            if (radioButtonConnectToMySql.Checked)
            {
                newConnectionSuccesfull = SAI_Editor_Manager.Instance.worldDatabase.CanConnectToDatabase(SAI_Editor_Manager.Instance.connString, false);
            }

            //! We also save the settings if no connection was made. It's possible the user unchecked
            //! the radioboxes, changed some settings and then set it back to no DB connection.
            if (newConnectionSuccesfull || !radioButtonConnectToMySql.Checked)
            {
                Settings.Default.Entropy     = salt;
                Settings.Default.Host        = textBoxHost.Text;
                Settings.Default.User        = textBoxUsername.Text;
                Settings.Default.Password    = textBoxPassword.Text.Length == 0 ? String.Empty : textBoxPassword.Text.ToSecureString().EncryptString(Encoding.Unicode.GetBytes(salt));
                Settings.Default.Database    = textBoxWorldDatabase.Text;
                Settings.Default.Port        = textBoxPort.Text.Length > 0 ? CustomConverter.ToUInt32(textBoxPort.Text) : 0;
                Settings.Default.AutoConnect = checkBoxAutoConnect.Checked;

                if (radioButtonConnectToMySql.Checked)
                {
                    SAI_Editor_Manager.Instance.ResetDatabases();
                }
            }

            Settings.Default.InstantExpand          = checkBoxInstantExpand.Checked;
            Settings.Default.PromptToQuit           = checkBoxPromptToQuit.Checked;
            Settings.Default.HidePass               = checkBoxHidePass.Checked;
            Settings.Default.AnimationSpeed         = CustomConverter.ToInt32(textBoxAnimationSpeed.Text);
            Settings.Default.PromptExecuteQuery     = checkBoxPromptExecuteQuery.Checked;
            Settings.Default.ChangeStaticInfo       = checkBoxChangeStaticInfo.Checked;
            Settings.Default.ShowTooltipsStaticly   = checkBoxShowTooltipsStaticly.Checked;
            Settings.Default.GenerateComments       = checkBoxAutoGenerateComments.Checked;
            Settings.Default.CreateRevertQuery      = checkBoxCreateRevertQuery.Checked;
            Settings.Default.PhaseHighlighting      = false;// checkBoxPhaseHighlighting.Checked;
            Settings.Default.DuplicatePrimaryFields = checkBoxDuplicatePrimaryFields.Checked;
            Settings.Default.WowExpansionIndex      = (uint)comboBoxWowExpansion.SelectedIndex;
            SAI_Editor_Manager.Instance.Expansion   = (WowExpansion)Settings.Default.WowExpansionIndex;
            Settings.Default.Save();

            if (newConnectionSuccesfull)
            {
                ((MainForm)Owner).checkBoxAutoConnect.Checked  = checkBoxAutoConnect.Checked;
                ((MainForm)Owner).textBoxHost.Text             = textBoxHost.Text;
                ((MainForm)Owner).textBoxUsername.Text         = textBoxUsername.Text;
                ((MainForm)Owner).textBoxPassword.Text         = decryptedPassword;
                ((MainForm)Owner).textBoxWorldDatabase.Text    = textBoxWorldDatabase.Text;
                ((MainForm)Owner).checkBoxAutoConnect.Checked  = checkBoxAutoConnect.Checked;
                ((MainForm)Owner).expandAndContractSpeed       = CustomConverter.ToInt32(textBoxAnimationSpeed.Text);
                ((MainForm)Owner).textBoxPassword.PasswordChar = Convert.ToChar(checkBoxHidePass.Checked ? '●' : '\0');
            }
            else if (radioButtonConnectToMySql.Checked) //! Don't report this if there is no connection to be made anyway
            {
                MessageBox.Show("The database settings were not saved because no connection could be established. All other changed settings were saved.", "Something went wrong!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (checkBoxAutoGenerateComments.Checked != generateComments && checkBoxAutoGenerateComments.Checked)
            {
                ((MainForm)Owner).userControl.GenerateCommentsForAllItems();
            }

            if (checkBoxShowTooltipsStaticly.Checked != showTooltipsStaticly)
            {
                ((MainForm)Owner).userControl.ExpandOrContractToShowStaticTooltips(!checkBoxShowTooltipsStaticly.Checked);
            }

            if (checkBoxPhaseHighlighting.Checked != phaseHighlighting)
            {
                ((MainForm)Owner).userControl.ListViewList.Apply(true);
                ((MainForm)Owner).userControl.checkBoxUsePhaseColors.Checked = checkBoxPhaseHighlighting.Checked;
            }

            ((MainForm)Owner).HandleUseWorldDatabaseSettingChanged();
        }
Exemple #34
0
 public RNG()
 {
     rnd      = new Random();
     rngCrypt = new RNGCryptoServiceProvider();
 }
 public CryptographicallyRandomCodeGenerator()
 {
     _rng = new RNGCryptoServiceProvider();
 }
 private static string GenerateToken()
 {
     using (var prng = new RNGCryptoServiceProvider())
     {
         return GenerateToken(prng);
     }
 }
Exemple #37
0
    private static KeyValuePair<string, string> Encrypt(string password)
    {
        RNGCryptoServiceProvider csprng = new RNGCryptoServiceProvider();
        byte[] salt = new byte[SALT_BYTES];
        csprng.GetBytes(salt);

        string saltStr = Convert.ToBase64String(salt);

        return new KeyValuePair<string, string>(saltStr, Encrypt(saltStr, password));
    }
Exemple #38
0
        public void Test1()
        {
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            TableServerData          tsd = new TableServerData("0");

            Entry[]  not_expired = new Entry[12];
            Entry[]  to_expire   = new Entry[12];
            DateTime now         = DateTime.UtcNow;
            DateTime live        = now.AddSeconds(120);
            DateTime expire      = now.AddSeconds(5);

            for (int i = 0; i < 4; i++)
            {
                byte[] key = new byte[20];
                rng.GetBytes(key);
                for (int j = 0; j < 3; j++)
                {
                    byte[] value = new byte[20];
                    rng.GetBytes(value);
                    Entry ent = new Entry(key, value, now, expire);
                    to_expire[i * 3 + j] = ent;
                    tsd.AddEntry(ent);
                    value = new byte[20];
                    rng.GetBytes(value);
                    ent = new Entry(key, value, now, live);
                    not_expired[i * 3 + j] = ent;
                    tsd.AddEntry(ent);
                    Assert.IsFalse(not_expired[i * 3 + j].Equals(to_expire[i * 3 + j]),
                                   String.Format("{0}: not_expired == to_expire.", i * 3 + j));
                }
            }

            for (int i = 0; i < 4; i++)
            {
                LinkedList <Entry> entries = tsd.GetEntries(not_expired[i * 3].Key);
                for (int j = 0; j < 3; j++)
                {
                    Assert.IsTrue(entries.Contains(not_expired[i * 3 + j]), "step 0: not_expired " + (i * 3 + j));
                    Assert.IsTrue(entries.Contains(to_expire[i * 3 + j]), "step 0: to_expire " + (i * 3 + j));
                }
            }

            for (int i = 0; i < 4; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    int pos = i * 3 + j;
                    if (pos % 2 == 0)
                    {
                        Entry ent = not_expired[pos];
                        tsd.UpdateEntry(ent.Key, ent.Value, now.AddSeconds(160));
                    }
                }
            }

            Entry entry = to_expire[11];

            tsd.UpdateEntry(entry.Key, entry.Value, now.AddSeconds(160));

            for (int i = 0; i < 4; i++)
            {
                LinkedList <Entry> entries = tsd.GetEntries(not_expired[i * 3].Key);
                for (int j = 0; j < 3; j++)
                {
                    Assert.IsTrue(entries.Contains(not_expired[i * 3 + j]), "step 1: not_expired " + (i * 3 + j));
                    Assert.IsTrue(entries.Contains(to_expire[i * 3 + j]), "step 1: to_expire " + (i * 3 + j));
                }
            }

            while (DateTime.UtcNow < expire.AddSeconds(1))
            {
                for (int i = 0; i < 50000000; i++)
                {
                    int k = i % 5;
                    k += 6;
                }
            }
            for (int i = 0; i < 3; i++)
            {
                LinkedList <Entry> entries = tsd.GetEntries(not_expired[i * 3].Key);
                for (int j = 0; j < 3; j++)
                {
                    Assert.IsTrue(entries.Contains(not_expired[i * 3 + j]), "step 2: not_expired " + (i * 3 + j));
                    Assert.IsFalse(entries.Contains(to_expire[i * 3 + j]), "step 2: to_expire " + (i * 3 + j));
                }
            }
            Assert.AreEqual(13, tsd.Count, "Entries we didn't check are removed by CheckEntries.");
        }
Exemple #39
0
 public CryptoApiRandomGenerator()
 {
     rndProv = new RNGCryptoServiceProvider();
 }
 public CryptoRandomNumberGen()
 {
     csp = new RNGCryptoServiceProvider();
 }
        public void CertificateAndMasterKeyExecTest()
        {
            string script;
            IDictionary <string, string> customSettings = new ConcurrentDictionary <string, string>();
            var keyPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            var buffer  = new byte[256 / 8];

            using (var cryptoRandom = new RNGCryptoServiceProvider())
            {
                cryptoRandom.GetBytes(buffer);
            }
            File.WriteAllBytes(keyPath, buffer);
            var certPath = GenerateAndSaveSelfSignedCertificate();

            if (PlatformDetails.RunningOnPosix)
            {
                var scriptPath = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Guid.NewGuid().ToString(), ".sh"));
                var keyArgs    = CommandLineArgumentEscaper.EscapeAndConcatenate(new List <string> {
                    scriptPath, keyPath
                });
                var certArgs = CommandLineArgumentEscaper.EscapeAndConcatenate(new List <string> {
                    scriptPath, certPath
                });

                customSettings[RavenConfiguration.GetKey(x => x.Security.MasterKeyExec)]            = "bash";
                customSettings[RavenConfiguration.GetKey(x => x.Security.MasterKeyExecArguments)]   = $"{keyArgs}";
                customSettings[RavenConfiguration.GetKey(x => x.Security.CertificateExec)]          = "bash";
                customSettings[RavenConfiguration.GetKey(x => x.Security.CertificateExecArguments)] = $"{certArgs}";
                customSettings[RavenConfiguration.GetKey(x => x.Core.ServerUrls)] = "https://" + Environment.MachineName + ":0";

                script = "#!/bin/bash\ncat \"$1\"";
                File.WriteAllText(scriptPath, script);
                Process.Start("chmod", $"700 {scriptPath}");
            }
            else
            {
                var scriptPath = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Guid.NewGuid().ToString(), ".ps1"));
                var keyArgs    = CommandLineArgumentEscaper.EscapeAndConcatenate(new List <string> {
                    "-NoProfile", scriptPath, keyPath
                });
                var certArgs = CommandLineArgumentEscaper.EscapeAndConcatenate(new List <string> {
                    "-NoProfile", scriptPath, certPath
                });

                customSettings[RavenConfiguration.GetKey(x => x.Security.MasterKeyExec)]            = "powershell";
                customSettings[RavenConfiguration.GetKey(x => x.Security.MasterKeyExecArguments)]   = $"{keyArgs}";
                customSettings[RavenConfiguration.GetKey(x => x.Security.CertificateExec)]          = "powershell";
                customSettings[RavenConfiguration.GetKey(x => x.Security.CertificateExecArguments)] = $"{certArgs}";
                customSettings[RavenConfiguration.GetKey(x => x.Core.ServerUrls)] = "https://" + Environment.MachineName + ":0";
                script = @"param([string]$userArg)
try {
    $bytes = Get-Content -path $userArg -encoding Byte
    $stdout = [System.Console]::OpenStandardOutput()
    $stdout.Write($bytes, 0, $bytes.Length)
}
catch {
    Write-Error $_.Exception
    exit 1
}
exit 0";
                File.WriteAllText(scriptPath, script);
            }

            UseNewLocalServer(customSettings: customSettings, runInMemory: false);
            // The master key loading is lazy, let's put a database secret key to invoke it.
            var dbName      = GetDatabaseName();
            var databaseKey = new byte[32];

            using (var rand = RandomNumberGenerator.Create())
            {
                rand.GetBytes(databaseKey);
            }
            var base64Key = Convert.ToBase64String(databaseKey);

            // sometimes when using `dotnet xunit` we get platform not supported from ProtectedData
            try
            {
                ProtectedData.Protect(Encoding.UTF8.GetBytes("Is supported?"), null, DataProtectionScope.CurrentUser);
            }
            catch (PlatformNotSupportedException)
            {
                return;
            }
            Server.ServerStore.PutSecretKey(base64Key, dbName, true);
            X509Certificate2 serverCertificate;

            try
            {
                serverCertificate = new X509Certificate2(certPath, (string)null, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
            }
            catch (CryptographicException e)
            {
                throw new CryptographicException($"Failed to load the test certificate from {certPath}.", e);
            }
            using (var store = GetDocumentStore(new Options
            {
                AdminCertificate = serverCertificate,
                ClientCertificate = serverCertificate,
                ModifyDatabaseName = s => dbName,
                ModifyDatabaseRecord = record => record.Encrypted = true,
                Path = NewDataPath()
            }))
            {
            }
            var secrets         = Server.ServerStore.Secrets;
            var serverMasterKey = (Lazy <byte[]>) typeof(SecretProtection).GetField("_serverMasterKey", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(secrets);

            Assert.True(serverMasterKey.Value.SequenceEqual(buffer));
            Assert.True(Server.Certificate.Certificate.Equals(serverCertificate));
        }
Exemple #42
0
 public SecureRandom()
 {
     _csp = new RNGCryptoServiceProvider("TANYA");
 }
Exemple #43
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.
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

        rng.GetBytes(randomBytes);

        // Convert 4 bytes into a 32-bit integer value.
        int seed = (randomBytes[0] & 0x7f) << 24 |
                   randomBytes[1] << 16 |
                   randomBytes[2] << 8 |
                   randomBytes[3];

        // 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));
    }
Exemple #44
0
 public RngWrapper(CspParameters cspParams)
 {
     this._wrapped = new RNGCryptoServiceProvider(cspParams);
 }
Exemple #45
0
 /// <summary>
 /// Next Bytes given initial buffer
 /// </summary>
 /// <param name="buf">byte array buffer</param>
 public virtual void NextBytes(byte[] buf)
 {
     using (var rng = new RNGCryptoServiceProvider()) rng.GetNonZeroBytes(buf);
 }
        protected void btn_changePassword_Click(object sender, EventArgs e)
        {
            string old_pwd = HttpUtility.HtmlEncode(tb_old_password.Text.ToString().Trim());

            string new_pwd = HttpUtility.HtmlEncode(tb_password.Text.ToString().Trim());

            System.Diagnostics.Debug.WriteLine("old password: "******"new password: "******"LoggedIn"].ToString();
                SHA512Managed hashing = new SHA512Managed();
                string        dbHash  = getDBHash(email);
                string        dbSalt  = getDBSalt(email);


                try
                {
                    if (dbSalt != null && dbSalt.Length > 0 && dbHash != null && dbHash.Length > 0)
                    {
                        string pwdWithSalt  = old_pwd + dbSalt;
                        byte[] hashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));
                        string userHash     = Convert.ToBase64String(hashWithSalt);

                        if (userHash.Equals(dbHash))
                        {
                            System.Diagnostics.Debug.WriteLine("Old Password Matches Password in Database");

                            //string new_pwd = HttpUtility.HtmlEncode(tb_password.Text.ToString().Trim());



                            //Server Side Check making sure password does indeed meet all the complexity requirements stated in "Password Complexity Requirements"
                            if ((new_pwd.Length >= 12) && (Regex.IsMatch(new_pwd, "[a-z]")) && (Regex.IsMatch(new_pwd, "[A-Z]")) && (Regex.IsMatch(new_pwd, "[0-9]")) && (Regex.IsMatch(new_pwd, "[^a-zA-Z0-9]")))
                            {
                                //lbl_testing.Text = "success";
                                System.Diagnostics.Debug.WriteLine("success");


                                //SqlConnection connection = new SqlConnection(SITCONNECTDBConnectionString);
                                //string sql = "update Account SET PasswordHash=@PASSWORDHASH, PasswordSalt=@PASSWORDSALT, IV=@IV, Key=@KEY WHERE Email=@EMAIL";
                                //SqlCommand cmd = new SqlCommand(sql, connection);
                                //cmd.Parameters.AddWithValue("@EMAIL", email);


                                //Generate random "salt"
                                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                                byte[] saltByte = new byte[8];

                                //Fills array of bytes with a cryptographically strong sequence of random values.
                                rng.GetBytes(saltByte);
                                salt = Convert.ToBase64String(saltByte);

                                SHA512Managed hashing2 = new SHA512Managed();

                                string pwdWithSalt2  = new_pwd + salt;
                                byte[] plainHash     = hashing2.ComputeHash(Encoding.UTF8.GetBytes(new_pwd));
                                byte[] hashWithSalt2 = hashing2.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt2));

                                finalHash = Convert.ToBase64String(hashWithSalt2);


                                RijndaelManaged cipher = new RijndaelManaged();
                                cipher.GenerateKey();
                                Key = cipher.Key;
                                IV  = cipher.IV;

                                //SqlConnection connection = new SqlConnection(SITCONNECTDBConnectionString);
                                //string sql = "update Account SET PasswordHash=@PASSWORDHASH, PasswordSalt=@PASSWORDSALT, IV=@IV, Key=@KEY WHERE Email=@EMAIL";
                                //SqlCommand cmd = new SqlCommand(sql, connection);
                                //cmd.Parameters.AddWithValue("@EMAIL", email);

                                updatePassword();


                                Response.Redirect("Default.aspx", false);


                                //MyDBServiceReference.Service1Client client = new MyDBServiceReference.Service1Client();
                                //int result = client.CreateEmployee(tbNric.Text, tbName.Text, dob, ddlDept.Text, wage);
                            }
                            else
                            {
                                //lbl_testing.Text = "your new password does not meet password requirements";

                                System.Diagnostics.Debug.WriteLine("your new password does not meet password requirements");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.ToString());
                }
                finally { }



                System.Diagnostics.Debug.WriteLine("Password changed successfully");


                Response.Redirect("Default.aspx");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("New Password cannot be the same as Old Password!");
                Page.Response.Redirect(Page.Request.Url.ToString(), true);
            }
        }
        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            string confirmpassword = tb_ConfirmPass.Text.ToString().Trim();
            string email           = (string)Session["LoggedIn"];
            string newpass         = HttpUtility.HtmlEncode(tb_NewPassword.Text.ToString().Trim());

            SHA512Managed hashing = new SHA512Managed();
            string        dbHash  = getDBHash(email);
            string        dbSalt  = getDBSalt(email);
            string        dbHash2 = getDBHash2(email);
            string        dbSalt2 = getDBSalt2(email);
            string        dbHash3 = getDBHash3(email);
            string        dbSalt3 = getDBSalt3(email);

            string pwdSalt = newpass + dbSalt;

            byte[] hashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdSalt));
            string userHash     = Convert.ToBase64String(hashWithSalt);

            string pwdSalt2 = newpass + dbSalt2;

            byte[] hashWithSalt2 = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdSalt2));
            string userHash2     = Convert.ToBase64String(hashWithSalt2);

            string pwdSalt3 = newpass + dbSalt3;

            byte[] hashWithSalt3 = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdSalt3));
            string userHash3     = Convert.ToBase64String(hashWithSalt3);

            try
            {
                if (dbSalt != null && dbSalt.Length > 0 && dbHash != null && dbHash.Length > 0)
                {
                    //checking if passwordhash2 and passwordsalt2 is empty | Add new pass into passwordhash2 and passwordsalt2
                    if (dbSalt2 == null && dbHash2 == null)
                    {
                        //************* Start of making new password into database **************

                        //Continue with adding the new password
                        bool validinput = ValidateInput();

                        if (validinput)
                        {
                            if (dbSalt3 == null && dbHash3 == null)
                            {
                                if (confirmpassword == newpass)
                                {
                                    //Generating random "salt"
                                    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                                    byte[] saltByte = new byte[8];

                                    //Fills array of bytes with a cryptographically strong sequence of random values.
                                    rng.GetBytes(saltByte);
                                    salt = Convert.ToBase64String(saltByte);

                                    SHA512Managed newhashing = new SHA512Managed();

                                    string pwdWithSalt = newpass + salt;
                                    byte[] plainHash   = newhashing.ComputeHash(Encoding.UTF8.GetBytes(newpass));
                                    byte[] hashAndSalt = newhashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));

                                    finalHash = Convert.ToBase64String(hashAndSalt);

                                    RijndaelManaged cipher = new RijndaelManaged();
                                    cipher.GenerateKey();
                                    Key = cipher.Key;
                                    IV  = cipher.IV;
                                    updatePassAge(email);

                                    int updateresult = updatePassword2(email);
                                    if (updateresult == 1)
                                    {
                                        Session.Clear();
                                        Session.Abandon();
                                        Session.RemoveAll();

                                        if (Request.Cookies["ASP.NET_SessionId"] != null)
                                        {
                                            Response.Cookies["ASP.NET_SessionId"].Value   = string.Empty;
                                            Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(-20);
                                        }

                                        if (Request.Cookies["AuthToken"] != null)
                                        {
                                            Response.Cookies["Authtoken"].Value   = string.Empty;
                                            Response.Cookies["AuthToken"].Expires = DateTime.Now.AddMonths(-20);
                                        }
                                        ClientScript.RegisterStartupScript(this.GetType(), "randomtext", "alertSuccess()", true);
                                    }
                                }
                                else
                                {
                                    lb_ConfirmPassError.Visible   = true;
                                    lb_ConfirmPassError.Text      = "Does not match with New Password!";
                                    lb_ConfirmPassError.ForeColor = Color.Red;
                                }
                            }
                            else
                            {
                                if (dbHash != userHash && dbHash3 != userHash3)
                                {
                                    if (confirmpassword == newpass)
                                    {
                                        //Generating random "salt"
                                        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                                        byte[] saltByte = new byte[8];

                                        //Fills array of bytes with a cryptographically strong sequence of random values.
                                        rng.GetBytes(saltByte);
                                        salt = Convert.ToBase64String(saltByte);

                                        SHA512Managed newhashing = new SHA512Managed();

                                        string pwdWithSalt = newpass + salt;
                                        byte[] plainHash   = newhashing.ComputeHash(Encoding.UTF8.GetBytes(newpass));
                                        byte[] hashAndSalt = newhashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));

                                        finalHash = Convert.ToBase64String(hashAndSalt);

                                        RijndaelManaged cipher = new RijndaelManaged();
                                        cipher.GenerateKey();
                                        Key = cipher.Key;
                                        IV  = cipher.IV;
                                        updatePassAge(email);

                                        int updateresult = updatePassword2(email);
                                        if (updateresult == 1)
                                        {
                                            Session.Clear();
                                            Session.Abandon();
                                            Session.RemoveAll();

                                            if (Request.Cookies["ASP.NET_SessionId"] != null)
                                            {
                                                Response.Cookies["ASP.NET_SessionId"].Value   = string.Empty;
                                                Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(-20);
                                            }

                                            if (Request.Cookies["AuthToken"] != null)
                                            {
                                                Response.Cookies["Authtoken"].Value   = string.Empty;
                                                Response.Cookies["AuthToken"].Expires = DateTime.Now.AddMonths(-20);
                                            }
                                            ClientScript.RegisterStartupScript(this.GetType(), "randomtext", "alertSuccess()", true);
                                        }
                                    }
                                    else
                                    {
                                        lb_ConfirmPassError.Visible   = true;
                                        lb_ConfirmPassError.Text      = "Does not match with New Password!";
                                        lb_ConfirmPassError.ForeColor = Color.Red;
                                    }
                                }
                                else
                                {
                                    lb_NewPassError.Visible   = true;
                                    lb_NewPassError.Text      = "Your password cannot be the same as your last 2 ones!";
                                    lb_NewPassError.ForeColor = Color.Red;
                                }
                            }
                        }
                    }
                    else
                    {
                        if (dbSalt3 == null && dbHash3 == null)
                        {
                            //************* Start of making new password into database **************

                            //Continue with adding the new password
                            bool validinput = ValidateInput();

                            if (validinput)
                            {
                                if (userHash2 != dbHash2 && userHash != dbHash)
                                {
                                    if (confirmpassword == newpass)
                                    {
                                        //Generating random "salt"
                                        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                                        byte[] saltByte = new byte[8];

                                        //Fills array of bytes with a cryptographically strong sequence of random values.
                                        rng.GetBytes(saltByte);
                                        salt = Convert.ToBase64String(saltByte);

                                        SHA512Managed newhashing = new SHA512Managed();

                                        string pwdWithSalt = newpass + salt;
                                        byte[] plainHash   = newhashing.ComputeHash(Encoding.UTF8.GetBytes(newpass));
                                        byte[] hashAndSalt = newhashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));

                                        finalHash = Convert.ToBase64String(hashAndSalt);

                                        RijndaelManaged cipher = new RijndaelManaged();
                                        cipher.GenerateKey();
                                        Key = cipher.Key;
                                        IV  = cipher.IV;

                                        updatePassAge(email);
                                        int updateresult = updatePassword3(email);
                                        if (updateresult == 1)
                                        {
                                            Session.Clear();
                                            Session.Abandon();
                                            Session.RemoveAll();


                                            if (Request.Cookies["ASP.NET_SessionId"] != null)
                                            {
                                                Response.Cookies["ASP.NET_SessionId"].Value   = string.Empty;
                                                Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(-20);
                                            }

                                            if (Request.Cookies["AuthToken"] != null)
                                            {
                                                Response.Cookies["Authtoken"].Value   = string.Empty;
                                                Response.Cookies["AuthToken"].Expires = DateTime.Now.AddMonths(-20);
                                            }
                                            ClientScript.RegisterStartupScript(this.GetType(), "randomtext", "alertSuccess()", true);
                                        }
                                    }
                                    else
                                    {
                                        lb_ConfirmPassError.Visible   = true;
                                        lb_ConfirmPassError.Text      = "Does not match with New Password!";
                                        lb_ConfirmPassError.ForeColor = Color.Red;
                                    }
                                }
                                else
                                {
                                    lb_NewPassError.Visible   = true;
                                    lb_NewPassError.Text      = "Your password cannot be the same as your old one!";
                                    lb_NewPassError.ForeColor = Color.Red;
                                }
                            }
                        }
                        else
                        {
                            //************* Start of making new password into database **************


                            //Continue with adding the new password
                            bool validinput = ValidateInput();

                            if (validinput)
                            {
                                if (userHash2 != dbHash2 && userHash3 != dbHash3)
                                {
                                    if (confirmpassword == newpass)
                                    {
                                        //Generating random "salt"
                                        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                                        byte[] saltByte = new byte[8];

                                        //Fills array of bytes with a cryptographically strong sequence of random values.
                                        rng.GetBytes(saltByte);
                                        salt = Convert.ToBase64String(saltByte);

                                        SHA512Managed newhashing = new SHA512Managed();

                                        string pwdWithSalt = newpass + salt;
                                        byte[] plainHash   = newhashing.ComputeHash(Encoding.UTF8.GetBytes(newpass));
                                        byte[] hashAndSalt = newhashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));

                                        finalHash = Convert.ToBase64String(hashAndSalt);

                                        RijndaelManaged cipher = new RijndaelManaged();
                                        cipher.GenerateKey();
                                        Key = cipher.Key;
                                        IV  = cipher.IV;

                                        updatePassAge(email);

                                        int updateresult = updatePassword(email);
                                        if (updateresult == 1)
                                        {
                                            Session.Clear();
                                            Session.Abandon();
                                            Session.RemoveAll();
                                            makePassNull(email);

                                            if (Request.Cookies["ASP.NET_SessionId"] != null)
                                            {
                                                Response.Cookies["ASP.NET_SessionId"].Value   = string.Empty;
                                                Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(-20);
                                            }

                                            if (Request.Cookies["AuthToken"] != null)
                                            {
                                                Response.Cookies["Authtoken"].Value   = string.Empty;
                                                Response.Cookies["AuthToken"].Expires = DateTime.Now.AddMonths(-20);
                                            }
                                            ClientScript.RegisterStartupScript(this.GetType(), "randomtext", "alertSuccess()", true);
                                        }
                                    }
                                    else
                                    {
                                        lb_ConfirmPassError.Visible   = true;
                                        lb_ConfirmPassError.Text      = "Does not match with New Password!";
                                        lb_ConfirmPassError.ForeColor = Color.Red;
                                    }
                                }
                                else
                                {
                                    lb_NewPassError.Visible   = true;
                                    lb_NewPassError.Text      = "Your password cannot be the same as your old one!";
                                    lb_NewPassError.ForeColor = Color.Red;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new HttpException(400, ex.ToString());
            }
            finally { }
        }
        private byte[] Decrypt(byte[] buffer, Encryption encryption, byte[] iv = null, byte[] salt = null, string password = null)
        {
            if (buffer is null)
            {
                throw new ArgumentNullException(nameof(buffer));
            }

            if (encryption == Encryption.Password)
            {
                if (iv is null)
                {
                    throw new ArgumentNullException(nameof(iv));
                }

                if (salt is null)
                {
                    throw new ArgumentNullException(nameof(salt));
                }

                if (string.IsNullOrEmpty(password))
                {
                    PasswordRequiredEventArgs e = new PasswordRequiredEventArgs();
                    PasswordRequired?.Invoke(this, e);

                    if (string.IsNullOrEmpty(e.Password))
                    {
                        throw new ArgumentException("Password cannot be empty or null.", nameof(password));
                    }
                    else
                    {
                        password = e.Password;
                    }
                }
            }

            byte[] plainText = new byte[buffer.Length];
            buffer.CopyTo(plainText, 0);

            if (encryption == Encryption.Password)
            {
                using var random = RNGCryptoServiceProvider.Create();

                using Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(password, salt, KeyDerivationIterations, HashAlgorithmName.SHA512);

                Aes aes;

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    aes = new AesCng();
                }
                else
                {
                    aes = new AesManaged();
                }
                aes.Key = deriveBytes.GetBytes(aes.KeySize / 8);
                aes.IV  = iv;

                using var decryptor = aes.CreateDecryptor();
                plainText           = decryptor.TransformFinalBlock(plainText, 0, plainText.Length);

                aes.Dispose();
            }
            else if (encryption == Encryption.LocalMachine)
            {
                plainText = ProtectedData.Unprotect(plainText, null, DataProtectionScope.LocalMachine);
            }
            else if (encryption == Encryption.CurrentUser)
            {
                plainText = ProtectedData.Unprotect(plainText, null, DataProtectionScope.CurrentUser);
            }

            return(plainText);
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value is null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            MessageClientIdentity clientIdent = (MessageClientIdentity)value;

            JObject jObject = new JObject();

            jObject.Add(nameof(MessageClientIdentity.SystemName), clientIdent.SystemName);
            jObject.Add(nameof(MessageClientIdentity.Name), clientIdent.Name);

            ECParameters parms = clientIdent.ECDiffieHellman.ExportParameters(_savePrivateKey);

            if (!parms.Curve.IsNamed)
            {
                throw new NotImplementedException();
            }

            jObject.Add("CurveOid", parms.Curve.Oid.Value);

            if (parms.D != null && _savePrivateKey)
            {
                byte[] privateKey = parms.D;

                if (_encryptionType == Encryption.Password)
                {
                    using var random = RNGCryptoServiceProvider.Create();
                    byte[] salt = new byte[SaltSize];
                    random.GetBytes(salt);

                    using Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(_password, salt, KeyDerivationIterations, HashAlgorithmName.SHA512);
                    Aes aes;
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        aes = new AesCng();
                    }
                    else
                    {
                        aes = new AesManaged();
                    }
                    aes.Key = deriveBytes.GetBytes(aes.KeySize / 8);

                    jObject.Add("Salt", salt);
                    jObject.Add("IV", aes.IV);

                    using var encryptor = aes.CreateEncryptor();
                    privateKey          = encryptor.TransformFinalBlock(privateKey, 0, privateKey.Length);

                    aes.Dispose();
                }
                else if (_encryptionType == Encryption.LocalMachine)
                {
                    privateKey = ProtectedData.Protect(privateKey, null, DataProtectionScope.LocalMachine);
                }
                else if (_encryptionType == Encryption.CurrentUser)
                {
                    privateKey = ProtectedData.Protect(privateKey, null, DataProtectionScope.CurrentUser);
                }

                jObject.Add("Encryption", _encryptionType.ToString());

                jObject.Add("D", privateKey);
            }

            jObject.Add("Q.X", parms.Q.X);
            jObject.Add("Q.Y", parms.Q.Y);

            jObject.Add("Hash", clientIdent.IdentityHash);
            jObject.WriteTo(writer);
        }
Exemple #50
0
 /// <summary>
 /// Constructor for byte key
 /// </summary>
 /// <param name="cipherKey">Cipher key as a byte array</param>
 public CryptoBlowFish(byte[] cipherKey)
 {
     randomSource = new RNGCryptoServiceProvider();
     SetupKey(cipherKey);
 }
Exemple #51
0
 public RngWrapper(string str)
 {
     this._wrapped = new RNGCryptoServiceProvider(str);
 }
Exemple #52
0
 /// <summary>
 /// Constructor for hex key
 /// </summary>
 /// <param name="hexKey">Cipher key as a hex string</param>
 public CryptoBlowFish(string hexKey)
 {
     randomSource = new RNGCryptoServiceProvider();
     SetupKey(HexToByte(hexKey));
 }
Exemple #53
0
            /// <summary>
            /// Generates a hash for the given plain text value and returns a
            /// base64-encoded result. Before the hash is computed, a random salt
            /// is generated and appended to the plain text. This salt is stored at
            /// the end of the hash value, so it can be used later for hash
            /// verification.
            /// </summary>
            /// <param name="plainText">
            /// Plaintext value to be hashed. The function does not check whether
            /// this parameter is null.
            /// </param>
            /// <param name="hashAlgorithm">
            /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1",
            /// "SHA256", "SHA384", and "SHA512" (if any other value is specified
            /// MD5 hashing algorithm will be used). This value is case-insensitive.
            /// </param>
            /// <param name="saltBytes">
            /// Salt bytes. This parameter can be null, in which case a random salt
            /// value will be generated.
            /// </param>
            /// <returns>
            /// Hash value formatted as a base64-encoded string.
            /// </returns>
            public static string ComputeHash(string plainText,
                                             string hashAlgorithm,
                                             byte[] saltBytes)
            {
                // If salt is not specified, generate it on the fly.
                if (saltBytes == null)
                {
                    // Define min and max salt sizes.
                    int minSaltSize = 4;
                    int maxSaltSize = 8;

                    // Generate a random number for the size of the salt.
                    Random random   = new Random();
                    int    saltSize = random.Next(minSaltSize, maxSaltSize);

                    // Allocate a byte array, which will hold the salt.
                    saltBytes = new byte[saltSize];

                    // Initialize a random number generator.
                    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

                    // Fill the salt with cryptographically strong byte values.
                    rng.GetNonZeroBytes(saltBytes);
                }

                // Convert plain text into a byte array.
                byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

                // Allocate array, which will hold plain text and salt.
                byte[] plainTextWithSaltBytes =
                    new byte[plainTextBytes.Length + saltBytes.Length];

                // Copy plain text bytes into resulting array.
                for (int i = 0; i < plainTextBytes.Length; i++)
                {
                    plainTextWithSaltBytes[i] = plainTextBytes[i];
                }

                // Append salt bytes to the resulting array.
                for (int i = 0; i < saltBytes.Length; i++)
                {
                    plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];
                }

                // Because we support multiple hashing algorithms, we must define
                // hash object as a common (abstract) base class. We will specify the
                // actual hashing algorithm class later during object creation.
                HashAlgorithm hash;

                // Make sure hashing algorithm name is specified.
                if (hashAlgorithm == null)
                {
                    hashAlgorithm = "";
                }

                // Initialize appropriate hashing algorithm class.
                switch (hashAlgorithm.ToUpper())
                {
                case "SHA1":
                    hash = new SHA1Managed();
                    break;

                case "SHA256":
                    hash = new SHA256Managed();
                    break;

                case "SHA384":
                    hash = new SHA384Managed();
                    break;

                case "SHA512":
                    hash = new SHA512Managed();
                    break;

                default:
                    hash = new MD5CryptoServiceProvider();
                    break;
                }

                // Compute hash value of our plain text with appended salt.
                byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

                // Create array which will hold hash and original salt bytes.
                byte[] hashWithSaltBytes = new byte[hashBytes.Length +
                                                    saltBytes.Length];

                // Copy hash bytes into resulting array.
                for (int i = 0; i < hashBytes.Length; i++)
                {
                    hashWithSaltBytes[i] = hashBytes[i];
                }

                // Append salt bytes to the result.
                for (int i = 0; i < saltBytes.Length; i++)
                {
                    hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];
                }

                // Convert result into a base64-encoded string.
                string hashValue = Convert.ToBase64String(hashWithSaltBytes);

                // Return the result.
                return(hashValue);
            }
Exemple #54
0
        public ActionResult Create(groupsModel gModel, HttpPostedFileBase file)
        {
            var user    = Session["User"] as Users;
            var group   = new Groups();
            var manager = new Manager();

            if (!ModelState.IsValid)
            {
                return(View("Create"));
            }
            group.groupName = gModel.groupName;

            char[] chars =
                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
            byte[] data = new byte[8];
            using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
            {
                crypto.GetBytes(data);
            }
            StringBuilder code = new StringBuilder(8);

            foreach (byte b in data)
            {
                code.Append(chars[b % (chars.Length)]);
            }
            string cod  = code.ToString();
            var    test = db.Groups.FirstOrDefault(g => g.groupCode == cod);

            if (test == null)
            {
                group.groupCode = code.ToString();
            }
            else
            {
                TempData["msg"] = "<script>alert('İşlem sırasında beklenmedik bir hata oluştu.')</script>";
                return(RedirectToAction("Index", "Home"));
            }

            if (file != null && file.ContentLength > 0)
            {
                string fileName = Path.GetFileName(file.FileName);
                string imgPath  = Path.Combine(Server.MapPath("~/Group_Images/"), fileName);
                file.SaveAs(imgPath);
                group.groupImageUrl = "/Group_Images/" + file.FileName;
            }
            else if (file == null)
            {
                group.groupImageUrl = "/Group_Images/default.png";
            }
            var control = db.Manager.FirstOrDefault(c => c.userFk == user.userId);

            if (control == null)
            {
                manager.managerNameSurname = user.userNameSurname;
                manager.userFk             = user.userId;
                db.Manager.Add(manager);
                db.SaveChanges();
                group.managerFk = manager.managerId;
            }
            else
            {
                group.managerFk = control.managerId;
            }
            db.Groups.Add(group);
            db.SaveChanges();
            db.spAddUserGroups(user.userId, group.groupId);
            db.SaveChanges();
            return(RedirectToAction("Index", "Home"));
        }
Exemple #55
0
        public void Test2()
        {
            TableServerData          tsd = new TableServerData("0");
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

            MemBlock[] addresses = new MemBlock[100];
            byte[]     value     = new byte[20];
            rng.GetBytes(value);
            DateTime now       = DateTime.UtcNow;
            DateTime lease_end = now.AddMinutes(1);

            for (int i = 0; i < addresses.Length; i++)
            {
                addresses[i] = (new AHAddress(rng)).ToMemBlock();
                tsd.AddEntry(new Entry(addresses[i], value, now, lease_end));
            }

            AHAddress             start   = new AHAddress(rng);
            AHAddress             end     = new AHAddress(rng);
            LinkedList <MemBlock> keys_se = tsd.GetKeysBetween(start, end);
            LinkedList <MemBlock> keys_es = tsd.GetKeysBetween(end, start);
            String output = " - " + start + ":" + end;

            if (start.IsLeftOf(end))
            {
                foreach (MemBlock address in addresses)
                {
                    AHAddress addr = new AHAddress(address);
                    if (addr.IsLeftOf(end) && addr.IsRightOf(start))
                    {
                        Assert.IsTrue(keys_se.Contains(address), addr + " in lse" + output);
                        Assert.IsTrue(keys_es.Contains(address), addr + " in les" + output);
                    }
                    else
                    {
                        Assert.IsFalse(keys_se.Contains(address), addr + " out lse" + output);
                        Assert.IsFalse(keys_es.Contains(address), addr + " out les" + output);
                    }
                }
            }
            else
            {
                foreach (MemBlock address in addresses)
                {
                    AHAddress addr = new AHAddress(address);
                    if (addr.IsLeftOf(start) && addr.IsRightOf(end))
                    {
                        Assert.IsTrue(keys_se.Contains(address), addr + " in rse" + output);
                        Assert.IsTrue(keys_es.Contains(address), addr + " in res" + output);
                    }
                    else
                    {
                        Assert.IsFalse(keys_se.Contains(address), addr + " out rse" + output);
                        Assert.IsFalse(keys_es.Contains(address), addr + " out res" + output);
                    }
                }
            }

            LinkedList <MemBlock> keys = tsd.GetKeys();

            foreach (MemBlock addr in addresses)
            {
                Assert.IsTrue(keys.Contains(addr), "keys does not contain: " + (new AHAddress(addr)));
            }
        }
 public static byte[] GetRandomBytes(int length)
 {
     byte[] ba = new byte[length];
     RNGCryptoServiceProvider.Create().GetBytes(ba);
     return(ba);
 }
Exemple #57
0
 public static bool nativeGenerateSeed(byte[] result)
 {
     try
     {
         RNGCryptoServiceProvider csp = new RNGCryptoServiceProvider();
         csp.GetBytes(result);
         return true;
     }
     catch (CryptographicException)
     {
         return false;
     }
 }
Exemple #58
0
 private byte[] pad_rng_seq(RNGCryptoServiceProvider rng, Random r)
 {
     byte[] b = new byte[r.Next(global::et.PadSettings.RANDOM_SEQUENCE_BOUND_LOW, global::et.PadSettings.RANDOM_SEQUENCE_BOUND_HIGH)];
     rng.GetBytes(b);
     return(b);
 }
Exemple #59
0
		public HMAC()
		{
			// Create the hash
			hash = MD5.Create();
			// Set HashSizeValue
			HashSizeValue = hash.HashSize;

			// Generate a radom key
			byte[] rgbKey = new byte[64];
			RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
			rng.GetNonZeroBytes(rgbKey);

			KeyValue = (byte[])rgbKey.Clone();

			this.Initialize();
		}
Exemple #60
0
 public void populate(RNGCryptoServiceProvider r)
 {
     salt      = new Tools.ByValData.ByValFixedByteArray16();
     salt.data = new byte[16];
     r.GetBytes(salt.data);
 }