开源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(一)综合介绍 ...
随机推荐
- ThinkPhp学习12
原文:ThinkPhp学习12 二.输出模板内容 (重点) a.display 1.display中没有参数 $this->display(); 2.可以带参数 $this ...
- hdu4055 Number String
Number String Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Tota ...
- 字符编码详解 good
字符编码详解 字符编码详解
- ORACLE RMAN介绍
本地连接: $ rman target / or $ rman target / nocatalog 远程连接: $ rman target sys/sys@sky RMAN命令执行方式: 1.单条 ...
- 【矩阵乘】【NOI 2012】【cogs963】随机数生成器
963. [NOI2012] 随机数生成器 ★★ 输入文件:randoma.in 输出文件:randoma.out 简单对照 时间限制:1 s 内存限制:128 MB **[问题描写叙述] 栋栋近期迷 ...
- web开发性能优化---用户体验篇
怎样从技术角度怎样增强用户体验.都是非常多平台都在做的事情,依据个人实际经验碰到几种体验做下总结. 1.降低页面刷新白屏 适当使用ajax技术.改善刷新白屏现象. 2.信息提醒,邮件.站内信.短信在购 ...
- hdu4283(区间dp)
题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=4283 题意:有一个队列,每个人有一个愤怒值D,如果他是第K个上场,不开心指数就为(K-1)*D.但是边 ...
- NOJ1184 失落的邮票 哈希表
意甲冠军 我们共收集N邮票.现在失去了2张,剩下N-2张-..原集邮收集了所有对.因此,找到什么两枚邮票是一个.它们输出. (确定缺少邮票是不一样的) 思路 由于编号比較大,能够用hash表压缩成数组 ...
- Linq 数据操作,两个数组求差、交集、并集
int[] a = { 1, 2, 3, 4, 5, 6, 7 }; int[] b = { 4, 5, 6, 7, 8, 9, 10 }; int[] c = { 1, 2, 3, 3, 4, 1, ...
- 利用try-catch判断变量是已声明未声明还是未赋值
原文 利用try-catch判断变量是已声明未声明还是未赋值 这篇文章主要介绍了利用try-catch判断变量是已声明未赋值还是未声明,需要的朋友可以参考下 目的是如果一个变量是已声明未赋值,就可以直 ...