Refine RNG usage

- Create instance once, bind it to ShadowsocksController

Signed-off-by: Syrone Wong <wong.syrone@gmail.com>
This commit is contained in:
Syrone Wong
2016-11-09 10:28:50 +08:00
parent c908caa584
commit 8fcb66b6ff
5 changed files with 52 additions and 6 deletions
+1 -6
View File
@@ -1,8 +1,6 @@
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Net;
@@ -237,10 +235,7 @@ namespace Shadowsocks.Encryption
protected static void randBytes(byte[] buf, int length)
{
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
rng.GetBytes(buf, 0, length);
}
RNG.GetBytes(buf, length);
}
public override void Encrypt(byte[] buf, int length, byte[] outbuf, out int outlength)
+44
View File
@@ -0,0 +1,44 @@
using System;
using System.Security.Cryptography;
namespace Shadowsocks.Encryption
{
public static class RNG
{
private static RNGCryptoServiceProvider _rng = null;
public static void Init()
{
if (_rng == null)
_rng = new RNGCryptoServiceProvider();
}
public static void Close()
{
if (_rng == null) return;
_rng.Dispose();
_rng = null;
}
public static void Reload()
{
Close();
Init();
}
public static void GetBytes(byte[] buf, int len)
{
try
{
_rng.GetBytes(buf, 0, len);
}
catch (Exception)
{
// the backup way
byte[] tmp = new byte[len];
_rng.GetBytes(tmp);
Buffer.BlockCopy(tmp, 0, buf, 0, len);
}
}
}
}