Microsoft MVP성태의 닷넷 이야기
.NET Framework: 376. .NET 2.0의 유니코드 관련 문자열 비교 오류 [링크 복사], [링크+제목 복사],
조회: 19057
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13361정성태5/31/20233815오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/20233200오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/20233507오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/20233849.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233643.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20233968DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233899.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20234144.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233763.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234273VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233541오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233844.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233765.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20234187.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/20234027오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/20235419.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/20236565.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/20234457디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/20234359.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/20234046닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/20234147오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/20234942닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/20234342닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/20234849Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/20234674.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/20234714.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...