Пример #1
0
        public static string GeneratePassword(int intLength, int intNumberOfNonAlphaNumericCharacters)
        {
            int intNonAlphaCount = 0;
            byte[] buffer = new byte[intLength];
            char[] aryPassword = new char[intLength];
            char[] aryPunctuations = "!@@$%$%*()@-+=[{]}#%>|%#?".ToCharArray();

            System.Security.Cryptography.RNGCryptoServiceProvider objCrypto = new System.Security.Cryptography.RNGCryptoServiceProvider();
            objCrypto.GetBytes(buffer);

            for (int i = 0; i < intLength; i++)
            {
                //Convert each byte into its representative character
                int intRndChr = (buffer[i] % 87);
                if (intRndChr < 10)
                    aryPassword[i] = Convert.ToChar(Convert.ToUInt16(48 + intRndChr));
                else if (intRndChr < 36)
                    aryPassword[i] = Convert.ToChar(Convert.ToUInt16((65 + intRndChr) - 10));
                else if (intRndChr < 62)
                    aryPassword[i] = Convert.ToChar(Convert.ToUInt16((97 + intRndChr) - 36));
                else
                {
                    if (intNonAlphaCount >= intNumberOfNonAlphaNumericCharacters)
                    {
                        i--;
                        objCrypto.GetBytes(buffer);
                    }
                    else
                    {
                        aryPassword[i] = aryPunctuations[intRndChr - 62];
                        intNonAlphaCount++;
                    }
                }
            }

            if (intNonAlphaCount < intNumberOfNonAlphaNumericCharacters)
            {
                Random objRandom = new Random();
                for (int i = 0; i < (intNumberOfNonAlphaNumericCharacters - intNonAlphaCount); i++)
                {
                    int intIndex;
                    do
                    {
                        intIndex = objRandom.Next(0, intLength);
                    } while (!Char.IsLetterOrDigit(aryPassword[intIndex]));
                    aryPassword[intIndex] = aryPunctuations[objRandom.Next(0, aryPunctuations.Length)];
                }
            }

            Array.Reverse(aryPassword);
            return new string(aryPassword);
        }
Пример #2
0
 public Challenge(string CBCryptHostId)
 {
     this.CBCryptHostId = CBCryptHostId;
     this.ChallengeBytes = new byte[ChallengeSize];
     // The easiest way for me to generate an ephemeral key is to feed random bytes into CBCrypt.GenerateKeyPair
     var tempKey = new byte[tempKeySize];
     using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider()) {
         rng.GetBytes(this.ChallengeBytes);
         rng.GetBytes(tempKey);
     }
     this.ServerEphemeralKey = new CBCryptKey(tempKey);
     this.ServerPublicKeyDerEncoded = this.ServerEphemeralKey.GetPublicKeyDerEncoded();
 }
Пример #3
0
        public void Roundtrip_RndIV_Success()
        {
            const string vendorGuid = "abc";
            const bool   isRead     = false;

            var str = "{\"filters\": [{\"property_name\": \"vendor_id\",\"operator\": \"eq\",\"property_value\": \"VENDOR_GUID\"}],\"allowed_operations\": [ \"READ_OR_WRITE\" ]}";

            str = str.Replace("VENDOR_GUID", vendorGuid);

            str = str.Replace("READ_OR_WRITE", isRead ? "read" : "write");

            var rnd   = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var bytes = new byte[16];

            rnd.GetBytes(bytes);

            var iv = String.Concat(bytes.Select(b => b.ToString("X2"))); Trace.WriteLine("IV: " + iv);

            Trace.WriteLine("plaintext: " + str);
            var scopedKey = ScopedKey.EncryptString(SettingsEnv.MasterKey, str, iv);

            Trace.WriteLine("encrypted: " + scopedKey);
            var decrypted = ScopedKey.Decrypt(SettingsEnv.MasterKey, scopedKey);

            Trace.WriteLine("decrypted: " + decrypted);

            // Make sure the input string exactly matches the decrypted string. This input isn't of
            // a length that is a multiple of block size or key size, so this would have required
            // manual padding in the past. The decrypted string shouldn't have any padding now.
            Assert.AreEqual(str, decrypted);
        }
Пример #4
0
        public void Roundtrip_RndIV_Success()
        {
            const string vendor_guid = "abc";
            const bool   isRead      = false;

            var str = "{\"filters\": [{\"property_name\": \"vendor_id\",\"operator\": \"eq\",\"property_value\": \"VENDOR_GUID\"}],\"allowed_operations\": [ \"READ_OR_WRITE\" ]}";

            str = str.Replace("VENDOR_GUID", vendor_guid);

            if (isRead)
            {
                str = str.Replace("READ_OR_WRITE", "read");
            }
            else
            {
                str = str.Replace("READ_OR_WRITE", "write");
            }

            var rnd = new System.Security.Cryptography.RNGCryptoServiceProvider();

            byte[] bytes = new byte[16];
            rnd.GetBytes(bytes);

            var IV = String.Concat(bytes.Select(b => b.ToString("X2"))); Trace.WriteLine("IV: " + IV);

            var scopedKey = ScopedKey.EncryptString(SettingsEnv.MasterKey, str, IV); //System.Text.Encoding.Default.GetString(bytes));
            var decrypted = ScopedKey.Decrypt(SettingsEnv.MasterKey, scopedKey);

            Trace.WriteLine("decrypted: " + decrypted);
        }
Пример #5
0
 private void LbFileKey_Click(object sender, EventArgs e)
 {
     byte[] buffer = new byte[64];
     using (var csp = new System.Security.Cryptography.RNGCryptoServiceProvider())
         csp.GetBytes(buffer);
     TbFileKey.Text = Util.ToHexString(buffer);
 }
Пример #6
0
 /// <summary>
 /// Creates and sets a random initialization vector.
 /// </summary>
 /// <returns>The random IV</returns>
 public byte[] SetRandomIV()
 {
     InitVector = new byte[8];
     randomSource.GetBytes(InitVector);
     IVSet = true;
     return(InitVector);
 }
Пример #7
0
        // courtesy of https://dotnetfiddle.net/grgEIh
        private static void GenerateToken()
        {
            string allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            int    length       = 64;

            const int byteSize       = 0x100;
            var       allowedCharSet = new HashSet <char>(allowedChars).ToArray();

            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]);
                    }
                }
                Console.WriteLine(result.ToString());
            }
        }
 private byte[] CreateRandomSalt()
 {
     byte[] randomSalt = new byte[SaltLength];
     System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
     rng.GetBytes(randomSalt);
     return(randomSalt);
 }
Пример #9
0
        private byte[] NewSalt()
        {
            var salt = new byte[saltLength];

            RNG.GetBytes(salt);
            return(salt);
        }
Пример #10
0
 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);
 }
Пример #11
0
        static void Espresso_Publisher(ZContext context)
        {
            // The publisher sends random messages starting with A-J:

            using (var publisher = ZSocket.Create(context, ZSocketType.PUB))
            {
                publisher.Bind("tcp://*:6000");

                ZError error;
                var    hash = new System.Security.Cryptography.RNGCryptoServiceProvider();

                while (true)
                {
                    var bytes = new byte[5];
                    hash.GetBytes(bytes);

                    if (!publisher.Send(bytes, 0, bytes.Length, ZSocketFlags.None, out error))
                    {
                        if (error == ZError.ETERM)
                        {
                            return;                             // Interrupted
                        }
                        throw new ZException(error);
                    }

                    Thread.Sleep(20);
                }
            }
        }
Пример #12
0
 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));
 }
Пример #13
0
        static void Main(string[] args)
        {
            if (args == null || args.Length < 2)
            {
                Console.WriteLine("Usage: rngf [file size in mb] [file name]");
                return;
            }

            var sizeInMB = int.Parse(args[0]);
            var filename = args[1];

            var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();

            using (var fs = File.OpenWrite(filename))
            {
                for (var i = 0; i < sizeInMB; i++)
                {
                    var buffer = new byte[1024 * 1024];
                    rng.GetBytes(buffer);
                    fs.Write(buffer, 0, buffer.Length);
                }
            }

            Console.WriteLine(string.Format("Output '{0}' ({1}MB).", filename, sizeInMB));
        }
Пример #14
0
        static void Espresso_Publisher(ZContext context)
        {
            // The publisher sends random messages starting with A-J:

            using (var publisher = new ZSocket(context, ZSocketType.PUB))
            {
                publisher.Bind("tcp://*:6000");

                ZError error;

                while (true)
                {
                    var bytes = new byte[5];
                    using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
                    {
                        rng.GetBytes(bytes);
                    }
                    var frame = new ZFrame(bytes);
                    if (!publisher.Send(frame, out error))
                    {
                        if (error == ZError.ETERM)
                        {
                            return;                             // Interrupted
                        }
                        throw new ZException(error);
                    }

                    Thread.Sleep(1);
                }
            }
        }
Пример #15
0
        public ActionResult Index(Members member)
        {
            //先做一個salt再存Password
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            byte[] buf = new byte[15];
            rng.GetBytes(buf);
            string salt = Convert.ToBase64String(buf);

            string Password = member.Password;

            Password        = FormsAuthentication.HashPasswordForStoringInConfigFile(Password + salt, "sha1");
            member.Password = Password;

            db.Members.Add(member);
            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                throw;
            }

            return(View());
        }
Пример #16
0
 public ZActor(ZContext context, ZAction action, params object[] args)
     : this(context, default(string), action, args)
 {
     var rnd0 = new byte[8];
     using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider()) rng.GetBytes(rnd0);
     this.Endpoint = string.Format("inproc://{0}", ZContext.Encoding.GetString(rnd0));
 }
Пример #17
0
        public bool AddNewUser(string password, PublicUserDTO userDto)
        {
            try
            {
                var userentity = userDto.ToPublicUser();// userDto.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(password, salt);
                pbkdf2.IterationCount = 1000;
                byte[] hash = pbkdf2.GetBytes(32); // Hashed and salted password
                userentity.Salt      = salt;
                userentity.Password  = hash;
                userentity.IssueDate = DateTime.Now;
                _dBContext.PublicUsers.Add(userentity);

                return(_dBContext.SaveChanges() > 0);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Пример #18
0
        public static string Generate()
        {
            // Generate random
            var rnd = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var entropy = new byte[bytes - 4];
            try {
                rnd.GetBytes(entropy);
            } finally {
                rnd.Dispose();
            }

            // Hash
            var sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            byte[] hash;
            try {
                hash = sha.ComputeHash(entropy);
            } finally {
                sha.Dispose();
            }

            // Compute output
            var raw = new byte[bytes];
            Array.Copy(entropy, 0, raw, 0, bytes - 4);
            Array.Copy(hash, 0, raw, bytes - 4, 4);

            // Convert to Base64
            return Convert.ToBase64String(raw).Replace('+', '!').Replace('/', '~');
        }
Пример #19
0
        static void Main()
        {
            Console.WriteLine("using System.Random:");

            Random rand = new Random();

            for (int i = 0; i < 5; i++)
            {
                Console.Write("{0} ", rand.Next());
            }
            Console.WriteLine();

            Console.WriteLine("using System.Random/numbers in range (-10, 10)");
            for (int i = 0; i < 5; i++)
            {
                Console.Write("{0} ", rand.Next(-10, 10));
            }
            Console.WriteLine();

            Console.WriteLine("using RNGCryptoServiceProvider:");

            System.Security.Cryptography.RNGCryptoServiceProvider cryptRand = new System.Security.Cryptography.RNGCryptoServiceProvider();
            for (int i = 0; i < 5; i++)
            {
                byte[] bytes = new byte[4];
                cryptRand.GetBytes(bytes);
                Int32 number = BitConverter.ToInt32(bytes, 0);
                Console.Write("{0} ", number);
            }
            Console.WriteLine();
            Console.ReadKey();
        }
Пример #20
0
 public void TestOccasaionallyIgnored()
 {
     var rnd = new System.Security.Cryptography.RNGCryptoServiceProvider();
     var buf = new byte[1];
     rnd.GetBytes(buf);
     if ( buf[0] > 100 ) Assert.Ignore("too big");
 }
Пример #21
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));
 }
Пример #22
0
 /// <summary>
 /// Create string salt
 /// </summary>
 /// <param name="grv">Create string salt</param>
 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);
 }
        public ActionResult ChangePassword(User user)
        {
            /*
             * SSOContext _db = new SSOContext();
             * UserLuka l = new UserLuka();
             * l.NAME = "luka lol";
             *
             * _db.UserLukas.Add(l);
             * _db.SaveChanges();
             */
            // Succeful login
            // Make token
            var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();

            byte[] tokenB = new byte[40];
            rng.GetBytes(tokenB);

            //Convert to hex
            String tokenHex = BitConverter.ToString(tokenB).Replace("-", String.Empty);
            Claim  claim    = new Claim();

            claim.Token   = tokenHex;
            claim.Valid   = "1";
            claim.Created = DateTime.Now;
            claim.User    = user;

            throw new SSOBaseException("This method is currently not implemented.", System.Net.HttpStatusCode.NotImplemented);
        }
Пример #24
0
 static string GetNonceAsHexDigitString(int lengthInBytes)
 {
     var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
     var bytes = new byte[lengthInBytes];
     rng.GetBytes(bytes);
     return ToHexDigitString(bytes);
 }
Пример #25
0
 public static string GenerateNewSalt()
 {
     byte[] saltInBytes = new byte[16];
     System.Security.Cryptography.RNGCryptoServiceProvider saltGenerator = new System.Security.Cryptography.RNGCryptoServiceProvider();
     saltGenerator.GetBytes(saltInBytes);
     return(Convert.ToBase64String(saltInBytes));
 }
Пример #26
0
 public static string GenerateNewSalt()
 {
     byte[] saltInBytes = new byte[16];
        System.Security.Cryptography.RNGCryptoServiceProvider saltGenerator = new System.Security.Cryptography.RNGCryptoServiceProvider();
        saltGenerator.GetBytes(saltInBytes);
        return Convert.ToBase64String(saltInBytes);
 }
Пример #27
0
		static void Espresso_Publisher(ZContext context) 
		{
			// The publisher sends random messages starting with A-J:

			using (var publisher = new ZSocket(context, ZSocketType.PUB))
			{
				publisher.Bind("tcp://*:6000");

				ZError error;

				while (true)
				{
					var bytes = new byte[5];
					using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
					{
						rng.GetBytes(bytes);
					}

					if (!publisher.SendBytes(bytes, 0, bytes.Length, ZSocketFlags.None, out error))
					{
						if (error == ZError.ETERM)
							return;	// Interrupted
						throw new ZException(error);
					}

					Thread.Sleep(1);
				}
			}
		}
Пример #28
0
        /// <remarks>
        /// http://stackoverflow.com/questions/730268/unique-random-string-generation
        /// </remarks>
        string GenerateRandomString(int length,
            string allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
        {
            if (length < 0) throw new ArgumentOutOfRangeException(nameof(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($"allowedChars may contain no more than {byteSize} characters.");

            // 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();
            }
        }
Пример #29
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));
 }
Пример #30
0
        public string GetNext(int length, char[] charSet)
        {
            if (length < 0)
            {
                throw new ArgumentOutOfRangeException("length", "Length cannot be less than zero.");
            }

            const int byteSize = 0x100;
            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 % charSet.Length);
                        if (outOfRangeStart <= buf[i]) continue;
                        result.Append(charSet[buf[i] % charSet.Length]);
                    }
                }
                return result.ToString();
            }
        }
Пример #31
0
        //抽奖算法函数
        private void lottyCtrl()
        {
            //开始
            string strPath = "";
            int    ocont   = 0;

            ocont = SeedsList.Items.Count - 1;
            //随机数
            if (timer_lottery.Enabled == false)
            {
                if (ocont > 1)
                {
                    timer_lottery.Enabled = true;
                    strPath        = System.IO.Directory.GetCurrentDirectory() + "\\images\\btn_end.png";
                    BtnStart.Image = Image.FromFile(strPath);
                }
                else
                {
                    MessageBox.Show("已没有可供抽取的人员,抽奖中止");
                }
            }
            else
            {
                strPath               = System.IO.Directory.GetCurrentDirectory() + "\\images\\btn_start.png";
                BtnStart.Image        = Image.FromFile(strPath);
                timer_lottery.Enabled = false;
                //从数据库中抽一个人,显示,记录
                OleDbConnection odcConnection = new OleDbConnection(strConn);
                odcConnection.Open();
                OleDbCommand odCommand      = odcConnection.CreateCommand();
                DateTime     dt             = DateTime.Now;
                char[]       delimiterChars = { ';' };
                byte[]       bytes          = new byte[4];
                System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
                rng.GetBytes(bytes);
                Random rnd2   = new Random(BitConverter.ToInt32(bytes, 0));
                int    rndNum = rnd2.Next(0, SeedsList.Items.Count - 1);
                string Rtext  = SeedsList.Items[rndNum].ToString();
                SeedsList.Items.RemoveAt(rndNum); //删除一个
                string[] sArray = Rtext.Split(delimiterChars);
                LabName.Text = sArray[2] + "[" + sArray[3] + "]";
                LabCorp.Text = sArray[1];
                string inaward     = sArray[0].ToString();
                string inaward_sql = "INSERT INTO AwardList(award,employee_dept,employee_name,employee_no,pubdate) VALUES('" + AwardName + "','" + sArray[1].ToString() + "','" + sArray[2].ToString() + "','" + sArray[3].ToString() + "','" + dt.ToString("yyyyMMddHHmmss") + "')";
                odCommand.CommandText = "update seedlist set award_flag = '1'  where id = " + inaward;
                odCommand.ExecuteNonQuery();
                odCommand.CommandText = inaward_sql;
                odCommand.ExecuteNonQuery();
                SeedsList.Items.Clear();
                odCommand.CommandText = "select id,employee_dept,employee_name,employee_no from Seedlist where award_flag = '0' and left(employee_no,1) in ('0','6','8') order by id asc";
                OleDbDataReader odrReader = odCommand.ExecuteReader();
                while (odrReader.Read())
                {
                    SeedsList.Items.Add(odrReader[0].ToString() + ";" + odrReader[1].ToString() + ";" + odrReader[2].ToString() + ";" + odrReader[3].ToString());
                }
                odrReader.Close();
                odcConnection.Close();
            }
        }
Пример #32
0
        // RNG'd salt.
        public static string GenerateSalt()
        {
            var rng  = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var salt = new byte[8];

            rng.GetBytes(salt);
            return(Convert.ToBase64String(salt));
        }
Пример #33
0
        private static byte[] CreateSalt(int saltLength)
        {
            var buffer = new byte[saltLength];
            var rng    = new System.Security.Cryptography.RNGCryptoServiceProvider();

            rng.GetBytes(buffer);
            return(buffer);
        }
Пример #34
0
        public static String GenerarSal()
        {
            var random = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var bytes  = new byte[6];

            random.GetBytes(bytes);
            return(Convert.ToBase64String(bytes));
        }
            static string GetNonceAsHexDigitString(int lengthInBytes)
            {
                var rng   = new System.Security.Cryptography.RNGCryptoServiceProvider();
                var bytes = new byte[lengthInBytes];

                rng.GetBytes(bytes);
                return(ToHexDigitString(bytes));
            }
Пример #36
0
        protected string CreateSalt(int size)
        {
            var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var buff = new byte[size];
            rng.GetBytes(buff);

            return Convert.ToBase64String(buff);
        }
Пример #37
0
        public static async Task GetRandomActivationCode(this UserSubscriptions userSubscription)
        {
            var crypto = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var bytes  = new byte[5];

            crypto.GetBytes(bytes);
            userSubscription.ActivationCode = BitConverter.ToString(bytes).Replace("-", string.Empty);
        }
Пример #38
0
        // při kontrole nevytvářím tuto sůl jen si ji načtu z DB
        public string vytvorSul(int velikost)
        {
            var rng  = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var buff = new byte[velikost];

            rng.GetBytes(buff);
            return(Convert.ToBase64String(buff));
        }
Пример #39
0
 public static string CreateSalt(int prmSize)
 {
     System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
     byte[] buffer = null;
     buffer = new byte[prmSize + 1];
     rng.GetBytes(buffer);
     return(Convert.ToBase64String(buffer));
 }
Пример #40
0
        public string CreateSalt(int size)
        {
            var rng  = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var buff = new byte[size];

            rng.GetBytes(buff);
            return(Convert.ToBase64String(buff));
        }
Пример #41
0
 public static Token GenerateToken()
 {
     byte[] tokenByte = new byte[95];
     System.Security.Cryptography.RNGCryptoServiceProvider rng =
         new System.Security.Cryptography.RNGCryptoServiceProvider();
     rng.GetBytes(tokenByte);
     return(new Token(tokenByte));
 }
Пример #42
0
 public string CreateSalt()
 {
     int size = 10;//new Random().Next(10, 15);
     var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
     var buff = new byte[size];
     rng.GetBytes(buff);
     return Convert.ToBase64String(buff);
 }
Пример #43
0
        private static string GenerateAuthString()
        {
            using var provider = new System.Security.Cryptography.RNGCryptoServiceProvider();
            byte[] bytes = new byte[16];

            provider.GetBytes(bytes);
            return(new Guid(bytes).ToString());
        }
Пример #44
0
        public string CreateSalt(int size)
        {
            var rng  = new System.Security.Cryptography.RNGCryptoServiceProvider(); //Skapar upp en ny "Random generator" från security namespase.
            var buff = new byte[size];                                              //Skapar upp en array med längden från inparametern.

            rng.GetBytes(buff);                                                     //Random genererar bytes i arrayen
            return(Convert.ToBase64String(buff));                                   //Konverterar och returnerar det nu färdiga saltet.
        }
Пример #45
0
 public static int GetRandomNumber(int min, int max)
 {
     System.Security.Cryptography.RNGCryptoServiceProvider rng =
         new System.Security.Cryptography.RNGCryptoServiceProvider();
     byte[] buffer = new byte[4];
     rng.GetBytes(buffer);
     int result = BitConverter.ToInt32(buffer, 0);
     return new System.Random(result).Next(min, max);
 }
Пример #46
0
        public static byte[] GetRandomBytes(int length)
        {
            var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var buffer = new byte[length];

            rng.GetBytes(buffer);

            return buffer;
        }
Пример #47
0
        /// <summary>
        /// Initialize the class
        /// </summary>
        public SecureDelete()
        {
            // get random buffer
            using (System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
                rng.GetBytes(_rndBuffer);

            // create reverse random buffer
            Buffer.BlockCopy(_rndBuffer, 0, _revBuffer, 0, _revBuffer.Length);
            Array.Reverse(_revBuffer);
        }
Пример #48
0
 /// <summary>
 /// 获取线程级随机数
 /// </summary>
 /// <returns></returns>
 public static Random Random()
 {
     var bytes = new byte[4];
     var rng =
         new System.Security.Cryptography.RNGCryptoServiceProvider();
     rng.GetBytes(bytes);
     var seed = BitConverter.ToInt32(bytes, 0);
     var tick = DateTime.Now.Ticks + (seed);
     return new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32));
 }
Пример #49
0
        public static string createRandomString()
        {
            //create Random Number Generator
            var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();

            //create random string
            byte[] randomBytes = new byte[32];
            rng.GetBytes (randomBytes);

            return byteArrayToHexString (randomBytes);
        }
Пример #50
0
 public static System.String GetRandomString(System.Int32 length)
 {
     System.Byte[] seedBuffer = new System.Byte[4];
     using (var rngCryptoServiceProvider = new System.Security.Cryptography.RNGCryptoServiceProvider())
     {
         rngCryptoServiceProvider.GetBytes(seedBuffer);
         System.String chars = "-abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ";
         System.Random random = new System.Random(System.BitConverter.ToInt32(seedBuffer, 0));
         return new System.String(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());
     }
 }
Пример #51
0
        public static int secRand()
        {
            byte[] randByte = new byte[4];
            System.Security.Cryptography.RNGCryptoServiceProvider secRand = new System.Security.Cryptography.RNGCryptoServiceProvider();
            secRand.GetBytes(randByte);
            int seed = ((randByte[0] & 0x7f) << 24 |
                randByte[1] << 16 |
                randByte[2] << 8 |
                randByte[3]);

            return seed;
        }
Пример #52
0
 public void SaveAccessKey(AccessKey accessKey, TObjectState state)
 {
     if (accessKey.OrganisationID == 0)
     {
         accessKey.OrganisationID = DataAccessFactory.AccessKeys.GenerateOrganisationID();
     }
     if ((state == TObjectState.Add) && string.IsNullOrEmpty(accessKey.Key))
     {
         byte[] secretkey = new Byte[64];
         System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
         Model.AccessKey existingTenantAccessKey;
         do
         {
             rng.GetBytes(secretkey);
             accessKey.Key = StringUtils.Encode(secretkey);
             existingTenantAccessKey = DataAccessFactory.AccessKeys.GetAccessKey(accessKey.Key);
         } while (existingTenantAccessKey != null);
         rng.GetBytes(secretkey);
         accessKey.Secret = StringUtils.Encode(secretkey);
     }
     DataAccessFactory.AccessKeys.SaveAccessKey(accessKey, state);
 }
Пример #53
0
        public string createHashedPassword(string pwd)
        {
            var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
                byte[] salt = new byte[8];
                rng.GetBytes(salt); // Create an 8 byte salt
                var iterations = 1000; // Choose a value that will perform well given your hardware.
                var pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(pwd, salt, iterations);
                var hash = pbkdf2.GetBytes(60); // Get 60 bytes for the hash

                var str = System.Text.Encoding.Default.GetString(hash);

                Console.WriteLine(str);

                return hash.ToString();
        }
Пример #54
0
        static String BuildAuthenticationHeader()
        {
            System.Security.Cryptography.RNGCryptoServiceProvider provider = new System.Security.Cryptography.RNGCryptoServiceProvider();

            byte[] bytes = new byte[20];
            provider.GetBytes(bytes);
            String nonce = System.Convert.ToBase64String(bytes);
            String created = String.Format("{0:yyyy-MM-dd'T'HH:mm:sszz00}", DateTime.Now);
            byte[] intermediateBytes = System.Text.UTF8Encoding.UTF8.GetBytes(nonce + created + apiKey);
            byte[] passwordDigestHash = System.Security.Cryptography.SHA256.Create().ComputeHash(intermediateBytes);

            String passwordDigest = System.Convert.ToBase64String(passwordDigestHash, Base64FormattingOptions.None);

            return "UsernameToken Username=\"" + apiUsername + "\",PasswordDigest=\"" + passwordDigest + "\",Nonce=\"" + nonce + "\",Created=\"" + created + "\"";
        }
        public static string ToHashString(this byte [] bytes, bool numeric = false)
        {
            using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
            {
                rng.GetBytes(bytes);
                if (numeric)
                {
                    bytes.UpdateEach((b) => (byte)(byteMod(b, 0xA) + OFFSET));
                    return System.Text.Encoding.UTF8.GetString(bytes);
                }

                bytes.UpdateEach((b) => (byte)(byteMod(b, MOD) + OFFSET));
                bytes.UpdateEach((b) => (byte)((b > BREAK) ? b + ALPHA_OFFSET : b));
                return System.Text.Encoding.UTF8.GetString(bytes);
            }
        }
Пример #56
0
        /// <summary>
        /// 参考:msdn上的RNGCryptoServiceProvider例子
        /// </summary>
        /// <param name="numSeeds"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        private static int NextRandom(int numSeeds, int length)
        {
            // Create a byte array to hold the random value.
            byte[] randomNumber = new byte[length];
            // Create a new instance of the RNGCryptoServiceProvider.
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            // Fill the array with a random value.
            rng.GetBytes(randomNumber);
            // Convert the byte to an uint value to make the modulus operation easier.
            uint randomResult = 0x0;
            for (int i = 0; i < length; i++)
            {
                randomResult |= ((uint)randomNumber[i] << ((length - 1 - i) * 8));
            }

            return (int)(randomResult % numSeeds) + 1;
        }
Пример #57
0
 private static int Next(int numSeeds, int length)
 {
     // Create a byte array to hold the random value.
     byte[] buffer = new byte[length];
     // Create a new instance of the RNGCryptoServiceProvider.
     System.Security.Cryptography.RNGCryptoServiceProvider Gen = new System.Security.Cryptography.RNGCryptoServiceProvider();
     // Fill the array with a random value.
     Gen.GetBytes(buffer);
     // Convert the byte to an uint value to make the modulus operation easier.
     uint randomResult = 0x0;//这里用uint作为生成的随机数
     for (int i = 0; i < length; i++)
     {
         randomResult |= ((uint)buffer[i] << ((length - 1 - i) * 8));
     }
     // Return the random number mod the number
     // of sides. The possible values are zero-based
     return (int)(randomResult % numSeeds);
 }
Пример #58
0
        //Untested
        public string ScrambledAlphabet()
        {
            string copy = new string(alphabet);

            StringBuilder sb = new StringBuilder();
            byte[] tokenData = new byte[2];
            using (System.Security.Cryptography.RandomNumberGenerator rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
            {
                for (int i = 0; i < alphabet.Length; i++)
                {
                    rng.GetBytes(tokenData);

                    int value = (int)(BitConverter.ToUInt16(tokenData, 0) % copy.Length);

                    sb.Append(copy[value]);

                    copy = copy.Replace(copy[value].ToString(), "");
                }
            }
            return sb.ToString();
        }
Пример #59
0
 private static int Next(int numSeeds, int length)
 {
     byte[] buffer = new byte[length];
     System.Security.Cryptography.RNGCryptoServiceProvider Gen =
         new System.Security.Cryptography.RNGCryptoServiceProvider();
     Gen.GetBytes(buffer);
     uint randomResult = 0x0; //这里用uint作为生成的随机数  
     for (int i = 0; i < length; i++)
     {
         randomResult |= ((uint) buffer[i] << ((length - 1 - i)*8));
     }
     return (int) (randomResult%numSeeds);
 }
Пример #60
0
 //use the RNGCryptoServiceProvider class to get a random bytes array of assigned length
 private static byte[] GetRandByte( int length )
 {
     System.Security.Cryptography.RNGCryptoServiceProvider rndGenerator = new System.Security.Cryptography.RNGCryptoServiceProvider();
     byte[] btResult = new byte[ length ];
     rndGenerator.GetBytes( btResult );
     return btResult;
 }