Microsoft MVP성태의 닷넷 이야기
.NET Framework: 136. 자바와 닷넷의 압축 호환 [링크 복사], [링크+제목 복사],
조회: 32192
글쓴 사람
정성태 (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)
13491정성태12/19/20232276Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232403개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232178개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232116오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232417개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232234개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232125오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232219개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232364닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20233046닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232349개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232747개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232405개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232641닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232329닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232421닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232238개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232530닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232254C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232366Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232696닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232476닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232354닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232470오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232631닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232374개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...