开源Math.NET基础数学类库使用(14)C#生成安全的随机数
原文:【原创】开源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#生成安全的随机数的更多相关文章
- 【原创】开源Math.NET基础数学类库使用(14)C#生成安全的随机数
本博客所有文章分类的总目录:[总目录]本博客博文总目录-实时更新 开源Math.NET基础数学类库使用总目录:[目录]开源Math.NET基础数学类库使用总目录 前言 ...
- 【目录】开源Math.NET基础数学类库使用总目录
本博客所有文章分类的总目录链接:[总目录]本博客博文总目录-实时更新 1.开源Math.NET数学组件文章 1.开源Math.NET基础数学类库使用(01)综合介绍 2.开源Math.NET ...
- 【原创】开源Math.NET基础数学类库使用(02)矩阵向量计算
本博客所有文章分类的总目录:[总目录]本博客博文总目录-实时更新 开源Math.NET基础数学类库使用总目录:[目录]开源Math.NET基础数学类库使用总目录 前言 ...
- 开源Math.NET基础数学类库使用(11)C#计算相关系数
阅读目录 前言 1.Math.NET计算相关系数的类 2.Correlation的实现 3.使用案例 4.资源 本博客所有文章分类的总目录:[总目录]本博客博文总目录-实 ...
- 开源Math.NET基础数学类库使用(06)数值分析之线性方程组直接求解
原文:[原创]开源Math.NET基础数学类库使用(06)数值分析之线性方程组直接求解 开源Math.NET基础数学类库使用系列文章总目录: 1.开源.NET基础数学计算组件Math.NET(一) ...
- 开源Math.NET基础数学类库使用(05)C#解析Delimited Formats数据格式
原文:[原创]开源Math.NET基础数学类库使用(05)C#解析Delimited Formats数据格式 开源Math.NET基础数学类库使用系列文章总目录: 1.开源.NET基础数学计算组件 ...
- 开源Math.NET基础数学类库使用(04)C#解析Matrix Marke数据格式
原文:[原创]开源Math.NET基础数学类库使用(04)C#解析Matrix Marke数据格式 开源Math.NET基础数学类库使用系列文章总目录: 1.开源.NET基础数学计算组件Math. ...
- 开源Math.NET基础数学类库使用(03)C#解析Matlab的mat格式
原文:[原创]开源Math.NET基础数学类库使用(03)C#解析Matlab的mat格式 开源Math.NET基础数学类库使用系列文章总目录: 1.开源.NET基础数学计算组件Math.NET( ...
- 开源Math.NET基础数学类库使用(02)矩阵向量计算
原文:[原创]开源Math.NET基础数学类库使用(02)矩阵向量计算 开源Math.NET基础数学类库使用系列文章总目录: 1.开源.NET基础数学计算组件Math.NET(一)综合介绍 ...
随机推荐
- uva 10655 - Contemplation! Algebra(矩阵高速幂)
题目连接:uva 10655 - Contemplation! Algebra 题目大意:输入非负整数,p.q,n,求an+bn的值,当中a和b满足a+b=p,ab=q,注意a和b不一定是实数. 解题 ...
- Missile:双状态DP
题目 描写叙述 Long , long ago ,country A invented a missile system to destroy the missiles from their enem ...
- a++为啥不能用作左值
原地址:http://wy892648414.blog.163.com/blog/static/212212135201378496591/ 1)首先说左值和右值的定义: 变量和文字常量都有存储区,并 ...
- 《Java程序代理器》- java桌面程序运行的前端启动框架
虽说让java直接在桌面运行,有很多方法,但最简单的还是有个exe双击执行 要java执行就得有虚拟机,但原本的虚拟机文件体积太大,不方便随同打包,精简的虚拟机功能又不全,指不定什么时候报错 所以正规 ...
- hdu1532(最大流)
传送门:Drainage Ditches 题意:给出n个河流,m个点,以及每个河流的流量,求从1到m点的最大流量. 分析:网络流入门题,第一次写按照白书上毫无优化的Ford_fulkerson算法,先 ...
- Patch to solve sqlite3_int64 error when building Python 2.7.3 on RHEL/CentOS
Patch to solve sqlite3_int64 error when building Python 2.7.3 on RHEL/CentOS Patch to solve sqlite3_ ...
- poj1836--Alignment(dp,最长上升子序列变形)
Alignment Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 13319 Accepted: 4282 Descri ...
- SWT中的多线程(Invalid thread access)
最近在学习swt的东西,遇到一个问题,特转录如下. SWT异常: org.eclipse.swt.SWTException: Invalid thread access 在创建SWT界面的线程之外的线 ...
- 陈一舟《情系人人》:先搞钱,再搞人才_DoNews-IT门户-移动互联网新闻-电子商务新闻-游戏新闻-风险投资新闻-IT社交网络社区
陈一舟<情系人人>:先搞钱,再搞人才_DoNews-IT门户-移动互联网新闻-电子商务新闻-游戏新闻-风险投资新闻-IT社交网络社区 陈一舟<情系人人>:先搞钱,再搞人才
- 公布windows的"Universal Apps" Unity3D游戏
转载请注明出处:http://blog.csdn.net/u010019717 更全的内容请看我的游戏蛮牛地址:http://www.unitymanual.com/space-uid-18602.h ...