原文:【原创】开源Math.NET基础数学类库使用(14)C#生成安全的随机数

               本博客所有文章分类的总目录:http://www.cnblogs.com/asxinyu/p/4288836.html

开源Math.NET基础数学类库使用总目录:http://www.cnblogs.com/asxinyu/p/4329737.html

前言

  真正意义上的随机数(或者随机事件)在某次产生过程中是按照实验过程中表现的分布概率随机产生的,其结果是不可预测的,是不可见的。而计算机中的随机函数是按照一定算法模拟产生的,其结果是确定的,是可见的。我们可以这样认为这个可预见的结果其出现的概率是100%。所以用计算机随机函数所产生的“随机数”并不随机,是伪随机数。伪随机数的作用在开发中的使用非常常见,因此.NET在System命名空间,提供了一个简单的Random随机数生成类型。但这个类型并不能满足所有的需求,本节开始就将陆续介绍Math.NET中有关随机数的扩展以及其他伪随机生成算法编写的随机数生成器。

  今天要介绍的是Math.NET中利用C#快速的生成安全的随机数。

  如果本文资源或者显示有问题,请参考 本文原文地址http://www.cnblogs.com/asxinyu/p/4301554.html

1.什么是安全的随机数?

  Math.NET在MathNet.Numerics.Random命名空间中的实现了一个基于System.Security.Cryptography.RandomNumberGenerator的安全随机数发生器。

  实际使用中,很多人对这个不在意,那么Random和安全的随机数有什么区别,什么是安全的随机数呢?

  在许多类型软件的开发过程中,都要使用随机数。例如纸牌的分发、密钥的生成等等。随机数至少应该具备两个条件:
1. 数字序列在统计上是随机的。
2. 不能通过已知序列来推算后面未知的序列。
  只有实际物理过程才是真正随机的。而一般来说,计算机是很确定的,它很难得到真正的随机数。所以计算机利用设计好的一套算法,再由用户提供一个种子值,得出被称为“伪随机数”的数字序列,这就是我们平时所使用的随机数。
这种伪随机数字足以满足一般的应用,但它不适用于加密等领域,因为它具有弱点:
1. 伪随机数是周期性的,当它们足够多时,会重复数字序列。
2. 如果提供相同的算法和相同的种子值,将会得出完全一样的随机数序列。
3. 可以使用逆向工程,猜测算法与种子值,以便推算后面所有的随机数列。

  对于这个随机数发生器,本人深有体会,在研究生期间,我的研究方向就是 流密码,其中一个主要的课题就是 如何生成高安全性能的随机数发生器,研究了2年吧,用的是 混沌生成伪随机数,用于加密算法。.NET自带的Random类虽然能满足常规要求,但在一些高安全场合,是不建议使用的,因为其生成的随机数是可以预测和破解的。所以在.net中也提供了一个用于加密的RandomNumberGenerator。Math.NET就是该类的一个翻版。虽然其效率要比Random更低,但是更安全。

2..NET中使用RNGCryptoServiceProvider的例子

 RNGCryptoServiceProvider的使用可以参考一个MSDN的例子:  

 using System;
using System.IO;
using System.Text;
using System.Security.Cryptography; class RNGCSP
{
public static void Main()
{
for(int x = ; x <= ; x++)
Console.WriteLine(RollDice());
} public static int RollDice(int NumSides)
{
byte[] randomNumber = new byte[]; RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider(); Gen.GetBytes(randomNumber); int rand = Convert.ToInt32(randomNumber[]); return rand % NumSides + ;
}
}

3.Math.NET中安全随机数类的实现

  随机数生成器算法的实现基本都类似,这里就看一下Math.NET中安全的随机数生成器CryptoRandomSource类的实现:

 public sealed class CryptoRandomSource : RandomSource, IDisposable
{
const double Reciprocal = 1.0/uint.MaxValue;
readonly RandomNumberGenerator _crypto; /// <summary>
/// Construct a new random number generator with a random seed.
/// </summary>
/// <remarks>Uses <see cref="System.Security.Cryptography.RNGCryptoServiceProvider"/> and uses the value of
/// <see cref="Control.ThreadSafeRandomNumberGenerators"/> to set whether the instance is thread safe.</remarks>
public CryptoRandomSource()
{
_crypto = new RNGCryptoServiceProvider();
} /// <summary>
/// Construct a new random number generator with random seed.
/// </summary>
/// <param name="rng">The <see cref="RandomNumberGenerator"/> to use.</param>
/// <remarks>Uses the value of <see cref="Control.ThreadSafeRandomNumberGenerators"/> to set whether the instance is thread safe.</remarks>
public CryptoRandomSource(RandomNumberGenerator rng)
{
_crypto = rng;
} /// <summary>
/// Construct a new random number generator with random seed.
/// </summary>
/// <remarks>Uses <see cref="System.Security.Cryptography.RNGCryptoServiceProvider"/></remarks>
/// <param name="threadSafe">if set to <c>true</c> , the class is thread safe.</param>
public CryptoRandomSource(bool threadSafe) : base(threadSafe)
{
_crypto = new RNGCryptoServiceProvider();
} /// <summary>
/// Construct a new random number generator with random seed.
/// </summary>
/// <param name="rng">The <see cref="RandomNumberGenerator"/> to use.</param>
/// <param name="threadSafe">if set to <c>true</c> , the class is thread safe.</param>
public CryptoRandomSource(RandomNumberGenerator rng, bool threadSafe) : base(threadSafe)
{
_crypto = rng;
} /// <summary>
/// Returns a random number between 0.0 and 1.0.
/// </summary>
/// <returns>
/// A double-precision floating point number greater than or equal to 0.0, and less than 1.0.
/// </returns>
protected override sealed double DoSample()
{
var bytes = new byte[];
_crypto.GetBytes(bytes);
return BitConverter.ToUInt32(bytes, )*Reciprocal;
} public void Dispose()
{
#if !NET35
_crypto.Dispose();
#endif
} /// <summary>
/// Fills an array with random numbers greater than or equal to 0.0 and less than 1.0.
/// </summary>
/// <remarks>Supports being called in parallel from multiple threads.</remarks>
public static void Doubles(double[] values)
{
var bytes = new byte[values.Length*]; #if !NET35
using (var rnd = new RNGCryptoServiceProvider())
{
rnd.GetBytes(bytes);
}
#else
var rnd = new RNGCryptoServiceProvider();
rnd.GetBytes(bytes);
#endif for (int i = ; i < values.Length; i++)
{
values[i] = BitConverter.ToUInt32(bytes, i*)*Reciprocal;
}
} /// <summary>
/// Returns an array of random numbers greater than or equal to 0.0 and less than 1.0.
/// </summary>
/// <remarks>Supports being called in parallel from multiple threads.</remarks>
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public static double[] Doubles(int length)
{
var data = new double[length];
Doubles(data);
return data;
} /// <summary>
/// Returns an infinite sequence of random numbers greater than or equal to 0.0 and less than 1.0.
/// </summary>
/// <remarks>Supports being called in parallel from multiple threads.</remarks>
public static IEnumerable<double> DoubleSequence()
{
var rnd = new RNGCryptoServiceProvider();
var buffer = new byte[*]; while (true)
{
rnd.GetBytes(buffer);
for (int i = ; i < buffer.Length; i += )
{
yield return BitConverter.ToUInt32(buffer, i)*Reciprocal;
}
}
}
}

4.资源

  源码下载:http://www.cnblogs.com/asxinyu/p/4264638.html

  如果本文资源或者显示有问题,请参考 本文原文地址http://www.cnblogs.com/asxinyu/p/4301519.html

开源Math.NET基础数学类库使用(14)C#生成安全的随机数的更多相关文章

  1. 【原创】开源Math.NET基础数学类库使用(14)C#生成安全的随机数

                   本博客所有文章分类的总目录:[总目录]本博客博文总目录-实时更新  开源Math.NET基础数学类库使用总目录:[目录]开源Math.NET基础数学类库使用总目录 前言 ...

  2. 【目录】开源Math.NET基础数学类库使用总目录

    本博客所有文章分类的总目录链接:[总目录]本博客博文总目录-实时更新  1.开源Math.NET数学组件文章   1.开源Math.NET基础数学类库使用(01)综合介绍   2.开源Math.NET ...

  3. 【原创】开源Math.NET基础数学类库使用(02)矩阵向量计算

                   本博客所有文章分类的总目录:[总目录]本博客博文总目录-实时更新  开源Math.NET基础数学类库使用总目录:[目录]开源Math.NET基础数学类库使用总目录 前言 ...

  4. 开源Math.NET基础数学类库使用(11)C#计算相关系数

    阅读目录 前言 1.Math.NET计算相关系数的类 2.Correlation的实现 3.使用案例 4.资源                本博客所有文章分类的总目录:[总目录]本博客博文总目录-实 ...

  5. 开源Math.NET基础数学类库使用(06)数值分析之线性方程组直接求解

    原文:[原创]开源Math.NET基础数学类库使用(06)数值分析之线性方程组直接求解 开源Math.NET基础数学类库使用系列文章总目录:   1.开源.NET基础数学计算组件Math.NET(一) ...

  6. 开源Math.NET基础数学类库使用(05)C#解析Delimited Formats数据格式

    原文:[原创]开源Math.NET基础数学类库使用(05)C#解析Delimited Formats数据格式 开源Math.NET基础数学类库使用系列文章总目录:   1.开源.NET基础数学计算组件 ...

  7. 开源Math.NET基础数学类库使用(04)C#解析Matrix Marke数据格式

    原文:[原创]开源Math.NET基础数学类库使用(04)C#解析Matrix Marke数据格式 开源Math.NET基础数学类库使用系列文章总目录:   1.开源.NET基础数学计算组件Math. ...

  8. 开源Math.NET基础数学类库使用(03)C#解析Matlab的mat格式

    原文:[原创]开源Math.NET基础数学类库使用(03)C#解析Matlab的mat格式 开源Math.NET基础数学类库使用系列文章总目录:   1.开源.NET基础数学计算组件Math.NET( ...

  9. 开源Math.NET基础数学类库使用(02)矩阵向量计算

    原文:[原创]开源Math.NET基础数学类库使用(02)矩阵向量计算 开源Math.NET基础数学类库使用系列文章总目录:   1.开源.NET基础数学计算组件Math.NET(一)综合介绍    ...

随机推荐

  1. 与众不同 windows phone (21) - Device(设备)之摄像头(拍摄照片, 录制视频)

    原文:与众不同 windows phone (21) - Device(设备)之摄像头(拍摄照片, 录制视频) [索引页][源码下载] 与众不同 windows phone (21) - Device ...

  2. delphi中用代码实现注册Ocx和Dll(有点怪异,使用CallWindowProc来调用指定函数DllRegisterServer)

    在windows系统中,可以通过Regsvr32来实现注册ocx或者dl, 编程时,调用Regsvr32来注册,却不能正常执行.尤其是在Win7系统中,需要管理员身份才能运行. 使用下面的代码则能正常 ...

  3. [Android学习笔记]RelativeLayout的使用

    RelativeLayout是相对布局控件,在屏幕适配的时候非常有用,在此记录一些它的常用属性 第一类:属性值为true或falseandroid:layout_centerHrizontal     ...

  4. HDU/HDOJ 2612 Find a way 双向BFS

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2612 思路:从两个起点出发,有多个终点,求从两个起点同时能到达的终点具有的最小时间,开两个数组分别保存 ...

  5. 无向图的最短路径算法JAVA实现(转)

    一,问题描述 给出一个无向图,指定无向图中某个顶点作为源点.求出图中所有顶点到源点的最短路径. 无向图的最短路径其实是源点到该顶点的最少边的数目. 本文假设图的信息保存在文件中,通过读取文件来构造图. ...

  6. leetcode解析回文子串拆分

    转载请注明来自souldak,微博:@evagle Given a string s, partition s such that every substring of the partition i ...

  7. 超人学院Hadoop大数据技术资源分享

    超人学院Hadoop大数据技术资源分享 http://bbs.superwu.cn/forum.php?mod=viewthread&tid=807&fromuid=645 很多其它精 ...

  8. SVN最有效的方法打基线

    笔者:张克强    在微博上:张克强-敏捷307 2014/7/6 方法一来自于我的一条微博: 组织级scm建一个名为controlled的文件夹,当项目某文档通过评审后,组织级scm从项目文件夹下找 ...

  9. 国内国外MD5在线解密站点

    -http://www.cmd5.com/english.aspx (457,354,352,282) - http://www.md5crack.com - http://www.hashcheck ...

  10. HTTP协议中的短轮询、长轮询、长连接和短连接

    HTTP协议中的短轮询.长轮询.长连接和短连接 引言 最近刚到公司不到一个月,正处于熟悉项目和源码的阶段,因此最近经常会看一些源码.在研究一个项目的时候,源码里面用到了HTTP的长轮询.由于之前没太接 ...