The following demonstrates how to use C# language to download random data from a SwiftRNG device when used with Entropy Server for Windows through a named pipe connection. The following code will only work when running SwiftRNG Entropy Server. This is the recommended way for achieving maximum concurrent speed and performance. Before using the following example, make sure the SwiftRNG device is plugged into one of USB ports available.
A sample source code for retrieving random values from SwiftRNG device when using Entropy Server for Windows through a named pipe connection
using System;
using System.IO;
using System.IO.Pipes;
//
// A sample C# code that demonstrates how to use entropy server to download random bytes from SwiftRNG device.
// Before running this sample, make sure the entropy server is running on local computer.
//
namespace SwiftRNGEntropyClient
{
class Program
{
static void Main(string[] args)
{
NamedPipeClientStream client = new NamedPipeClientStream("SwiftRNG");
client.Connect();
BinaryReader reader = new BinaryReader(client);
BinaryWriter writer = new BinaryWriter(client);
// Prepare storage for 16 random bytes
byte[] rndBytes = new byte[16];
// Send a request to the entropy server to generate 16 bytes
sendRequest(writer, rndBytes.Length);
// Download 16 random bytes from the entropy server
receiveResponse(reader, rndBytes);
// Display downloaded random bytes
foreach (byte b in rndBytes)
{
Console.WriteLine(b);
}
writer.Close();
reader.Close();
client.Close();
}
/// <summary>
/// Read generated random bytes from the entropy server
/// </summary>
/// <param name="reader"></param>
/// <param name="rndBytes"></param>
static void receiveResponse(BinaryReader reader, byte[] rndBytes)
{
// Read random bytes from entropy server.
// Random bytes should be received at once with no delay in between.
int actualBytesReceived = reader.Read(rndBytes, 0, rndBytes.Length);
if (actualBytesReceived != rndBytes.Length)
{
throw new Exception("Error when downloading random bytes");
}
}
/// <summary>
/// Send the request to the entropy server. The request size is always 8 bytes.
/// </summary>
/// <param name="writer"></param>
/// <param name="byteCount"></param>
static void sendRequest(BinaryWriter writer, int byteCount)
{
if (byteCount < 1 || byteCount > 100000)
{
throw new Exception("Invalid request, must be between 1 and 100000 bytes");
}
// Prepare the command header
byte[] requestBytes = new byte[8];
// Set the byte count in the header
byte[] byteCountBytes = BitConverter.GetBytes(byteCount);
for (int i = 4; i < requestBytes.Length; i++)
{
requestBytes[i] = byteCountBytes[i - 4];
}
// Request bytes should be sent at once with no delay in between.
writer.Write(requestBytes);
writer.Flush();
}
}
}