The following demonstrates how to use C# language to download random data from an AlphaRNG device when used with Entropy Server for Windows through a named pipe connection. The following code will only work when running AlphaRNG Entropy Server. More information about Entropy Server API can be hound at this address.
A sample source code for retrieving random values from AlphaRNG 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 AlphaRNG device.
// Before running this sample, make sure the entropy server is running on local computer.
//
namespace AlphaRNGEntropyClient
{
class Program
{
static void Main(string[] args)
{
NamedPipeClientStream client = new NamedPipeClientStream("AlphaRNG");
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 retrieve 16 random bytes
sendRequest(writer, rndBytes.Length);
// There should not be any delay between sending the request and receiving response
// 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();
}
}
}