본문 바로가기
C#

09# 중복 없는 랜덤키 값 추출

by NaHyungMin 2017. 4. 18.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public static class UniqueKey
{
    private static readonly char[] chars = new char[] { '1''2''3''4''5''6''7''8''9''0' };
 
    public static Int64 GetKey(Int32 keyLength)
    {
        Int64 uniqueKey = 0;
        const Int32 count = 100;
 
        for(Int32 i = 0; i < count; i++)
        {
            RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
            byte[] data = new byte[keyLength];
            crypto.GetNonZeroBytes(data);
 
            StringBuilder result = new StringBuilder(keyLength);
 
            foreach (byte b in data)
            {
                result.Append(chars[b % (chars.Length - 1)]);
            }
 
            if (keyLength > result.Length)
                continue;
 
            uniqueKey = Convert.ToInt64(result);
            break;
        }
 
        return uniqueKey;
    }
}
cs

100번 반복하여, 중복되는 값은 쳐낸다.
키 길이는 변수로 받긴 하는데 길이 10 기준 1천만 반복하면 1만~1만5천 정도 길이가 미만인 키가 나온다.


'C#' 카테고리의 다른 글

11# 열거형 카운트 알아오기  (0) 2017.09.22
10# 데이터 압축  (0) 2017.05.19
08# 키보드 후킹  (0) 2016.05.11
07# C# Entity framework  (0) 2016.05.11
06# 네트워크 활성화/비활성화  (0) 2016.05.11