生成安全的用于加密的随机数

            请使用RandomNumberGenerator类,使用该类不会让人猜出你的随机数生成规律,也可用其派生类RNGCryptoServiceProvider类来生成随机数,例如:
            byte[] randomBytes = new byte[4];

            for (int i = 0; i < 100; i++)
            {
                RandomNumberGenerator rand;

                rand = RandomNumberGenerator.Create();
                rand.GetBytes(randomBytes);
                int randomInt = BitConverter.ToInt32(randomBytes, 0);

                Response.Write(randomInt .ToString("N") + "<br/>");
            }

            如果要创建安全的GUID请使用以下方法:

            byte[] randomBytes = new byte[16];

            for (int i = 0; i < 100; i++)
            {
                RandomNumberGenerator rand;

                rand = RandomNumberGenerator.Create();
                rand.GetBytes(randomBytes);

                Guid randomGuid = new Guid(randomBytes);

                Response.Write(randomGuid.ToString("N") + "<br/>");
            }

            但以上介绍的两个类比Random慢了至少8倍。

posted on 2009-08-06 22:17  维晟  阅读(592)  评论(0编辑  收藏  举报

导航