Microsoft MVP성태의 닷넷 이야기
.NET Framework: 376. .NET 2.0의 유니코드 관련 문자열 비교 오류 [링크 복사], [링크+제목 복사],
조회: 26237
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

.NET 2.0의 유니코드 관련 문자열 비교 오류

오호~~~ 재미있는 문제가 하나 올라왔습니다. ^^

C#에서 유니코드 정규화 또는 .StartsWith()에 문제가 있는 것 같습니다
; https://social.msdn.microsoft.com/Forums/ko-KR/8ff66698-793f-4953-8c16-0cb61477b1a6/c5064049436-50976457685307646300-512214450854868-4660845716?forum=visualcsharpko

위의 글에 나온 소스 코드는 매우 간단한데요.

string test1 = "끅";
test1 = test1.Normalize(NormalizationForm.FormD);
string test2 = "끊";
test2 = test2.Normalize(NormalizationForm.FormD);

bool result1 = test1.StartsWith(test2);
bool result2 = test2.StartsWith(test1);

string t = (result1 ? "true" : "false") + "    " + (result2 ? "true" : "false");

Console.WriteLine(t);

실제로 이를 실행해 보면, .NET 2.0에서 "ㄲㅡㄱ", "ㄲㅡㄶ"으로 분리된 문자열이 동일하다고 true 값을 반환합니다.

.NET Reflector로 확인해 보면, string.StartsWith 메서드는 결국 내부적으로 CultureInfo.CurrentCulture.CompareInfo.IsPrefix 메서드를 호출하기 때문에 소스 코드를 다음과 같이 바꿔도 됩니다.

string test1 = "끅";
test1 = test1.Normalize(NormalizationForm.FormD);
string test2 = "끊";
test2 = test2.Normalize(NormalizationForm.FormD);

bool result1 = CultureInfo.CurrentCulture.CompareInfo.IsPrefix(test1, test2);
bool result2 = CultureInfo.CurrentCulture.CompareInfo.IsPrefix(test2, test1);

string t = (result1 ? "true" : "false") + "    " + (result2 ? "true" : "false");

Console.WriteLine(t);

역시 .NET Reflector로 디버깅해서 들어가 보면 IsPrefix 메서드 중에서도 nativeIsPrefix를 호출하는 것을 알 수 있습니다.

public virtual unsafe bool IsPrefix(string source, string prefix, CompareOptions options)
{
    if ((source == null) || (prefix == null))
    {
        throw new ArgumentNullException((source == null) ? "source" : "prefix", Environment.GetResourceString("ArgumentNull_String"));
    }
    if (prefix.Length == 0)
    {
        return true;
    }
    if (options == CompareOptions.OrdinalIgnoreCase)
    {
        return source.StartsWith(prefix, StringComparison.OrdinalIgnoreCase);
    }
    if (((options & ~(CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase)) != CompareOptions.None) && (options != CompareOptions.Ordinal))
    {
        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options");
    }
    if (!this.IsSynthetic)
    {
        return nativeIsPrefix(this.m_pSortingTable, this.m_sortingLCID, source, prefix, options);
    }
    if (options == CompareOptions.Ordinal)
    {
        return nativeIsPrefix(CultureInfo.InvariantCulture.CompareInfo.m_pSortingTable, this.m_sortingLCID, source, prefix, options);
    }
    return this.SyntheticIsPrefix(source, 0, source.Length, prefix, GetNativeCompareFlags(options));
}

이 때, m_pSortingTable은 포인터 변수이고, m_sortingLCID 변수는 언어 코드가 들어가는 데 한글 윈도우의 경우 1042 값이 대입됩니다. 아쉽지만, 여기까지가 분석의 끝입니다. nativeIsPrefix는 InternalCall로써 .NET Framework 내부에서 C/C++ 코드로 구현되어 있으므로 디버깅이 안됩니다. (혹시나 싶어 웹에 검색해 보니 소스 코드가 역시 없군요. ^^)

[MethodImpl(MethodImplOptions.InternalCall)]
private static extern unsafe bool nativeIsPrefix(void* pSortingTable, int sortingLCID, string source, string prefix, CompareOptions options);




그런데, 왜 .NET 4.0에서는 잘 동작하는 걸까요? .NET 4.0 역시 StartsWith가 IsPrefix 메서드를 호출하는 것까지는 거의 비슷합니다. 그런데, 결정적으로 nativeIsPrefix가 아닌, 함수 이름조차도 변경된 InternalFindNLSStringEx 메서드를 부르는 차이가 있습니다.

[SecuritySafeCritical, __DynamicallyInvokable]
public virtual bool IsPrefix(string source, string prefix, CompareOptions options)
{
    if ((source == null) || (prefix == null))
    {
        throw new ArgumentNullException((source == null) ? "source" : "prefix", Environment.GetResourceString("ArgumentNull_String"));
    }
    if (prefix.Length == 0)
    {
        return true;
    }
    if (options == CompareOptions.OrdinalIgnoreCase)
    {
        return source.StartsWith(prefix, StringComparison.OrdinalIgnoreCase);
    }
    if (options == CompareOptions.Ordinal)
    {
        return source.StartsWith(prefix, StringComparison.Ordinal);
    }
    if ((options & ~(CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase)) != CompareOptions.None)
    {
        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options");
    }
    return (InternalFindNLSStringEx(this.m_dataHandle, this.m_handleOrigin, this.m_sortName, (GetNativeCompareFlags(options) | 0x100000) | ((source.IsAscii() && prefix.IsAscii()) ? 0x20000000 : 0), source, source.Length, 0, prefix, prefix.Length) > -1);
}

물론, 이 메서드 역시 P/Invoke 호출이기 때문에 더 이상 볼 것이 없습니다. ^^

[SuppressUnmanagedCodeSecurity, SecurityCritical, DllImport("QCall", CharSet=CharSet.Unicode)]
private static extern int InternalFindNLSStringEx(IntPtr handle, IntPtr handleOrigin, string localeName, int flags, string source, int sourceCount, int startIndex, string target, int targetCount);




그나저나, 문제 자체를 좀 더 들여다 볼까요?

ㄱ: 4353
ㅡ: 4467
(받침) ㄱ: 4520

ㄲ: 4353
ㅡ: 4467
(받침) ㄶ: 4525

"극"의 받침을 바꿔서 테스트 해보면 다음과 같은 결과가 나옵니다.

ㄲ: 4521 - false
ㄳ: 4522 - false
ㄴ: 4523 - false
ㄵ: 4534 - false
ㄷ: 4526 - false
ㄹ: 4527 - false
...[생략: 모두 false]...

'ㄻㅅ': 4562 - true # 이런 받침은 거의(?) 없으므로 무시해도 좋고.


재미있군요. ^^ 2가지 종성(ㄶ, ㄻㅅ)에 대해서 true 판단을 해버리는 것입니다. 반면 초성/중성의 경우에는 어떤 것으로 바꿔도 결과는 같습니다. 딱히 규칙을 찾을만한 것이 없어서 더 이상의 탐구는 할 수 없을 것 같습니다.

단지, .NET 2.0의 경우 한글이라면 '문화권'에 대한 영향이 없으므로 비교 옵션을 다음과 같이 Ordinal로 명시해 주는 임시 조치를 할 수는 있겠습니다.

bool result1 = CultureInfo.CurrentCulture.CompareInfo.IsPrefix(test1, test2, CompareOptions.Ordinal);
bool result2 = CultureInfo.CurrentCulture.CompareInfo.IsPrefix(test2, test1, CompareOptions.Ordinal);

// .NET 2.0 에서도 result1 == result2 == false

그런데, Ordinal 옵션을 함부로 주어도 되는 걸까요? ^^ 이를 위해 MSDN 문서를 들여다 봐야 합니다.

CompareOptions Enumeration
; https://learn.microsoft.com/en-us/dotnet/api/system.globalization.compareoptions

When possible, the application should use string comparison methods that accept a CompareOptions value to specify the kind of comparison expected. As a general rule, user-facing comparisons are best served by the use of linguistic options (using the current culture), while security comparisons should specify Ordinal or OrdinalIgnoreCase.

가능한 경우 응용 프로그램이 예상되는 비교 종류를 지정하려면 CompareOptions 값을 받는 문자열 비교 메서드를 사용해야 합니다. 일반적으로 사용자 쪽 비교는 언어적 옵션(현재 문화권 사용)을 사용하는 것이 가장 좋지만 보안 비교는 Ordinal 또는 OrdinalIgnoreCase를 지정해야 합니다.


"보안 비교(security comparison)"라는 것은 웹 브라우저의 피싱 사이트 문제를 아시는 분들에게는 익숙한 이야기일 것입니다. 예를 들어, "www.sos.com"의 도메인 명을 가진 웹 사이트가 있는데, 사용자들로 하여금 헷갈릴 수 있도록 "www.søs.com"이라는 유사한 도메인으로 피싱 사이트를 운영할 수 있다는 것입니다. 숫자 0과 영문자 O에 대한 차이를 노리는 것도 마찬가지고. 자세한 것은 다음의 문서를 참조하세요. ^^

Unicode Security Mechanisms
; http://www.unicode.org/reports/tr39/

MSDN 예제에도 "AE", "Æ" 비교가 나옵니다. 문화권으로 봤을 때는 이 2개의 글자를 동일하게 보지만, (웹 브라우저의 주소창처럼) 보안 문제를 고려했을 때 이것을 다르게 인식하는 것이 좋기 때문에 같다고 보면 안됩니다. 실제로 다음의 코드는 true를 반환하지만,

string t1 = "AE";
string t2 = "Æ";

Console.WriteLine(t1.StartsWith(t2)); // true
Console.WriteLine(t2.StartsWith(t1)); // true

Ordinal 옵션을 주면 false를 반환합니다.

string t1 = "AE";
string t2 = "Æ";

Console.WriteLine(t1.StartsWith(t2, StringComparison.Ordinal)); // false
Console.WriteLine(t2.StartsWith(t1, StringComparison.Ordinal)); // false




정리해 보면, 분명히 "ㄲㅡㄱ", "ㄲㅡㄶ" 을 동일하다고 반환하는 것은 버그가 맞고 이를 해결하려면 .NET 4.0 응용 프로그램으로 마이그레이션하는 것이 가장 적절한 선택입니다. 그게 불가능하다면 그나마 차선책으로 Ordinal 옵션을 주면 된다는!

참고로, 기왕에 이글을 읽어 보셨다면 아래의 글도 한번 읽어보세요. ^^

유니코드와 한글 - 유니코드와 닷넷을 이용한 한글 처리
; https://www.sysnet.pe.kr/2/0/1294

개발자 PC 환경 - 유니코드(Unicode)를 위한 설정
; https://www.sysnet.pe.kr/2/0/762




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 12/27/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 106  107  108  109  [110]  111  112  113  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11174정성태4/3/201719411VC++: 116. Visual Studio 단위 테스트 - Failed to set up the execution context to run the test
11173정성태4/3/201722975VC++: 115. Visual Studio에서 C++ DLL을 대상으로 단위 테스트할 때 비정상 종료한다면?파일 다운로드1
11172정성태4/3/201722108.NET Framework: 651. C# - 특정 EXE 프로세스를 종료시킨 EXE를 찾아내는 방법파일 다운로드1
11171정성태3/31/201718818VS.NET IDE: 114. Visual Studio 디버깅 경고 창 - You are debugging a Release build of ...
11170정성태3/31/201720720.NET Framework: 650. C# - CachedAnonymousMethodDelegate 유형의 코드 생성
11169정성태3/30/201720556VC++: 114. C++ vtable의 가상 함수 호출 가로채기파일 다운로드1
11168정성태3/29/201723889VC++: 113. C++ 클래스 상속 관계의 vtable 생성 과정
11167정성태3/28/201724198VC++: 112. C++의 가상 함수 테이블 (vtable)은 언제 생성될까요? [2]
11166정성태3/28/201718439오류 유형: 382. System.Data.SqlClient.SqlException - Arithmetic overflow error converting IDENTITY to data type int.
11165정성태3/27/201721714오류 유형: 381. Visual C++에서 min, max 함수를 사용한 경우 C2589, C2059 컴파일 오류 발생
11164정성태3/27/201730045VC++: 111. C++ 클래스의 상속에 따른 메모리 구조 [2]파일 다운로드1
11163정성태3/25/201719820VC++: 110. CreateThread Win32 API에 C++ 클래스의 멤버 함수를 전달하는 방법파일 다운로드1
11162정성태3/24/201724063오류 유형: 380. Visual Studio 빌드 실패 - The OutputPath property is not set for project
11161정성태3/24/201716771오류 유형: 379. ICOMAdminCatalog.GetCollection 호출 시 0x80070422 예외 발생
11160정성태3/23/201721690.NET Framework: 649. ASP.NET - Server cannot append header after HTTP headers have been sent. (HTTP 헤더를 보낸 후에는 서버에서 헤더를 추가할 수 없습니다.)파일 다운로드1
11159정성태3/23/201718982Windows: 136. Memory-mapped File은 Private Bytes 크기에 포함될까요?파일 다운로드1
11158정성태3/22/201718625디버깅 기술: 85. Windbg - SOS 디버깅 사례 System.NullReferenceException 예외 추적
11157정성태3/22/201721867.NET Framework: 648. Dictionary<TKey, TValue>를 deep copy하는 방법파일 다운로드1
11156정성태3/21/201722493.NET Framework: 647. 닷넷(C#) 코드로 인증서 요청 코드 만드는 방법파일 다운로드1
11155정성태3/21/201722706.NET Framework: 646. SslStream의 CipherAlgorithm 선택이 가능할까요?파일 다운로드1
11154정성태3/5/201729712VC++: 109. DLL에서 STL 객체를 인자/반환값으로 갖는 함수를 제공할 때, 그 함수를 외부에서 사용하는 경우 비정상 종료한다면? [2]파일 다운로드1
11153정성태3/5/201729094VC++: 108. DLL에 정의된 C++ template 클래스의 복사 생성자 문제파일 다운로드1
11152정성태3/4/201722769VC++: 107. VirtualAlloc, HeapAlloc, GlobalAlloc, LocalAlloc, malloc, new의 차이점파일 다운로드1
11151정성태3/3/201723371VC++: 106. DLL 개발자가 주의해야 할 Secure CRT 함수 사용 [1]파일 다운로드1
11150정성태2/21/201719312.NET Framework: 645. Visual Studio Fakes 기능에서 Shim... 클래스가 생성되지 않는 경우 [5]
11149정성태2/21/201722984오류 유형: 378. A 64-bit test cannot run in a 32-bit process. Specify platform as X64 to force test run in X64 mode on X64 machine.
... 106  107  108  109  [110]  111  112  113  114  115  116  117  118  119  120  ...