암호학적으로 안전한 난수가 필요하다면 RNGCryptoServiceProvider 클래스를 사용하는 것이 좋습니다. 이 클래스는 암호화 서비스 공급자(CSP) 기반의 암호학적 난수 생성기를 구현하며, 일반적인 Random 클래스보다 예측 가능성이 훨씬 낮아 보안이 중요한 작업에 적합합니다.
RNGCryptoServiceProvider로 난수 값 얻기
동일한 클래스를 활용하면 다음과 같은 방식으로 안전한 무작위 값을 손쉽게 얻을 수 있습니다.
using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider()) {
byte[] val = new byte[6];
crypto.GetBytes(val);
randomvalue = BitConverter.ToInt32(val, 1);
}GetBytes() 메서드는 바이트 배열에 암호학적으로 강력한 임의 값을 채워 넣으며, BitConverter.ToInt32()를 통해 이를 정수 형태로 변환할 수 있습니다.
예제 코드
안전한 난수를 직접 생성해 보고 싶다면 아래 전체 코드를 실행해 보세요. 이 예제에서는 생성된 값을 활용해 0과 1 사이의 난수를 만들어 출력합니다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
public class Demo {
public static void Main(string[] args) {
for (int i = 0; i <= 5; i++) {
Console.WriteLine(randomFunc());
}
}
private static double randomFunc() {
string n = "";
int randomvalue;
double n2;
using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider()) {
byte[] val = new byte[6];
crypto.GetBytes(val);
randomvalue = BitConverter.ToInt32(val, 1);
}
n += randomvalue.ToString().Substring(1, 1)[0];
n += randomvalue.ToString().Substring(2, 1)[0];
n += randomvalue.ToString().Substring(3, 1)[0];
n += randomvalue.ToString().Substring(4, 1)[0];
n += randomvalue.ToString().Substring(5, 1)[0];
double.TryParse(n, out n2);
n2 = n2 / 100000;
return n2;
}
}출력 결과
0.13559 0.0465 0.18058 0.26494 0.52231 0.78927
참고 사항
.NET 6 이상 버전에서는 RNGCryptoServiceProvider가 더 이상 사용되지 않는(deprecated) API로 분류되었습니다. 최신 프로젝트에서는 RandomNumberGenerator.GetBytes() 또는 RandomNumberGenerator.Fill() 메서드를 사용하는 것이 권장되며, 동일하게 암호학적으로 안전한 난수를 제공합니다.