1 /******************************************************************************/
2 /* SlunkCrypt, by LoRd_MuldeR <MuldeR2@GMX.de> */
3 /* This work has been released under the CC0 1.0 Universal license! */
4 /******************************************************************************/
8 using System.Security.Cryptography;
10 namespace com.muldersoft.slunkcrypt.gui.utils
12 class SecureRandom : IDisposable
14 private volatile bool m_disposed = false;
16 private readonly RNGCryptoServiceProvider m_provider;
17 private readonly byte[] m_tempBuffer = new byte[256];
19 private int m_offset = int.MaxValue;
21 // =============================================================================
23 // =============================================================================
29 m_provider = new RNGCryptoServiceProvider();
33 throw new IOException("Failed to create RNGCryptoServiceProvider instance!", e);
42 // =============================================================================
44 // =============================================================================
46 public int NextInt32()
50 throw new ObjectDisposedException("SecureRandom");
52 EnsureBytesAvailable(sizeof(int));
53 int value = BitConverter.ToInt32(m_tempBuffer, m_offset);
54 m_offset += sizeof(int);
58 public uint NextUInt32()
62 throw new ObjectDisposedException("SecureRandom");
64 EnsureBytesAvailable(sizeof(uint));
65 uint value = BitConverter.ToUInt32(m_tempBuffer, m_offset);
66 m_offset += sizeof(uint);
70 public long NextInt64()
74 throw new ObjectDisposedException("SecureRandom");
76 EnsureBytesAvailable(sizeof(long));
77 long value = BitConverter.ToInt64(m_tempBuffer, m_offset);
78 m_offset += sizeof(long);
82 public ulong NextUInt64()
86 throw new ObjectDisposedException("SecureRandom");
88 EnsureBytesAvailable(sizeof(ulong));
89 ulong value = BitConverter.ToUInt64(m_tempBuffer, m_offset);
90 m_offset += sizeof(ulong);
99 GC.SuppressFinalize(this);
102 FillArray(m_tempBuffer, 0);
108 m_provider.Dispose();
115 // =============================================================================
117 // =============================================================================
119 private void EnsureBytesAvailable(int length)
121 if ((m_offset >= m_tempBuffer.Length) || ((m_tempBuffer.Length - m_offset) < length))
125 m_provider.GetBytes(m_tempBuffer);
130 throw new IOException("Failed to generated random bytes!", e);
135 private static void FillArray(byte[] array, byte value)
137 if (!ReferenceEquals(array, null))
139 for (int i = 0; i < array.Length; ++i)