Microsoft MVP성태의 닷넷 이야기
.NET Framework: 136. 자바와 닷넷의 압축 호환 [링크 복사], [링크+제목 복사],
조회: 32199
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 3개 있습니다.)

자바와 닷넷의 압축 호환


이전에 썼던 글이 바로 이 글을 쓰기 위한 선행 작업이었습니다.

Deflate, GZip, Zip
; https://www.sysnet.pe.kr/2/0/723

며칠 전에, 자바로 구현된 서버 측 서비스와 연동해야 할 일이 있었습니다. 작업 중의 하나는 압축 데이터를 서로 교환하는 것이었는데, .NET에서 압축된 데이터를 Java에서 풀지 못하는 일이 발생했습니다. 문제가 발생한 이후, 우리 쪽은 GZipStream을 사용한다고 했고 약간의 시간이 흐르고 Java 측 개발자는 그에 맞춰서 조정을 해주었습니다. 그래서 연동이 되었지요. ^^

그 상황에서는 다행히 Java 측 개발자가 "맞춰주는" 분위기여서 ^^ 그렇게 했지만, 사실 상황에 따라서는 이것이 반대로 되어야 합니다. 그런 경우에 여러분은 어떻게 조정을 해주시겠습니까?

해답은 간단합니다. 바로 "Deflate, GZip, Zip" 글의 내용을 이해하고 있으면 그 부분은 쉽게 해결이 됩니다. 즉, 자바에서 "DeflaterOutputStream"을 사용해서 압축을 했는데 닷넷 측에서 "GZipStream"을 이용해서 압축을 해제하는 식이면 오류가 발생하게 되는 것입니다. 전형적으로 다음과 같은 오류가 발생합니다.

[그림 1: 압축 해제 오류]
gzipstream_gzipheader_1.png

"
The magic number in GZip header is not correct. Make sure you are passing in a GZip stream.

"



왜인지 아시겠죠? 자바의 Deflate 압축에는 헤더 데이터가 없는데, 닷넷의 GZipStream에서 헤더를 읽어내려고 시도하기 때문에 위와 같은 예외가 발생하는 것입니다. (물론, 그 반대의 경우 - 닷넷에서 DeflateStream으로 압축하고 자바에서 GZIPInputStream으로 압축을 해제할 때도 오류가 발생하겠지요.)




실제로, 연동을 해보는 코딩을 연습삼아 만들어 보기로 했습니다. 우선, 서버 측 압축 소스 코드를 공개한 다음의 글을 참조해서 이클립스로 간단하게 프로젝트를 만들었습니다.

http 압축/해제
; http://yally93.egloos.com/2148475

보시는 것처럼, DeflaterOutputStream / InflaterInputStream을 사용했기 때문에 "raw 압축 데이터"만을 다룰 테고 닷넷 측 역시 DeflateStream으로 받아줘야 합니다.

일단 자바 측 소스 코드는 위의 글에서 조금 변경하여 다음과 같이 작성했습니다.

import java.io.*;
import java.util.zip.*;

public class FileDeflater 
{
	public String zipping(String param) 
	{
		try {
			byte[] unzip = param.getBytes();
			ByteArrayInputStream bif = new ByteArrayInputStream(unzip);

			ByteArrayOutputStream zipbof = new ByteArrayOutputStream();
			DeflaterOutputStream dos = new DeflaterOutputStream(zipbof);
			int position = 0;

			for (int read_byte = 0; (read_byte = bif.read()) != -1; position++) 
			{
				dos.write(read_byte);
			}
			 
			dos.finish();
			zipbof.flush();

			byte[] zipbyteArray = zipbof.toByteArray();

			return new sun.misc.BASE64Encoder().encode(zipbyteArray);
		} 
		catch (Exception ex) 
		{
			return null;
		}
	}
}

public class testApp 
{
	public static void main(String[] args) 
	{
		FileDeflater a = new FileDeflater();
		String text = a.zipping("u cant watch korean 한글");
		System.out.println (text);		
	}

}

순서는 압축한 다음에 base64 인코딩을 했기 때문에 닷넷 측에서는 base64 디코딩을 먼저 하고 압축 해제를 하면 되므로 다음과 같이 작성할 수 있습니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string txt = "eJwrVUhOzCtRKE8sSc5QyM4vSk3MUzh+ceNtAHCQClc="; // 자바의 "u cant watch korean 한글" 압축 결과

            byte[] compressedBytes = Convert.FromBase64String(txt);

            MemoryStream ms = new MemoryStream(compressedBytes);
            byte[] decompressedBuffer;

            using (DeflateStream zipStream = new DeflateStream(ms, CompressionMode.Decompress))
            {
                decompressedBuffer = Program.ReadAllBytesFromStream(zipStream);
            }

            string plainText = Encoding.Default.GetString(decompressedBuffer);
            Console.WriteLine(plainText);
        }

        public static byte[] ReadAllBytesFromStream(Stream stream)
        {
            MemoryStream ret = new MemoryStream();

            Byte[] buffer = new Byte[2048];
            int size;

            while (true)
            {
                size = stream.Read(buffer, 0, buffer.Length);
                if (size > 0)
                {
                    ret.Write(buffer, 0, size);
                }
                else
                {
                    break;
                }
            }

            ret.Flush();
            ret.Close();
            return ret.ToArray();
        }
    }
}

그런데, 실행하고 나면 의외로 다음과 같은 예외가 발생합니다.

Unhandled Exception: System.IO.InvalidDataException: Block length does not match with its complement.
   at System.IO.Compression.Inflater.DecodeUncompressedBlock(Boolean& end_of_block)
   at System.IO.Compression.Inflater.Decode()
   at System.IO.Compression.Inflater.Inflate(Byte[] bytes, Int32 offset, Int32 length)
   at System.IO.Compression.DeflateStream.Read(Byte[] array, Int32 offset, Int32 count)
   at ConsoleApplication1.Program.ReadAllBytesFromStream(Stream stream) in D:\temp\Program.cs:line 40
   at ConsoleApplication1.Program.Main(String[] args) in D:\temp\Program.cs:line 24
Press any key to continue . . .

구글 검색을 해서 찾아낸 결과,

"Block length does not match with its complement." in DeflateStream
; http://www.chiramattel.com/george/blog/2007/09/09/deflatestream-block-length-does-not-match.html

이런 문제가 있었군요. 자바 측의 DeflaterOutputStream은 zlib 스펙을 정의한 RFC 1950을 따르는 반면 닷넷 측의 DeflateStream은 액면 그대로 deflate 스펙을 정의한 RFC 1951을 따르기 때문에 발생하는 것입니다. 다행히 그 차이는 크지 않아서 단순히 처음의 2byte만을 건너뛰면 되어서 닷넷 측 소스 코드를 다음과 같이 변경해 주면 됩니다.

static void Main(string[] args)
{
    string txt = "eJwrVUhOzCtRKE8sSc5QyM4vSk3MUzh+ceNtAHCQClc=";

    byte[] compressedBytes = Convert.FromBase64String(txt);

    MemoryStream ms = new MemoryStream(compressedBytes);
    ms.Position = 2;
    byte[] decompressedBuffer;

    using (DeflateStream zipStream = new DeflateStream(ms, CompressionMode.Decompress))
    {
        decompressedBuffer = Program.ReadAllBytesFromStream(zipStream);
    }

    string plainText = Encoding.Default.GetString(decompressedBuffer);
    Console.WriteLine(plainText);
}




그 외에, 주의해야 할 사항이 하나 있다면 바로 문자열의 인코딩 방식입니다. 만약 자바에서 다음과 같이 문자열에 대한 바이트를 구했다면,

byte[] unzip = param.getBytes();

이때의 인코딩 방식은 기본적으로 시스템에서 설정된 코드 페이지가 됩니다. 처음에 저는 자바의 문자열도 Unicode를 기본으로 채택하고 있기 때문에 위와 같이 기본 getBytes()를 호출하는 경우 Unicode 인코딩을 따른다고 생각했는데 그렇지 않았습니다. 즉, 한글 윈도우즈의 경우에 DBCS로 "ks_c_5601-1987"이 되는 것입니다.

위와 동일한 코드가 닷넷에서는 다음과 같이 적용됩니다.

byte [] encoded = Encoding.Default.GetBytes(txt);

다들 아시겠지만 이것은 전혀 바람직하지 않은 코딩 방법입니다. 서버와 클라이언트가 동일한 코드 페이지로 구성되어 있다는 가정을 해서는 안 됩니다. 대신에, 아래와 같이 문자열 인코딩을 UTF-8이나 Unicode로 명시적으로 지정하는 것이 좋습니다.

=== 자바: UTF-8 인코딩 바이트 배열 구하기 ===
byte[] unzip = param.getBytes("UTF-8");

=== 닷넷: UTF-8 인코딩된 바이트로부터 문자열 구하기 ===
string plainText = Encoding.UTF8.GetString(decompressedBuffer);

이를 테스트한 소스 코드를 첨부해 두었습니다. (자바 프로젝트는 Eclipse로 만들었고, 닷넷 프로젝트는 Visual Studio 2008입니다.)



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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/3/2023]

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)
13414정성태9/16/20233585디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233794닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20237099닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/20233579Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보
13410정성태9/11/20235117닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성) [1]
13409정성태9/8/20233945닷넷: 2140. C# - Win32 API를 이용한 모니터 전원 끄기
13408정성태9/5/20233919Windows: 251. 임의로 만든 EXE 파일을 포함한 ZIP 파일의 압축을 해제할 때 Windows Defender에 의해 삭제되는 경우
13407정성태9/4/20233633닷넷: 2139. C# - ParallelEnumerable을 이용한 IEnumerable에 대한 병렬 처리
13406정성태9/4/20233623VS.NET IDE: 186. Visual Studio Community 버전의 라이선스
13405정성태9/3/20234027닷넷: 2138. C# - async 메서드 호출 원칙
13404정성태8/29/20233600오류 유형: 876. Windows - 키보드의 등호(=, Equals sign) 키가 눌리지 않는 경우
13403정성태8/21/20233405오류 유형: 875. The following signatures couldn't be verified because the public key is not available: NO_PUBKEY EB3E94ADBE1229CF
13402정성태8/20/20233504닷넷: 2137. ILSpy의 nuget 라이브러리 버전 - ICSharpCode.Decompiler
13401정성태8/19/20233762닷넷: 2136. .NET 5+ 환경에서 P/Invoke의 성능을 높이기 위한 SuppressGCTransition 특성 [1]
13400정성태8/10/20233601오류 유형: 874. 파이썬 - pymssql을 윈도우 환경에서 설치 불가
13399정성태8/9/20233519닷넷: 2135. C# - 지역 변수로 이해하는 메서드 매개변수의 값/참조 전달
13398정성태8/3/20234380스크립트: 55. 파이썬 - pyodbc를 이용한 SQL Server 연결 사용법
13397정성태7/23/20233863닷넷: 2134. C# - 문자열 연결 시 string.Create를 이용한 GC 할당 최소화
13396정성태7/22/20233641스크립트: 54. 파이썬 pystack 소개 - 메모리 덤프로부터 콜 스택 열거
13395정성태7/20/20233510개발 환경 구성: 685. 로컬에서 개발 중인 ASP.NET Core/5+ 웹 사이트에 대해 localhost 이외의 호스트 이름으로 접근하는 방법
13394정성태7/16/20233475오류 유형: 873. Oracle.ManagedDataAccess.Client - 쿼리 수행 시 System.InvalidOperationException
13393정성태7/16/20233655닷넷: 2133. C# - Oracle 데이터베이스의 Sleep 쿼리 실행하는 방법
13392정성태7/16/20233552오류 유형: 872. Oracle - ORA-01031: insufficient privileges
13391정성태7/14/20233566닷넷: 2132. C# - sealed 클래스의 메서드를 callback 호출했을 때 인라인 처리가 될까요?
13390정성태7/12/20233507스크립트: 53. 파이썬 - localhost 호출 시의 hang 현상
13389정성태7/5/20233553개발 환경 구성: 684. IIS Express로 호스팅하는 웹을 WSL 환경에서 접근하는 방법
1  2  3  4  5  6  7  8  [9]  10  11  12  13  14  15  ...