using System;
using System.Runtime.InteropServices;
class Program
{
static void Main()
{
uint randomNumber = GetHardwareRandom();
Console.WriteLine($"하드웨어 난수: {randomNumber}");
}
static uint GetHardwareRandom()
{
uint value;
while (!RdRand(out value)) { } // RDRAND 성공할 때까지 반복
return value;
}
[DllImport("kernel32.dll")]
static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32.dll")]
static extern IntPtr LoadLibrary(string name);
static bool RdRand(out uint value)
{
if (IsRdRandAvailable())
{
return RdRandInstruction(out value);
}
value = 0;
return false;
}
static bool IsRdRandAvailable()
{
// CPUID 명령어로 RDRAND 지원 여부 확인
int cpuInfo = 0x1;
int ecx = CpuId(cpuInfo, out _, out _, out _);
return (ecx & 0x40000000) != 0;
}
[DllImport("kernel32.dll")]
static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect);
[StructLayout(LayoutKind.Sequential)]
struct HardwareRandom
{
public uint Value;
}
[return: MarshalAs(UnmanagedType.U1)]
static bool RdRandInstruction(out uint value)
{
HardwareRandom random = new HardwareRandom();
IntPtr ptr = Marshal.AllocHGlobal(sizeof(uint));
Marshal.StructureToPtr(random, ptr, false);
bool result = RdRandNative(ptr);
random = (HardwareRandom)Marshal.PtrToStructure(ptr, typeof(HardwareRandom));
Marshal.FreeHGlobal(ptr);
value = random.Value;
return result;
}
[DllImport("kernel32.dll")]
static extern bool RdRandNative(IntPtr value);
static int CpuId(int function, out int eax, out int ebx, out int ecx)
{
int edx;
CpuIdNative(function, out eax, out ebx, out ecx, out edx);
return ecx;
}
[DllImport("kernel32.dll")]
static extern void CpuIdNative(int function, out int eax, out int ebx, out int ecx, out int edx);
}