Microsoft MVP성태의 닷넷 이야기
.NET Framework: 136. 자바와 닷넷의 압축 호환 [링크 복사], [링크+제목 복사],
조회: 32203
글쓴 사람
정성태 (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)
13465정성태11/28/20232381개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232508닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/20232412오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/20232417오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/20232474닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/20232394닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/20232456닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/20232461닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
13457정성태11/25/20232343VS.NET IDE: 187. Visual Studio - 16.9 버전부터 추가된 "Display inline type hints" 옵션
13456정성태11/25/20232698닷넷: 2169. C# - OpenAI를 사용해 PDF 데이터를 대상으로 OpenAI 챗봇 작성 [1]파일 다운로드1
13455정성태11/25/20232595닷넷: 2168. C# - Azure.AI.OpenAI 패키지로 OpenAI 사용파일 다운로드1
13454정성태11/23/20232894닷넷: 2167. C# - Qdrant Vector DB를 이용한 Embedding 벡터 값 보관/조회 (Azure OpenAI) [1]파일 다운로드1
13453정성태11/23/20232355오류 유형: 879. docker desktop 설치 시 "Invalid JSON string. (Exception from HRESULT: 0x83750007)"
13452정성태11/22/20232461닷넷: 2166. C# - Azure OpenAI API를 이용해 사용자가 제공하는 정보를 대상으로 검색하는 방법파일 다운로드1
13451정성태11/21/20232600닷넷: 2165. C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작파일 다운로드1
13450정성태11/21/20232394닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
13449정성태11/21/20232512개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
13448정성태11/20/20232832닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
13447정성태11/16/20232700닷넷: 2162. ASP.NET Core 웹 사이트의 SSL 설정을 코드로 하는 방법
13446정성태11/16/20232664닷넷: 2161. .NET Conf 2023 - Day 1 Blazor 개요 정리
13445정성태11/15/20232994Linux: 62. 리눅스/WSL에서 CA 인증서를 저장하는 방법
13444정성태11/15/20232715닷넷: 2160. C# 12 - Experimental 특성 지원
13443정성태11/14/20232778개발 환경 구성: 687. OpenSSL로 생성한 사용자 인증서를 ASP.NET Core 웹 사이트에 적용하는 방법
13442정성태11/13/20232550개발 환경 구성: 686. 비주얼 스튜디오로 실행한 ASP.NET Core 사이트를 WSL 2 인스턴스에서 https로 접속하는 방법
13441정성태11/12/20232922닷넷: 2159. C# - ASP.NET Core 프로젝트에서 서버 Socket을 직접 생성하는 방법파일 다운로드1
13440정성태11/11/20232520Windows: 253. 소켓 Listen 시 방화벽의 Public/Private 제어 기능이 비활성화된 경우
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...