【原创】开源Math.NET基础数学类库使用(14)C#生成安全的随机数
本博客所有文章分类的总目录:【总目录】本博客博文总目录-实时更新
开源Math.NET基础数学类库使用总目录:【目录】开源Math.NET基础数学类库使用总目录
前言
真正意义上的随机数(或者随机事件)在某次产生过程中是按照实验过程中表现的分布概率随机产生的,其结果是不可预测的,是不可见的。而计算机中的随机函数是按照一定算法模拟产生的,其结果是确定的,是可见的。我们可以这样认为这个可预见的结果其出现的概率是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#生成安全的随机数的更多相关文章
- 开源Math.NET基础数学类库使用(14)C#生成安全的随机数
原文:[原创]开源Math.NET基础数学类库使用(14)C#生成安全的随机数 本博客所有文章分类的总目录:http://www.cnblogs.com/asxinyu/ ...
- 【目录】开源Math.NET基础数学类库使用总目录
本博客所有文章分类的总目录链接:[总目录]本博客博文总目录-实时更新 1.开源Math.NET数学组件文章 1.开源Math.NET基础数学类库使用(01)综合介绍 2.开源Math.NET ...
- 【原创】开源Math.NET基础数学类库使用(02)矩阵向量计算
本博客所有文章分类的总目录:[总目录]本博客博文总目录-实时更新 开源Math.NET基础数学类库使用总目录:[目录]开源Math.NET基础数学类库使用总目录 前言 ...
- 【原创】开源Math.NET基础数学类库使用(01)综合介绍
本博客所有文章分类的总目录:[总目录]本博客博文总目录-实时更新 开源Math.NET基础数学类库使用总目录:[目录]开源Math.NET基础数学类库使用总目录 前言 ...
- 【原创】开源Math.NET基础数学类库使用(03)C#解析Matlab的mat格式
本博客所有文章分类的总目录:[总目录]本博客博文总目录-实时更新 开源Math.NET基础数学类库使用总目录:[目录]开源Math.NET基础数学类库使用总目录 前言 ...
- 【原创】开源Math.NET基础数学类库使用(04)C#解析Matrix Marke数据格式
本博客所有文章分类的总目录:[总目录]本博客博文总目录-实时更新 开源Math.NET基础数学类库使用总目录:[目录]开源Math.NET基础数学类库使用总目录 前言 ...
- 【原创】开源Math.NET基础数学类库使用(05)C#解析Delimited Formats数据格式
本博客所有文章分类的总目录:[总目录]本博客博文总目录-实时更新 开源Math.NET基础数学类库使用总目录:[目录]开源Math.NET基础数学类库使用总目录 前言 ...
- 【原创】开源Math.NET基础数学类库使用(06)直接求解线性方程组
本博客所有文章分类的总目录:[总目录]本博客博文总目录-实时更新 开源Math.NET基础数学类库使用总目录:[目录]开源Math.NET基础数学类库使用总目录 前言 ...
- 【原创】开源Math.NET基础数学类库使用(07)常用的数学物理常数
本博客所有文章分类的总目录:[总目录]本博客博文总目录-实时更新 开源Math.NET基础数学类库使用总目录:[目录]开源Math.NET基础数学类库使用总目录 1.前 ...
随机推荐
- [译]App Framework 2.1 (2)之 Get Involved
App Framework API 第二篇 原文在此:http://app-framework-software.intel.com/documentation.php#intro/involved ...
- django _meta方法
models.Book._meta.'concrete_model': <class 'books.models.Book'> models.Book._meta.'related_fke ...
- 在php中定义常量时,const与define的区别?
问]在php中定义常量时,const与define的区别? [答]使用const使得代码简单易读,const本身就是一个语言结构,而define是一个函数.另外const在编译时要比define快很 ...
- java分享第二十天(build.xml的语法及写法)
通常情况下,Ant构建文件build.xml应该在项目的基础目录.可以自由使用其他文件名或将构建文件中其他位置.在本练习中,创建一个名为build.xml 在电脑的任何地方的文件. <?xml ...
- normalize.css入门和下载
CSS Reset 是革命党,CSS Reset 里最激进那一派提倡不管你小子有用没用,通通给我脱了那身衣服,凭什么你 body 出生就穿一圈 margin,凭什么你姓 h 的比别人吃得胖,凭什么你 ...
- mark
*求数根公式:a的数根b = (a-1) % 9 + 1; *约瑟环问题:f1 = 0; 第i个(i>1),f = (f+m) %i;
- effectiveC++ 内存管理 学习笔记
1.尽量使用初始化列表而不要再构造函数里赋值,初始化顺序和声明的顺序一致,一些类型如const,引用等,必须使用初始化.对于非内部数据类型成员对象应当采用初始化表,以获取更高的效率.example:B ...
- 50个jQuery插件可将你的网站带到另一个高度
Web领域一直在发生变化并且其边界在过去的每一天都在发生变化(甚至不能以小时为计),随着其边界的扩展取得了许多新发展.在这些进步之中,开发者的不断工作创造了更大和更好的脚本,这些脚本以插件方式带来更好 ...
- web app iphone4 iphone5 iphone6 响应式布局 适配代码
在网页中,pixel与point比值称为device-pixel-ratio,普通设备都是1,iPhone 4是2,有些Android机型是1.5.] 那么-webkit-min-device-pix ...
- HTML5、canvas颜色拾取器
效果图: 代码: <!doctype html> <html lang="en"> <head> <meta charset=" ...