开源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(一)综合介绍 ...
随机推荐
- 【MFC两种视频图像採集方法】DirectShow与Opencv
效果图: DirectShow採集核心代码: 创建线程调用该函数,採集图像通过x264解码封装rtmp协议包.推送至FMSserver,可实现视频直播 UINT __stdcall StartVide ...
- Mybatis在oracle、mysql、db2、sql server的like模糊查询
<!-- oracle --> <select id="searchUserBySearchName" parameterType="java.lang ...
- WOJ 1020
#include<stdio.h> #include<stdlib.h> int main() { int n,m; int *num,*link; int i,j,t,k=0 ...
- 用jsp写注冊页面
包含单选框.多选框.session的应用,页面自己主动跳转,中文乱码的处理,入门级 对于中文乱码的处理,注意几点:注冊页面数据提交方式为post不能忘了写,页面编码方式为gbk,处理提交信息的doRe ...
- MySQL的Master/Slave群集安装和配置
本文介绍MySQL的Master/Slave群集安装和配置,版本号安装最新的稳定版GA 5.6.19. 为了支持有限HA.我们用Master/Slave读写简单孤立的集群.有限HA这是当Master不 ...
- OCA读书笔记(13) - 性能管理
使用EM监控性能使用自动内存管理(AMM)使用Memory Advisor分配内存查看性能相关动态视图诊断无效的和不可用的对象 创建问题SQLsqlplus / as sysdbaconn scott ...
- hdu1495之经典搜索
非常可乐 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submi ...
- Android开发人员必知的开发资源
developer.android.com 官方开发人员网站推荐资源 在动手编写第一个 Android 应用之前,用心读一读 Android Design 章节.尤其是以下的这些文章: Devices ...
- UVA1455 - Kingdom(并查集 + 线段树)
UVA1455 - Kingdom(并查集 + 线段树) 题目链接 题目大意:一个平面内,给你n个整数点,两种类型的操作:road x y 把city x 和city y连接起来,line fnum ...
- hbase基本概念和hbase shell经常使用命令使用方法
HBase是一个分布式的.面向列的开源数据库,源于google的一篇论文<bigtable:一个结构化数据的分布式存储系统>.HBase是Google Bigtable的开源实现,它利用H ...