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 #2
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 #4
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 #5
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 #6
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 #7
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;
    }
        public void Performance_tests()
        {
            // random write.
            var gen   = new RNGCryptoServiceProvider();
            var bytes = 1024;
            var data  = new byte[bytes];

            gen.GetNonZeroBytes(data);
            var stopwatch = Stopwatch.StartNew();
            var records   = 100000;

            var total = records * bytes;

            Console.WriteLine("Data is {0} records of {1} bytes == {2} bytes or {3} MB", records, bytes, total, total / 1024 / 1024);

            for (int i = 0; i < records; i++)
            {
                _stream.TryAppend(data);
            }

            var timeSpan = stopwatch.Elapsed;

            Console.WriteLine("Writing one by one in {0}", timeSpan.TotalSeconds);

            var length = new FileInfo(Path.Combine(_path, "test")).Length;

            Console.WriteLine("Total file size: {0}", length);

            int counter = 0;
            var reading = Stopwatch.StartNew();

            foreach (var tapeRecord in _stream.ReadRecords(0, int.MaxValue))
            {
                counter += tapeRecord.Data.Length;
            }
            Console.WriteLine("Reading in {0} seconds", reading.Elapsed.TotalSeconds);
            Console.WriteLine("Read {0} bytes of raw data", counter);
        }
Exemple #9
0
        public static dynamic Hash(string RawData, byte[] Salt)
        {
            int MaxSaltlength = 16;
            int MinSaltlength = 4;

            byte[] SaltBytes = null;
            if (Salt != null)
            {
                SaltBytes = Salt;
            }
            else
            {
                Random random     = new Random();
                int    Saltlength = random.Next(MinSaltlength, MaxSaltlength);
                SaltBytes = new byte[Saltlength];
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                rng.GetNonZeroBytes(SaltBytes);
                rng.Dispose();
            }
            byte[] PlainData   = ASCIIEncoding.UTF8.GetBytes(RawData);
            byte[] DataAndSalt = new byte[PlainData.Length + SaltBytes.Length];
            for (int i = 0; i < PlainData.Length; i++)
            {
                DataAndSalt[i] = PlainData[i];
            }
            for (int j = 0; j < SaltBytes.Length; j++)
            {
                DataAndSalt[PlainData.Length + j] = SaltBytes[j];
            }
            SHA256Managed sha256 = new SHA256Managed();

            byte[]  HashValue = sha256.ComputeHash(DataAndSalt);
            dynamic result    = new ExpandoObject();

            result.Hash = Convert.ToBase64String(HashValue);
            result.Salt = Convert.ToBase64String(SaltBytes);
            return(result);
        }
Exemple #10
0
        public byte[] GetPasswordWithSalt(byte[] password)
        {
            var    rng          = new RNGCryptoServiceProvider();
            Random random       = new Random();
            var    pass         = password;
            int    saltSize     = random.Next(4, 8);
            var    salt         = new byte[saltSize];
            var    passwordHash = new byte[saltSize + pass.Length];

            rng.GetNonZeroBytes(salt);
            for (int i = 0; i < pass.Length; i++)
            {
                passwordHash[i] = pass[i];
            }


            for (int i = 0; i < salt.Length; i++)
            {
                passwordHash[pass.Length + i] = salt[i];
            }

            using (SHA256 sha256Hash = SHA256.Create())
            {
                byte[] hashBytes            = sha256Hash.ComputeHash(passwordHash);
                byte[] passwordHashWithSalt = new byte[hashBytes.Length +
                                                       salt.Length];
                for (int i = 0; i < hashBytes.Length; i++)
                {
                    passwordHashWithSalt[i] = hashBytes[i];
                }

                for (int i = 0; i < salt.Length; i++)
                {
                    passwordHashWithSalt[hashBytes.Length + i] = salt[i];
                }
                return(passwordHashWithSalt);
            }
        }
        /// <summary>
        /// This method checks if the connector is still ok.
        /// We try to send a simple query text, select 1 as ConnectionTest;
        /// </summary>
        internal Boolean IsValid()
        {
            try
            {
                // Here we use a fake NpgsqlCommand, just to send the test query string.

                // Get random test value.
                Byte[] testBytes = new Byte[2];
                rng.GetNonZeroBytes(testBytes);
                String testValue = String.Format("Npgsql{0}{1}", testBytes[0], testBytes[1]);

                //Query(new NpgsqlCommand("select 1 as ConnectionTest", this));
                string compareValue = string.Empty;
                string sql          = "select '" + testValue + "'";
                // restore initial connection parameters resetted by "Discard ALL"
                if (SupportsDiscard)
                {
                    sql = this.initQueries + sql;
                }
                using (NpgsqlCommand cmd = new NpgsqlCommand(sql, this))
                {
                    compareValue = (string)cmd.ExecuteScalar();
                }

                if (compareValue != testValue)
                {
                    return(false);
                }

                this.RequireReadyForQuery = true;
            }
            catch
            {
                return(false);
            }

            return(true);
        }
Exemple #12
0
        public static string PasswordHash(string unhashed, byte[] saltBytes)
        {
            if (saltBytes == null)
            {
                int    minSalt  = 4;
                int    maxSalt  = 8;
                Random random   = new Random();
                int    saltSize = random.Next(minSalt, maxSalt);
                saltBytes = new byte[saltSize];
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                rng.GetNonZeroBytes(saltBytes);
            }
            byte[] unhashedBytes         = Encoding.UTF8.GetBytes(unhashed);
            byte[] unhashedBytesWithSalt = new byte[unhashedBytes.Length + saltBytes.Length];
            for (int i = 0; i < unhashedBytes.Length; i++)
            {
                unhashedBytesWithSalt[i] = unhashedBytes[i];
            }
            for (int i = 0; i < saltBytes.Length; i++)
            {
                unhashedBytesWithSalt[unhashedBytes.Length + i] = saltBytes[i];
            }
            HashAlgorithm hash = new SHA256Managed();

            byte[] hashBytes    = hash.ComputeHash(unhashedBytesWithSalt);
            byte[] hashWithSalt = new byte[hashBytes.Length + saltBytes.Length];
            for (int i = 0; i < hashBytes.Length; i++)
            {
                hashWithSalt[i] = hashBytes[i];
            }
            for (int i = 0; i < saltBytes.Length; i++)
            {
                hashWithSalt[hashBytes.Length + i] = saltBytes[i];
            }
            string hashValue = Convert.ToBase64String(hashWithSalt);

            return(hashValue);
        }
        /// <summary>
        /// Generate a salt key that will be stored inside first page database
        /// </summary>
        /// <returns></returns>
        public static byte[] Salt(int maxLength = 16)
        {
#if NET35
            var random = new RNGCryptoServiceProvider();

            // empty salt array
            var salt = new byte[maxLength];

            // build the random bytes
            random.GetNonZeroBytes(salt);

            // Return the string encoded salt
            return(salt);
#else
            // simple solution for NETStandard
            var rnd  = new Random();
            var salt = new byte[maxLength];

            rnd.NextBytes(salt);

            return(salt);
#endif
        }
Exemple #14
0
        public static string MakeSalt(string algoType, int rounds)
        {
            int saltChars = 16;

            if (algoType == TypeMd5)
            {
                saltChars = 8;
            }

            // Find out how many random bytes we need for the saltChars as
            // base64 has overhead of 4/3
            double base64Overhead = 4.0 / 3.0;

            int bytesNeeded = (int)((double)saltChars / base64Overhead);

            byte[] randomBytes = new byte[bytesNeeded];

            var random = new RNGCryptoServiceProvider();

            random.GetNonZeroBytes(randomBytes);

            return(string.Format("{0}rounds={1}${2}", algoType, rounds, Convert.ToBase64String(randomBytes)));
        }
Exemple #15
0
        /// <summary>
        /// Generates a sequence of <paramref name="length"/> random ASCII
        /// characters.
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        private static string GenerateKey(int length)
        {
            Debug.Assert(length > 0);
            using (var rng = new RNGCryptoServiceProvider()) {
                var bytes = new byte[1];
                var data  = new char[length];

                for (int i = 0; i < data.Length; ++i)
                {
                    rng.GetNonZeroBytes(bytes);
                    if ((bytes[0] >= 0x20) && (bytes[0] <= 0x7e))
                    {
                        data[i] = (char)bytes[0];
                    }
                    else
                    {
                        --i;
                    }
                }

                return(new string(data));
            }
        }
Exemple #16
0
        internal static string GenerateKey(int size)
        {
            if (size <= 0 || size > 512)
            {
                throw new System.ArgumentOutOfRangeException(nameof(size), "Size should be 0 < x <= 512");
            }

            char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!/()[]\\+*~#,;.-_".ToCharArray();

            byte[] data = new byte[size];
            using (var crypto = new RNGCryptoServiceProvider())
            {
                crypto.GetNonZeroBytes(data);
            }
            var result = new StringBuilder(size);

            foreach (byte b in data)
            {
                result.Append(chars[b % (chars.Length)]);
            }

            return(result.ToString());
        }
        /// <summary>
        /// Get integer between inclusive range
        /// Edge case of min == max to allow one value distributions to be 'randomised'
        /// </summary>
        /// <param name="min"></param>
        /// <param name="max"></param>
        /// <returns></returns>
        public int Next(int min, int max)
        {
            if (min > max)
            {
                throw new ArgumentOutOfRangeException(nameof(min), "min cannot be greater than max");
            }

            if (min == max)
            {
                return(min);
            }

            var bytes = new byte[sizeof(int)]; // 4 bytes

            _Random.GetNonZeroBytes(bytes);
            var val = BitConverter.ToInt32(bytes);

            // constrain our values to between our min and max
            // https://stackoverflow.com/a/3057867/86411
            var result = ((val - min) % (max - min + 1) + max - min + 1) % (max - min + 1) + min;

            return(result);
        }
        /// <summary>
        /// For more information see: http://codereview.stackexchange.com/questions/93614/salt-generation-in-c
        /// Generates a base64 random string.
        /// </summary>
        /// <param name="length">The length of the token</param>
        /// <returns></returns>
        private string GenerateSessionToken(int length)
        {
            string token = null;

            do
            {
                byte[] tokenBytes = new byte[length];

                using (var rngCryptoSerivceProvider = new RNGCryptoServiceProvider())
                {
                    rngCryptoSerivceProvider.GetNonZeroBytes(tokenBytes);
                }

                // Add the System.Web dll in reference in project.
                // Method from: https://msdn.microsoft.com/en-us/library/system.web.httpserverutility.urltokenencode.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
                token = System.Web.HttpServerUtility.UrlTokenEncode(tokenBytes);

                // Do this as long as we generate a token that already exists.
                // Event on a duplicate, it should not happen to often that a duplicate is generated at a decent length!
            } while (_repository.Get(sToken => sToken.Token == token).FirstOrDefault() != null);

            return(token);
        }
 /* Good1() changes the "if" so that both branches use the GoodSink */
 private void Good1()
 {
     if (IO.StaticReturnsTrueOrFalse())
     {
         /* FIX: use a strong PRNG */
         using (RNGCryptoServiceProvider secureRandom = new RNGCryptoServiceProvider())
         {
             byte[] randomNumber = new byte[10];
             secureRandom.GetNonZeroBytes(randomNumber);
             IO.WriteLine("" + Encoding.Default.GetString(randomNumber));
         }
     }
     else
     {
         /* FIX: use a strong PRNG */
         using (RNGCryptoServiceProvider secureRandom = new RNGCryptoServiceProvider())
         {
             byte[] randomNumber = new byte[10];
             secureRandom.GetNonZeroBytes(randomNumber);
             IO.WriteLine("" + Encoding.Default.GetString(randomNumber));
         }
     }
 }
        private byte[] ComputeSalt(string password)
        {
            byte[] passwordSalt;

            // Define min and max salt sizes.
            int minSaltSize = 32;
            int maxSaltSize = 64;

            // 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.
            passwordSalt = new byte[saltSize];

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

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

            return(passwordSalt);
        }
Exemple #21
0
        public void UsingRNGCryptoServiceProviderIsCompliant()
        {
            var initializationVectorConstant   = new byte[16];
            var initializationVectorRng        = new byte[16];
            var initializationVectorRngNonZero = new byte[16];

            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(initializationVectorRng);
                rng.GetNonZeroBytes(initializationVectorRngNonZero);
            }

            using var sa = SymmetricAlgorithm.Create("AES");

            sa.GenerateKey();
            var fromRng        = sa.CreateEncryptor(sa.Key, initializationVectorRng);
            var fromRngNonZero = sa.CreateEncryptor(sa.Key, initializationVectorRngNonZero);

            sa.GenerateIV();
            var fromGenerateIV = sa.CreateEncryptor(sa.Key, sa.IV);

            sa.CreateDecryptor(sa.Key, initializationVectorConstant); // Compliant, not relevant for decrypting
        }
Exemple #22
0
        /// <summary>
        /// Generate a random URL friendly string (youtube like)
        /// </summary>
        /// <param name="maxSize">result length</param>
        /// <returns>a random string</returns>
        public static string GetUniqueKey(int maxSize)
        {
            if (maxSize < 1)
            {
                throw new Exception("Length must be atleast 1");
            }

            var data = new byte[maxSize];

            using (var crypto = new RNGCryptoServiceProvider())
            {
                crypto.GetNonZeroBytes(data);
            }

            var result = new StringBuilder(maxSize);

            foreach (byte b in data)
            {
                result.Append(_chars[b % _chars.Length]);
            }

            return(result.ToString());
        }
        static public string CreateSaltedPasswordHash(string password)
        {
            // Generate random salt string
            RNGCryptoServiceProvider csp = new RNGCryptoServiceProvider();

            byte[] saltBytes = new byte[16];
            csp.GetNonZeroBytes(saltBytes);
            string saltString = Convert.ToBase64String(saltBytes);

            // Append the salt string to the password
            string saltedPassword = password + saltString;

            // Hash the salted password
            string hash = FormsAuthentication.HashPasswordForStoringInConfigFile
                              (saltedPassword, "SHA1");

            // Append the salt to the hash
            string saltedHash = hash + saltString;



            return(saltedHash);
        }
Exemple #24
0
        /// <summary>
        /// 产生一个指定长度的随机密码
        /// </summary>
        /// <param name="len">
        ///	密码长度
        /// </param>
        /// <returns>string:密码</returns>
        public static string GeneratePassword(int len)
        {
            byte[] password = new byte[len];
            RNGCryptoServiceProvider rng = RNGCryptoServiceProvider.Create() as RNGCryptoServiceProvider;

            rng.GetNonZeroBytes(password);

            for (int index = 0; index < len; index++)
            {
                if (password[index] > 127 || password[index] < 33)
                {
                    byte c = password[index];
                    c = (byte)(c & 127);
                    if (c < 32)
                    {
                        c += 33;
                    }
                    password[index] = c;
                }
            }

            return(Encoding.ASCII.GetString(password));
        }
Exemple #25
0
        public static CryptoStream CreateEncryptionStream(byte[] key, Stream outputStream)
        {
            byte[] iv = new byte[IvSize];

            using (var rng = new RNGCryptoServiceProvider())
                // Using a cryptographic random number generator
                rng.GetNonZeroBytes(iv);

            // Write IV to the start of the stream
            outputStream.Write(iv, 0, iv.Length);

            Rijndael rijndael = new RijndaelManaged();

            rijndael.Padding = PaddingMode.None;
            rijndael.KeySize = KeySize;

            CryptoStream encryptor = new CryptoStream(
                outputStream,
                rijndael.CreateEncryptor(key, iv),
                CryptoStreamMode.Write);

            return(encryptor);
        }
Exemple #26
0
        /// <summary>
        /// Uses the crypto random number generator to generate unique strings of a specified length
        /// </summary>
        /// <param name="length">The length of the string to be generated</param>
        /// <returns>The generated string</returns>
        internal static string GenerateUniqueString(int length)
        {
            string a = "1234567890";     //string should be numeric

            char[] chars = new char[a.Length];
            chars = a.ToCharArray();
            byte[] data = new byte[length];
            RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();

            crypto.GetNonZeroBytes(data);
            string        generatedString;
            StringBuilder strGeneratedString = new StringBuilder();

            // Generate the unique string
            foreach (byte b in data)
            {
                strGeneratedString.Append(chars[b % (chars.Length - 1)]);
            }
            // The generated unique string
            generatedString = strGeneratedString.ToString();
            // Return the generated string
            return(generatedString);
        }
    public static void Main(string[] args)
    {
        Console.Write("Enter a password: "******"Salt: {Convert.ToBase64String(salt)}");

        // derive a 256-bit subkey (use HMACSHA256 with 100,000 iterations)
        string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
                                                   password: password,
                                                   salt: salt,
                                                   prf: KeyDerivationPrf.HMACSHA256,
                                                   iterationCount: 100000,
                                                   numBytesRequested: 256 / 8));

        Console.WriteLine($"Hashed: {hashed}");
    }
        private static UserRecord GenerateUser(string username, string password)
        {
            var saltBytes = new byte[SaltSize];
            var provider  = new RNGCryptoServiceProvider();

            provider.GetNonZeroBytes(saltBytes);

            var salt = Convert.ToBase64String(saltBytes);

            var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, saltBytes, DerivedBytesIteration);
            var hashPassword       = Convert.ToBase64String(rfc2898DeriveBytes.GetBytes(DerivedBytesSize));

            var userRecord = new UserRecord
            {
                Id           = Guid.NewGuid(),
                Username     = username,
                Password     = hashPassword,
                Salt         = salt,
                CreatedAtUtc = DateTime.UtcNow
            };

            return(userRecord);
        }
Exemple #29
0
        public string Encrypt(string value)
        {
            string res = "";

            try
            {
                if (value == null)
                {
                    return("");
                }
                if (value.Trim().Length == 0)
                {
                    return("");
                }
                byte[] key, iv;
                byte[] salt = new byte[8];
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                rng.GetNonZeroBytes(salt);
                DeriveKeyAndIV(passphrase, salt, out key, out iv);
                byte[] encryptedBytes         = EncryptStringToBytesAes(value, key, iv);
                byte[] encryptedBytesWithSalt = new byte[salt.Length + encryptedBytes.Length + 8];
                Buffer.BlockCopy(Encoding.ASCII.GetBytes("Salted__"), 0, encryptedBytesWithSalt, 0, 8);
                Buffer.BlockCopy(salt, 0, encryptedBytesWithSalt, 8, salt.Length);
                Buffer.BlockCopy(encryptedBytes, 0, encryptedBytesWithSalt, salt.Length + 8, encryptedBytes.Length);
                res = Convert.ToBase64String(encryptedBytesWithSalt);
                string new_pass = sha256(passphrase);
                string new_enc  = CalcHMACSHA256Hash(res, new_pass) + res;
                res = encrypt_str(new_enc);
                return(res);
            }
            catch (Exception exp)
            {
                clsCommon common = new clsCommon();
                common.Log("Encrypt", exp.Message + "(value=" + value + ")", true, exp);
            }
            return(res);
        }
        public string GenerateSalt()
        {
            byte[] saltBytes = new byte[] { };

            try
            {
                // Define min and max salt sizes.
                int minSaltSize;
                int maxSaltSize;

                minSaltSize = 4;
                maxSaltSize = 8;

                // Generate a random number for the size of the salt.
                Random random;
                random = new Random();

                int saltSize;
                saltSize = random.Next(minSaltSize, maxSaltSize);

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

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

                // Fill the salt with cryptographically strong byte values.
                rng.GetNonZeroBytes(saltBytes);
            }
            catch (Exception ex)
            {
                //return errors
            }

            return(Convert.ToBase64String(saltBytes));
        }
        private static string GetRandomString(int length, IEnumerable <char> characterSet)
        {
            if (length <= 0)
            {
                throw new ArgumentException("Length must be more than 0", nameof(length));
            }
            if (length > int.MaxValue / 8)
            {
                throw new ArgumentException("Length must be less than 255", nameof(length));
            }
            if (characterSet == null)
            {
                throw new ArgumentNullException(nameof(characterSet));
            }
            var characterArray = characterSet.Distinct().ToArray();

            if (characterArray.Length == 0)
            {
                throw new ArgumentException("Set of characters must not be empty", nameof(characterSet));
            }

            var bytes = new byte[length * 8];

            using (var rng = new RNGCryptoServiceProvider())
                rng.GetNonZeroBytes(bytes);

            var sb = new StringBuilder(length);

            for (var i = 0; i < length; i++)
            {
                var index = BitConverter.ToUInt64(bytes, i * 8) % (ulong)characterArray.Length;
                sb.Append(characterArray[index]);
            }

            return(sb.ToString());
        }
Exemple #32
0
        public static string GeneratePassword1(int length = 4, string charSet = null)
        {
            if (string.IsNullOrEmpty(charSet))
            {
                charSet = "ACDEFGHJKLMNPQRSTUVWXYZabcdefhkmnoprstwxyz2345679@$-!"; // BIOgijlqvu018
            }
            var strBuilder = new StringBuilder();

            using (var provider = new RNGCryptoServiceProvider())
            {
                while (strBuilder.Length < length)
                {
                    byte[] oneByte = new byte[1];
                    provider.GetNonZeroBytes(oneByte);
                    char character = (char)oneByte[0];
                    //Console.WriteLine(charSet.IndexOf(character));
                    if (charSet.IndexOf(character) != -1)
                    {
                        strBuilder.Append(character);
                    }
                }
            }
            return(strBuilder.ToString());
        }
Exemple #33
0
        public static string GetRandomText(int length)
        {
            if (length < 1)
            {
                return(null);
            }
            // Space is in there a few times so we get more spaces
            var chars = " abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 !§$%&/()=?+*#,.-;:_ "
                        .ToCharArray();
            var data = new byte[length];

            using (var crypto = new RNGCryptoServiceProvider())
            {
                crypto.GetNonZeroBytes(data);
            }

            var result = new StringBuilder(length);

            foreach (var b in data)
            {
                result.Append(chars[b % chars.Length]);
            }
            return(result.ToString());
        }
Exemple #34
0
        /// <summary>
        /// 伪素数产生
        /// </summary>
        /// <returns></returns>
        private BigInteger PseudoPrime()
        {
            bool       isPrime = false;
            BigInteger a       = new BigInteger();

            while (!isPrime)
            {
                RNGCryptoServiceProvider csp = new RNGCryptoServiceProvider();
                byte[] baCsp = new byte[65];
                csp.GetNonZeroBytes(baCsp);
                baCsp[64] = 0;
                isPrime   = true;
                a         = new BigInteger(baCsp);
                foreach (BigInteger b in _PRIME_LIST)
                {
                    if (a % b == 0)
                    {
                        isPrime = false;
                        break;
                    }
                }
            }
            return(a);
        }
Exemple #35
0
        public static void Tester()
        {
            int num = 10;

            char[] array = new char[62];
            array = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
            RandomNumberGenerator randomNumberGenerator = new RNGCryptoServiceProvider();

            byte[] array2 = new byte[num];
            randomNumberGenerator.GetNonZeroBytes(array2);
            StringBuilder stringBuilder = new StringBuilder(num);

            foreach (byte b in array2)
            {
                stringBuilder.Append(array[(int)b % (array.Length - 1)]);
            }
            StringBuilder stringBuilder2 = stringBuilder;

            Console.Title = (((stringBuilder2 != null) ? stringBuilder2.ToString() : null) ?? "");
            Thread thread = new Thread(new ThreadStart(menu.Tester));

            Thread.Sleep(1500);
            thread.Start();
        }
 /* Good1() changes true to false */
 private void Good1()
 {
     if (false)
     {
         /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
         IO.WriteLine("Benign, fixed string");
     }
     else
     {
         byte[] hashedBytes;
         using (SHA512CryptoServiceProvider sha512 = new SHA512CryptoServiceProvider())
         {
             using (RNGCryptoServiceProvider random = new RNGCryptoServiceProvider())
             {
                 var salt = new byte[32];
                 /* FIX: Use a sufficiently random salt */
                 random.GetNonZeroBytes(salt);
                 byte[] textWithSaltBytes = Encoding.UTF8.GetBytes(string.Concat("hash me", salt));
                 hashedBytes = sha512.ComputeHash(textWithSaltBytes);
             }
         }
         IO.WriteLine(IO.ToHex(hashedBytes));
     }
 }
 /* Good1() changes PRIVATE_CONST_FIVE==5 to PRIVATE_CONST_FIVE!=5 */
 private void Good1()
 {
     if (PRIVATE_CONST_FIVE != 5)
     {
         /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
         IO.WriteLine("Benign, fixed string");
     }
     else
     {
         using (HashAlgorithm sha = new SHA512CryptoServiceProvider())
         {
             /* FIX: Use a sufficiently random salt */
             var salt = new byte[32];
             using (var random = new RNGCryptoServiceProvider())
             {
                 random.GetNonZeroBytes(salt);
                 byte[] textWithSaltBytes = Encoding.UTF8.GetBytes(string.Concat("hash me", salt));
                 byte[] hashedBytes       = sha.ComputeHash(textWithSaltBytes);
                 sha.Clear();
                 IO.WriteLine(IO.ToHex(hashedBytes));
             }
         }
     }
 }
Exemple #38
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();
		}
    /// <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. 
    /// </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>
    /// <remarks>
    /// ComputeHash code provided as an example by Obviex at
    /// http://www.obviex.com/samples/hash.aspx
    /// As noted by Obviex themselves, code is definitely not optimally efficient.
    /// Should performance requirements necessitate improvement, this should
    /// be improved.
    /// </remarks>
    public static string ComputeHash(string plainText,
                                     string hashAlgorithm,
                                     byte[] saltBytes)
    {
        if (plainText == null)
            return null;

        // 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;
    }
    public string GeneratePassword()
    {

        char[] chars = new char[62];
        chars =
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
        byte[] data = new byte[1];
        RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
        crypto.GetNonZeroBytes(data);
        data = new byte[8];
        crypto.GetNonZeroBytes(data);
        System.Text.StringBuilder result = new System.Text.StringBuilder(8);
        foreach (byte b in data)
        {
            result.Append(chars[b % (chars.Length)]);
        }
        return result.ToString();
    }
    /// <summary>
    /// Generates an array holding cryptographically strong bytes.
    /// </summary>
    /// <returns>
    /// Array of randomly generated bytes.
    /// </returns>
    /// <remarks>
    /// Salt size will be defined at random or exactly as specified by the
    /// minSlatLen and maxSaltLen parameters passed to the object constructor.
    /// The first four bytes of the salt array will contain the salt length
    /// split into four two-bit pieces.
    /// </remarks>
    private byte[] GenerateSalt()
    {
        // We don't have the length, yet.
        int saltLen = 0;

        // If min and max salt values are the same, it should not be random.
        if (minSaltLen == maxSaltLen)
            saltLen = minSaltLen;
        // Use random number generator to calculate salt length.
        else
            saltLen = GenerateRandomNumber(minSaltLen, maxSaltLen);

        // Allocate byte array to hold our salt.
        byte[] salt = new byte[saltLen];

        // Populate salt with cryptographically strong bytes.
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

        rng.GetNonZeroBytes(salt);

        // Split salt length (always one byte) into four two-bit pieces and
        // store these pieces in the first four bytes of the salt array.
        salt[0] = (byte)((salt[0] & 0xfc) | (saltLen & 0x03));
        salt[1] = (byte)((salt[1] & 0xf3) | (saltLen & 0x0c));
        salt[2] = (byte)((salt[2] & 0xcf) | (saltLen & 0x30));
        salt[3] = (byte)((salt[3] & 0x3f) | (saltLen & 0xc0));

        return salt;
    }
    public static string ComputeHash(string plainText, string hashAlgorithm, byte[] saltBytes)
    {
        if (saltBytes == null)
        {
            int minSaltSize = 4;
            int maxSaltSize = 8;

            Random random = new Random();
            int saltSize = random.Next(minSaltSize, maxSaltSize);

            saltBytes = new byte[saltSize];

            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

            rng.GetNonZeroBytes(saltBytes);
        }

        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

        byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length];

        for (int i = 0; i < plainTextBytes.Length; i++)
            plainTextWithSaltBytes[i] = plainTextBytes[i];

        for (int i = 0; i < saltBytes.Length; i++)
            plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];

        HashAlgorithm hash;

        if (hashAlgorithm == null)
            hashAlgorithm = "";

        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;
        }

        byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

        byte[] hashWithSaltBytes = new byte[hashBytes.Length + saltBytes.Length];

        for (int i = 0; i < hashBytes.Length; i++)
            hashWithSaltBytes[i] = hashBytes[i];

        for (int i = 0; i < saltBytes.Length; i++)
            hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];

        string hashValue = Convert.ToBase64String(hashWithSaltBytes);

        return hashValue;
    }