Inheritance: RandomNumberGenerator
 private byte[] GetRandomSaltValue()
 {
     var rcsp = new RNGCryptoServiceProvider();
     var bSalt = new byte[16];
     rcsp.GetBytes(bSalt);
     return bSalt;
 }
Example #2
0
		public byte[] GenerateSalt()
		{
			var rng = new RNGCryptoServiceProvider();
			var salt = new byte[256];
			rng.GetBytes(salt);
			return salt;
		}
Example #3
0
        public bool AddUser(string userPassword, UsersDTO user)
        {
            try
            {
                var userentity = user.ToUser();
                var salt       = new Byte[32];
                using (var provider = new System.Security.Cryptography.RNGCryptoServiceProvider())
                {
                    provider.GetBytes(salt); // Generated salt
                }
                var pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(userPassword, salt);
                pbkdf2.IterationCount = 1000;
                byte[] hash = pbkdf2.GetBytes(32); // Hashed and salted password
                userentity.Salt        = salt;
                userentity.EncPassword = hash;

                operationalDataContext.Users.Add(userentity);

                return(operationalDataContext.SaveChanges() > 0);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Example #4
0
        private string GetBase32UniqueId(int length, char[] allowedCharSet)
        {
            if (length < 0)
            {
                throw new ArgumentOutOfRangeException("length", "length cannot be less than zero.");
            }
            if (_byteSize < allowedCharSet.Length)
            {
                throw new ArgumentException(String.Format("allowedChars may contain no more than {0} characters.", _byteSize));
            }

            using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
            {
                var result = new StringBuilder();
                var buf    = new byte[128];
                while (result.Length < length)
                {
                    rng.GetBytes(buf);
                    for (var i = 0; i < buf.Length && result.Length < length; ++i)
                    {
                        var outOfRangeStart = _byteSize - (_byteSize % allowedCharSet.Length);
                        if (outOfRangeStart <= buf[i])
                        {
                            continue;
                        }
                        result.Append(allowedCharSet[buf[i] % allowedCharSet.Length]);
                    }
                }
                return(result.ToString());
            }
        }
 public static string GenerateRandomSalt()
 {
     RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
     byte[] bytes = new byte[10];
     provider.GetBytes(bytes);
     return Convert.ToBase64String(bytes);
 }
Example #6
0
 /// <summary>
 /// Initializes an implementation of HMACSHA1
 /// </summary>
 public override void Initialize()
 {
     System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
     byte[] key = new byte[64];
     rng.GetBytes(key);
     //_key = OpenNETCF.Security.Cryptography.Internal.Rand.GetRandomBytes(64);
 }
Example #7
0
        private int[] 親からランダムな交叉(int[] geneA, int[] geneB, int パラメータ数)
        {
            //Int32と同じサイズのバイト配列にランダムな値を設定する
            //byte[] bs = new byte[sizeof(int)];
            byte[] bs = new byte[4];
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(bs);
            //Int32に変換する
            int seed = System.BitConverter.ToInt32(bs, 0);
            // そのseedを基にRandomを作る
            var r = new Random(seed++);

            int[] gene = new int[パラメータ数 + 他の要素];

            for (int i = 0; i < パラメータ数; i++)
            {
                if (r.Next(2) == 1)
                {
                    gene[i] = geneA[i];
                }
                else
                {
                    gene[i] = geneB[i];
                }
            }
            bs = null;
            rng.Dispose();
            r = null;
            return(gene);
        }
Example #8
0
 /// <summary>
 /// Returns the given number of seed bytes generated for the first running of a new instance 
 /// of the random number generator.
 /// </summary>
 /// <param name="numberOfBytes">Number of seed bytes to generate.</param>
 /// <returns>Seed bytes generated</returns>
 public static byte[] GetSeed(int numberOfBytes)
 {
     RNGCryptoServiceProvider generatedSeed = new RNGCryptoServiceProvider();
     byte[] seeds = new byte[numberOfBytes];
     generatedSeed.GetBytes(seeds);
     return seeds;
 }
Example #9
0
        private int[] ランダムに遺伝子1つ作成(int[,] パラメータ)
        {
            int パラメータ数 = パラメータ.Length / 2;

            //Int32と同じサイズのバイト配列にランダムな値を設定する
            //byte[] bs = new byte[sizeof(int)];
            byte[] bs = new byte[4];
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(bs);
            //Int32に変換する
            int seed = System.BitConverter.ToInt32(bs, 0);
            // そのseedを基にRandomを作る
            var r = new Random(seed++);

            int[] gene = new int[パラメータ数 + 他の要素];

            for (int i = 0; i < パラメータ数; i++)
            {
                gene[i] = r.Next(パラメータ[i, 0], パラメータ[i, 1] + 1);
            }
            bs = null;
            rng.Dispose();
            r = null;
            return(gene);
        }
Example #10
0
 public static string GenerateUID()
 {
     try
     {
         int    maxSize = 15;
         int    minSize = 10;
         char[] chars   = new char[63];
         string a;
         a     = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
         chars = a.ToCharArray();
         int    size = maxSize;
         byte[] data = new byte[2];
         System.Security.Cryptography.RNGCryptoServiceProvider crypto = new System.Security.Cryptography.RNGCryptoServiceProvider();
         crypto.GetNonZeroBytes(data);
         size = maxSize;
         data = new byte[size + 1];
         crypto.GetNonZeroBytes(data);
         StringBuilder result = new StringBuilder(size);
         foreach (byte b in data)
         {
             result.Append(chars[b % (chars.Length - 1)]);
         }
         return(result.ToString().Trim());
     }
     catch (Exception ex)
     {
         return("");
     }
 }
        public string CreateReference(int size)
        {
            const int byteSize = 0x100;
            var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
            var allowedCharSet = new HashSet<char>(chars).ToArray();

            using (var cryptoProvider = new RNGCryptoServiceProvider())
            {
                var result = new StringBuilder();
                var buffer = new byte[128];

                while (result.Length < size)
                {
                    cryptoProvider.GetBytes(buffer);

                    for (var i = 0; i < buffer.Length && result.Length < size; ++i)
                    {
                        var outOfRangeStart = byteSize - (byteSize % allowedCharSet.Length);

                        if (outOfRangeStart <= buffer[i])
                        {
                            continue;
                        }

                        result.Append(allowedCharSet[buffer[i] % allowedCharSet.Length]);
                    }
                }
                return result.ToString();
            }
        }
Example #12
0
 public static int NextInt32(int max)
 {
     byte[] bytes = new byte[sizeof(int)];
     RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider();
     Gen.GetBytes(bytes);
     return Math.Abs(BitConverter.ToInt32(bytes, 0) % max);
 }
Example #13
0
        /// <summary>
        /// This function stores user credentials using the Windows Data Protection API
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        public static void StorePerUserCredentials(string userName, SecureString password, string fileName, string keyName)
        {
            // Generate additional entropy (will be used as the Initialization vector)
            // This is basically the (2048-bit) encryption key used to encrypt the credentials
            // The encryption key changes everytime the credentials get stored for increased security (everytime someone logs in with "Remember Me" ticked)
            byte[] entropy = new byte[256];
            using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(entropy);
            }

            var currentUserRegistry = Registry.CurrentUser.OpenSubKey("Software\\SystemsUnitedNavy", true);
            if (currentUserRegistry == null)
                currentUserRegistry = Registry.CurrentUser.CreateSubKey("Software\\SystemsUnitedNavy", RegistryKeyPermissionCheck.Default);

            currentUserRegistry.SetValue(keyName, entropy);


            var data = ProtectedData.Protect(StringToByteArray(string.Format("{0};#{1}",
                userName, SecureStringUtility.SecureStringToString(password))),
                entropy,
                DataProtectionScope.CurrentUser);

            File.WriteAllBytes(fileName, data);
        }
 /// <summary>
 /// Creates a key based on the indicated size.
 /// </summary>
 /// <param name="numBytes">size of the key.</param>
 /// <returns>Generated key of the specified length.</returns>
 public static string CreateKey(int numBytes)
 {
     RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
     byte[] buff = new byte[numBytes];
     rng.GetBytes(buff);
     return BytesToHexString(buff);
 }
 public void TestCryptoRandom()
 {
     using (var random = new System.Security.Cryptography.RNGCryptoServiceProvider())
     {
         this.TestRandom(random.AsRandom());
     }
 }
Example #16
0
		/// <summary>
		/// Creates an array of bytes with a cryptographically strong sequence of random values.
		/// </summary>
		/// <param name="length">Length of array to create.</param>
		/// <returns>An array of bytes filled with a cryptographically strong sequence of random values.</returns>
		public static byte[] GetRandomBytes(int length)
		{
			byte[] randomBytes = new byte[length];
			RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
			rng.GetBytes(randomBytes);
			return randomBytes;
		}
        /// <summary>
        /// Generate Password Salt Int to add to password
        /// </summary>
        /// <returns>Salt Int</returns>

        internal string GenerateSalt()
        {
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] buff = new byte[32];
            rng.GetBytes(buff);
            return Convert.ToBase64String(buff);
        }
Example #18
0
 public static Int64 NextInt64()
 {
     var bytes = new byte[sizeof(Int64)];
        RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider();
        Gen.GetBytes(bytes);
        return BitConverter.ToInt64(bytes , 0);
 }
Example #19
0
        /// <summary>
        /// Creates a new and initialized instance of the TripleSec RNG (no parameters).
        /// </summary>
        public RNGV4()
        {
            // sure, the .NET RNG is pretty good, but lets make an attacker's life miserable
            // and also guard against a compromised RNG
            SSC.RNGCryptoServiceProvider rng = new SSC.RNGCryptoServiceProvider();
            byte[] tempKey  = new byte[512];
            byte[] tempSalt = new byte[512];
            rng.GetBytes(tempKey);
            rng.GetBytes(tempSalt);
            byte[] interim = new SSC.Rfc2898DeriveBytes(tempKey, tempSalt, 64).GetBytes(1024);
            rng.GetBytes(tempSalt);
            byte[] final = new SSC.Rfc2898DeriveBytes(interim, tempSalt, 64).GetBytes(56);
            tempKey.Wipe();
            tempSalt.Wipe();
            interim.Wipe(); // DON'T LEAK!!
            _salt       = new byte[16];
            _aesIV      = new byte[16];
            _xsalsa20IV = new byte[24];
            Buffer.BlockCopy(final, 0, _salt, 0, _salt.Length);
            Buffer.BlockCopy(final, 16, _aesIV, 0, _aesIV.Length);
            Buffer.BlockCopy(final, 16 + 16, _xsalsa20IV, 0, _xsalsa20IV.Length);
            _ready = true;
//#if DEBUG
//            System.Diagnostics.Debug.Print("RNGV4:-------------------------------------");
//            System.Diagnostics.Debug.Print("salt:        " + BitConverter.ToString(_salt).Replace("-", "").ToLowerInvariant());
//            System.Diagnostics.Debug.Print("aesIV:       " + BitConverter.ToString(_salt).Replace("-", "").ToLowerInvariant());
//            System.Diagnostics.Debug.Print("xsalsa20IV:  " + BitConverter.ToString(_salt).Replace("-", "").ToLowerInvariant());
//            System.Diagnostics.Debug.Print("final array: " + BitConverter.ToString(final).Replace("-", "").ToLowerInvariant());
//#endif
            final.Wipe(); // DON'T LEAVE COPIES LAYING AROUND!
        }
Example #20
0
 public string GetSalt(int saltLength)
 {
     var rng = new RNGCryptoServiceProvider();
     var saltBytes = new byte[saltLength];
     rng.GetNonZeroBytes(saltBytes);
     return BitConverter.ToString(saltBytes).Replace("-", "");
 }
        public static Stack<int> CreateCardsValues([NotNull] GameStage stage)
        {
            Contract.Requires(stage != null);

            var totalNumberOfCards = stage.CardsRows.Sum();
            var numberOfDifferentCards = totalNumberOfCards / stage.CardsInGroup;

            var cardsValues = new List<int>();

            for (int i = 0; i < numberOfDifferentCards; i++)
            {
                cardsValues.AddRange(Enumerable.Repeat(i, stage.CardsInGroup));
            }

            using (var rndGen = new RNGCryptoServiceProvider())
            {
                byte[] bytes = new byte[cardsValues.Count];
                rndGen.GetBytes(bytes);

                int[] ints = bytes.Select(b => b - byte.MaxValue / 2).ToArray();

                var rnd = new Random((int)DateTime.UtcNow.Ticks);

                cardsValues.Sort((c1, c2) => ints[rnd.Next(0, ints.Length)]);
            }

            return new Stack<int>(cardsValues);
        }
Example #22
0
 private byte[] GenerateSalt(int size)
 {
     byte[] data = new byte[size];
     System.Security.Cryptography.RNGCryptoServiceProvider provider = new System.Security.Cryptography.RNGCryptoServiceProvider();
     provider.GetBytes(data);
     return(data);
 }
 public static byte[] generateSalt()
 {
     RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
     byte[] salt = new byte[256];
     rng.GetBytes(salt);
     return salt;
 }
Example #24
0
 public string GenerateSalt()
 {
     var random = new RNGCryptoServiceProvider();
     var salt = new Byte[8];
     random.GetBytes(salt);
     return Convert.ToBase64String(salt);
 }
Example #25
0
 public static byte[] GetBuffer(int length)
 {
     RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
     byte[] output = new byte[length];
     rng.GetBytes(output);
     return output;
 }
Example #26
0
        private void CompareBlocks(int BlockSize)
        {
            using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
            {
                byte[] key = new byte[32];
                byte[] iv = new byte[BlockSize];
                byte[] data = new byte[1600];

                rng.GetBytes(key);
                rng.GetBytes(iv);
                rng.GetBytes(data);

                byte[] enc1 = EncryptRDX(key, iv, data);
                byte[] enc2 = EncryptManaged(key, iv, data);

                if (Compare.AreEqual(enc1, enc2) == false)
                    throw new Exception("Encrypted output is not equal!");

                byte[] dec1 = DecryptRDX(key, iv, data);
                byte[] dec2 = DecryptManaged(key, iv, data);

                if (Compare.AreEqual(dec2, dec1) == false)
                    throw new Exception("Decrypted output is not equal to input data!");
            }
        }
 static int GetRandomSeed()
 {
     byte[] bytes = new byte[4];
     System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
     rng.GetBytes(bytes);
     return BitConverter.ToInt32(bytes, 0);
 }
Example #28
0
 public string GenerateSalt() {
 var data = new byte[0x10];
 using (var cryptoServiceProvider = new RNGCryptoServiceProvider()) {
 cryptoServiceProvider.GetBytes(data);
 return Convert.ToBase64String(data);
 }
 }
Example #29
0
 public static int GetRandomSeed()
 {
     byte[] bytes = new byte[4];
     System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
     rng.GetBytes(bytes);
     return(BitConverter.ToInt32(bytes, 0));
 }
Example #30
0
 public static string CreateSalt()
 {
     byte[] bytSalt = new byte[9];
     System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
     rng.GetBytes(bytSalt);
     return(Convert.ToBase64String(bytSalt));
 }
Example #31
0
 /// <summary>
 /// 生成随机数的种子
 /// </summary>
 /// <returns></returns>
 private static int getNewSeed()
 {
     byte[] rndBytes = new byte[4];
     System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
     rng.GetBytes(rndBytes);
     return(BitConverter.ToInt32(rndBytes, 0));
 }
Example #32
0
        static byte[] GenerateSaltedHash(string input, int size)
        {
            var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();

            byte[] salt = new byte[size];
            rng.GetBytes(salt);


            byte[]        plainText = Encoding.UTF8.GetBytes(input);
            HashAlgorithm algorithm = new SHA256Managed();

            byte[] plainTextWithSaltBytes =
                new byte[plainText.Length + salt.Length];

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

            return(algorithm.ComputeHash(plainTextWithSaltBytes));
        }
Example #33
0
 public static byte[] getNewRandomSeed(int seed_len)
 {
     byte[] entropy = new byte[seed_len];
     System.Security.Cryptography.RNGCryptoServiceProvider rngCSP = new System.Security.Cryptography.RNGCryptoServiceProvider();
     rngCSP.GetBytes(entropy);
     return(entropy);
 }
        /// <summary>
        /// Generate a random string of characters
        /// </summary>
        /// <param name="length">length of string</param>
        /// <param name="type">type of string to be generated</param>
        /// <returns></returns>
        public static string GenerateRandomString(int length, StringType type)
        {
            switch (type)
            {
                case StringType.AlphaNumeric:
                    string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
                    char[] chars = new char[length];
                    Random rd = new Random();

                    for (int i = 0; i < length; i++)
                    {
                        chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
                    }

                    return new string(chars);
                    break;

                case StringType.AlphaNumericSymbol:
                    //Generate a cryptographic random number.
                    var rng = new RNGCryptoServiceProvider();
                    var buff = new byte[length];
                    rng.GetBytes(buff);

                    rng.Dispose();

                    // Return a Base64 string representation of the random number.
                    return Convert.ToBase64String(buff);
                    break;
                default:
                    throw new ArgumentException("Type not supported");
            }
        }
Example #35
0
 public static string CreateRandomSalt()
 {
     var saltBytes = new Byte[4];
     var rng = new RNGCryptoServiceProvider();
     rng.GetBytes(saltBytes);
     return Convert.ToBase64String(saltBytes);
 }
        public static string Generate(int length, string allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
        {
            if (length < 0) throw new ArgumentOutOfRangeException("length", "length cannot be less than zero.");
            if (string.IsNullOrEmpty(allowedChars)) throw new ArgumentException("allowedChars may not be empty.");

            const int byteSize = 0x100;
            var allowedCharSet = new HashSet<char>(allowedChars).ToArray();
            if (byteSize < allowedCharSet.Length) throw new ArgumentException(String.Format("allowedChars may contain no more than {0} characters.", byteSize));

            // Guid.NewGuid and System.Random are not particularly random. By using a
            // cryptographically-secure random number generator, the caller is always
            // protected, regardless of use.
            using (var rng = new RNGCryptoServiceProvider())
            {
                var result = new StringBuilder();
                var buf = new byte[128];
                while (result.Length < length)
                {
                    rng.GetBytes(buf);
                    for (var i = 0; i < buf.Length && result.Length < length; ++i)
                    {
                        // Divide the byte into allowedCharSet-sized groups. If the
                        // random value falls into the last group and the last group is
                        // too small to choose from the entire allowedCharSet, ignore
                        // the value in order to avoid biasing the result.
                        var outOfRangeStart = byteSize - (byteSize % allowedCharSet.Length);
                        if (outOfRangeStart <= buf[i]) continue;
                        result.Append(allowedCharSet[buf[i] % allowedCharSet.Length]);
                    }
                }
                return result.ToString();
            }
        }
Example #37
0
 public string CreateSalt()
 {
     byte[] array = new byte[8];
     System.Security.Cryptography.RNGCryptoServiceProvider rNGCryptoServiceProvider = new System.Security.Cryptography.RNGCryptoServiceProvider();
     rNGCryptoServiceProvider.GetBytes(array);
     return(System.Convert.ToBase64String(array));
 }
		/// <summary>
		/// http://www.codeproject.com/Articles/14403/Generating-Unique-Keys-in-Net
		/// </summary>
		/// <returns></returns>
		public static string GetUniqueNumber()
		{
			//string result = DateTime.Now.Year.ToString() + Guid.NewGuid().ToString().GetHashCode().ToString("x");
			//return result;

			int maxSize = 8;
			char[] chars = new char[62];
			string a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
			chars = a.ToCharArray();
			int size = maxSize;
			byte[] data = new byte[1];

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

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

			return "CS" + result.ToString();

		}
Example #39
0
File: Util.cs Project: githexing/05
        public static string GetUniqueIndentifier(int length)
        {
            if (length <= 0)
            {
                return(string.Empty);
            }
            int maxSize = length;

            char[] chars = new char[62];
            string a     = "abcdefghijklmnopqrstuvwxyz1234567890";

            chars = a.ToCharArray();
            int size = maxSize;

            byte[] data = new byte[1];
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetNonZeroBytes(data);
            size = maxSize;
            data = new byte[size];
            rng.GetNonZeroBytes(data);
            StringBuilder result = new StringBuilder();

            foreach (byte b in data)
            {
                result.Append(chars[b % (chars.Length - 1)]);
            }
            if (result[0] >= '0' && result[0] <= '9')
            {
                return(GetUniqueIndentifier(length));
            }
            return(result.ToString());
        }
Example #40
0
 public static string GenerateSalt(int saltSize)
 {
     RNGCryptoServiceProvider rngCryptoServiceProvider = new RNGCryptoServiceProvider();
     byte[] byteArray = new Byte[saltSize];
     rngCryptoServiceProvider.GetBytes(byteArray);
     return Convert.ToBase64String(byteArray);
 }
Example #41
0
 public static byte[] CreateSalt(int size = 16)
 {
     RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
     byte[] buff = new byte[size];
     rng.GetBytes(buff);
     return buff;
 }
        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 = 200;

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

            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);
        }
Example #43
0
        //
        // internal static methods
        //

        // CMS TripleDES KeyWrap as described in "http://www.w3.org/2001/04/xmlenc#kw-tripledes"
        internal static byte[] TripleDESKeyWrapEncrypt (byte[] rgbKey, byte[] rgbWrappedKeyData) {
            // checksum the key
            SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
            byte[] rgbCKS = sha.ComputeHash(rgbWrappedKeyData);

            // generate a random IV
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] rgbIV = new byte[8];
            rng.GetBytes(rgbIV);

            // rgbWKCS = rgbWrappedKeyData | (first 8 bytes of the hash)
            byte[] rgbWKCKS = new byte[rgbWrappedKeyData.Length + 8];
            TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
            // Don't add padding, use CBC mode: for example, a 192 bits key will yield 40 bytes of encrypted data
            tripleDES.Padding = PaddingMode.None;
            ICryptoTransform enc1 = tripleDES.CreateEncryptor(rgbKey, rgbIV);
            Buffer.BlockCopy(rgbWrappedKeyData, 0, rgbWKCKS, 0, rgbWrappedKeyData.Length);
            Buffer.BlockCopy(rgbCKS, 0, rgbWKCKS, rgbWrappedKeyData.Length, 8);
            byte[] temp1 = enc1.TransformFinalBlock(rgbWKCKS, 0, rgbWKCKS.Length);
            byte[] temp2 = new byte[rgbIV.Length + temp1.Length];
            Buffer.BlockCopy(rgbIV, 0, temp2, 0, rgbIV.Length);
            Buffer.BlockCopy(temp1, 0, temp2, rgbIV.Length, temp1.Length);
            // temp2 = REV (rgbIV | E_k(rgbWrappedKeyData | rgbCKS))
            Array.Reverse(temp2);

            ICryptoTransform enc2 = tripleDES.CreateEncryptor(rgbKey, s_rgbTripleDES_KW_IV);
            return enc2.TransformFinalBlock(temp2, 0, temp2.Length);
        }
Example #44
0
 public static string GenerateToken()
 {
     RNGCryptoServiceProvider r = new RNGCryptoServiceProvider();
     byte[] buffer = new byte[39];
     r.GetNonZeroBytes(buffer);
     return Convert.ToBase64String(buffer);
 }
Example #45
0
        /// <summary>
        /// CreateHashedText
        /// </summary>
        /// <param name="plainText"></param>
        /// <param name="useSalt"></param>
        /// <returns></returns>
        public static KeyValuePair<string, string> CreateHashedText(string plainText,bool useSalt)
        {
            var plainTextBytes = Encoding.Unicode.GetBytes(plainText);

            string salt = string.Empty;
            string hashedText = string.Empty;
            if (useSalt)
            {
                var saltBytes = new byte[0x10];
                using (var random = new RNGCryptoServiceProvider())
                {
                    random.GetBytes(saltBytes);
                }

                salt = Convert.ToBase64String(saltBytes);
                plainTextBytes=saltBytes.Concat(plainTextBytes).ToArray();
            }

            byte[] hashBytes;
            using (var hashAlgorithm = HashAlgorithm.Create())
            {
                hashBytes = hashAlgorithm.ComputeHash(plainTextBytes);
            }

            hashedText = Convert.ToBase64String(hashBytes);

            return new KeyValuePair<string, string>(hashedText, salt);
        }
Example #46
0
 /// <summary>
 /// Returns a random 64 character hex string (256 bits)
 /// </summary>
 /// <returns>The random string</returns>
 private static string GetRandomSalt()
 {
     RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();
     byte[] salt = new byte[32]; // 256 bits
     random.GetBytes(salt);
     return BytesToHex(salt);
 }
Example #47
0
 private int GetRandomSeed()
 {
     byte[] bytes = new byte[4];
     System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
     rng.GetBytes(bytes);
     Console.WriteLine(BitConverter.ToInt32(bytes, 0));
     return(BitConverter.ToInt32(bytes, 0));
 }
Example #48
0
 /// <summary>
 /// 获取随机数种子
 /// </summary>
 /// <returns></returns>
 public static int GetRandomSeed()
 {
     byte[] bytes = new byte[4];
     //使用加密服务提供程序 (CSP)提供的实现来实现加密随机数生成器 (RNG)。无法继承此类。
     System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
     rng.GetBytes(bytes);//用经过加密的强随机值序列填充字节数组。
     return BitConverter.ToInt32(bytes, 0);
 }
Example #49
0
        public static String KrijoSalt(int madhesia)
        {
            var nrRastesishem = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var baferi        = new byte[madhesia];

            nrRastesishem.GetBytes(baferi);
            return(Convert.ToBase64String(baferi));
        }
        public string CreateSalt(int SaltSize)
        {
            var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();

            byte[] Salt = new byte[SaltSize];
            rng.GetBytes(Salt);
            return(Convert.ToBase64String(Salt));
        }
Example #51
0
        /// <summary>
        /// serialization of password
        /// </summary>
        /// <param name="size">password split size</param>
        /// <returns></returns>
        public string CreateSalt(int size)
        {
            byte[] bytedata    = new byte[size];
            var    rngProvider = new System.Security.Cryptography.RNGCryptoServiceProvider();

            rngProvider.GetBytes(bytedata);
            return(Convert.ToBase64String(bytedata));
        }
Example #52
0
        public static string CreateSalt(int size)
        {
            var rng  = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var buff = new byte[size];

            rng.GetBytes(buff);
            return(Convert.ToBase64String(buff));
        }
Example #53
0
    private String CreateSalt(int size)
    {
        RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();

        byte[] buffer = new byte[size];
        rng.GetBytes(buffer);

        return(Convert.ToBase64String(buffer));
    }
Example #54
0
    /// <summary>
    /// Return random string by specific length.
    /// </summary>
    /// <param name="length">String length.</param>
    /// <param name="NumbersOnly">Numbers only flag.</param>
    /// <returns>String with specified length.</returns>
    public static string RandomString(int length, bool NumbersOnly = false)
    {
        string allowedChars;

        if (NumbersOnly)
        {
            allowedChars = "0123456789";
        }
        else
        {
            allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        }

        if (length < 0)
        {
            throw new ArgumentOutOfRangeException("length", "length cannot be less than zero.");
        }
        if (string.IsNullOrEmpty(allowedChars))
        {
            throw new ArgumentException("allowedChars may not be empty.");
        }

        const int byteSize       = 0x100;
        var       allowedCharSet = allowedChars.ToCharArray();

        if (byteSize < allowedCharSet.Length)
        {
            throw new ArgumentException(String.Format("allowedChars may contain no more than {0} characters.", byteSize));
        }

        // Guid.NewGuid and System.Random are not particularly random. By using a
        // cryptographically-secure random number generator, the caller is always
        // protected, regardless of use.
        using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
        {
            var result = new StringBuilder();
            var buf    = new byte[128];
            while (result.Length < length)
            {
                rng.GetBytes(buf);
                for (var i = 0; i < buf.Length && result.Length < length; ++i)
                {
                    // Divide the byte into allowedCharSet-sized groups. If the
                    // random value falls into the last group and the last group is
                    // too small to choose from the entire allowedCharSet, ignore
                    // the value in order to avoid biasing the result.
                    var outOfRangeStart = byteSize - (byteSize % allowedCharSet.Length);
                    if (outOfRangeStart <= buf[i])
                    {
                        continue;
                    }
                    result.Append(allowedCharSet[buf[i] % allowedCharSet.Length]);
                }
            }
            return(result.ToString());
        }
    }
Example #55
0
 public byte[] generateIV()
 {
     using (System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
     {
         byte[] nonce = new byte[16];
         rng.GetBytes(nonce);
         return(nonce);
     }
 }
        public string GetSecretKey()
        {
            System.Security.Cryptography.RandomNumberGenerator cryptoRandomDataGenerator = new System.Security.Cryptography.RNGCryptoServiceProvider();
            byte[] buffer = new byte[48];
            cryptoRandomDataGenerator.GetBytes(buffer);
            string secretkey = Convert.ToBase64String(buffer);

            return(secretkey);
        }
Example #57
0
        protected void GenerateRandomDataButton_Click(object sender, EventArgs e)
        {
            // Generate random 10 byte array.
            var rnd   = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var bytes = new System.Byte[10];

            rnd.GetNonZeroBytes(bytes);
            DataTextBox.Text = string.Join("", bytes.Select(x => x.ToString("X2")));
        }
Example #58
0
 /****************************************************
 * Util
 ****************************************************/
 private static byte[] GetRandomData(int length)
 {
     using (var rngCsp = new System.Security.Cryptography.RNGCryptoServiceProvider())
     {
         var randomData = new byte[length];
         rngCsp.GetBytes(randomData);
         return(randomData);
     }
 }
Example #59
0
        private static string getPP()
        {
            var randomNumberGenerator = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var tokenData             = new byte[32];

            randomNumberGenerator.GetBytes(tokenData);
            return(Convert.ToBase64String(tokenData.Concat(Guid.NewGuid().ToByteArray()).ToArray())
                   .Replace('/', '_')
                   .Replace('+', '-'));
        }
Example #60
0
    private static Random GetRandom()
    {
        //产生随机数  参考代码:https://www.cnblogs.com/xiaowie/p/8759837.html
        byte[] randomBytes = new byte[4];
        System.Security.Cryptography.RNGCryptoServiceProvider rngServiceProivider = new System.Security.Cryptography.RNGCryptoServiceProvider();
        rngServiceProivider.GetBytes(randomBytes);
        int iSeed = BitConverter.ToInt32(randomBytes, 0);

        return(new Random(iSeed));
    }