The following demonstrates how to use Python language to download random data from a SwiftRNG device when used with SwiftRNG Entropy Server for Windows. The following code will only work when running SwiftRNG Entropy Server. Before using the following examples, make sure your Python project is targeted for Windows 64 bit platform and a SwiftRNG device is plugged into one of USB ports available. The SwiftRNG-64.dll is included in the software kit.
A sample source code for retrieving a random byte value from a SwiftRNG device when using Entropy Server for Windows and provided SwiftRNG-64.dll
import os
import sys
import ctypes
dll = ctypes.WinDLL("C:\\tools\\windows-binaries\\windows-x64-vs-2019\\SwiftRNG-64.dll")
func = dll.getEntropyAsByte
func.restype = ctypes.c_int
random = func()
if random > 255:
raise Exception("Could not retreieve entropy byte. Is entropy server running?")
else:
print ("Random byte: ", random)
A sample source code for retrieving an array of random bytes from a SwiftRNG device when using Entropy Server for Windows and provided SwiftRNG-64.dll
import os
import sys
import ctypes
byte_count = 10
byte_arr = ctypes.c_byte * byte_count
byte_arr_p = ctypes.POINTER(ctypes.c_byte)
dll = ctypes.WinDLL("C:\\tools\\windows-binaries\\windows-x64-vs-2019\\SwiftRNG-64.dll")
func = dll.getEntropy
func.restype = ctypes.c_int
func.argtypes = [byte_arr_p, ctypes.c_long]
entropy_bytes = byte_arr()
status = func(entropy_bytes, byte_count)
if status != 0:
raise Exception("Could not retreieve entropy bytes. Is entropy server running?")
print("Retrieved random bytes:")
for x in entropy_bytes:
print(x)
A sample source code for retrieving random numbers within a range from a SwiftRNG device when using Entropy Server for Windows and provided SwiftRNG-64.dll
import os
import sys
import ctypes
# How many random bytes needed to generate numbers within [-9999,9999] range.
byte_count = 2
# Absoulte maximum value needed.
max_abs_value = 9999
byte_arr = ctypes.c_byte * byte_count
byte_arr_p = ctypes.POINTER(ctypes.c_byte)
dll = ctypes.WinDLL("C:\\tools\\windows-binaries\\windows-x64-vs-2019\\SwiftRNG-64.dll")
func = dll.getEntropy
func.restype = ctypes.c_int
func.argtypes = [byte_arr_p, ctypes.c_long]
entropy_bytes = byte_arr()
count = 0
# Generate 10 random numbers within [-9999,9999] range.
while (count < 10):
count = count + 1
status = func(entropy_bytes, byte_count) # Retrieve two random bytes
if status != 0:
raise Exception("Could not retreieve entropy bytes. Is entropy server running?")
# Convert random bytes to an integer.
# Use signed=False to generate numbers within [0,9999] range (positive values).
integer = int.from_bytes(entropy_bytes, signed=True)
if integer < 0:
sign = -1
else:
sign = 1
# Reduce the interger value to the specific range.
reduced_integer = abs(integer) % (max_abs_value + 1) * sign
print("Random number:", reduced_integer)