brendan-duncan / archive

Dart library to encode and decode various archive and compression formats, such as Zip, Tar, GZip, ZLib, and BZip2.
MIT License
399 stars 139 forks source link

Compatibility with Java Deflater #271

Closed Gieted closed 1 year ago

Gieted commented 1 year ago

It looks like data compressed using Java's built-in Deflater cannot be uncompressed using archive's Inflate.

In JVM/Kotlin:

fun deflate(input: ByteArray): ByteArray {
    val outputStream = ByteArrayOutputStream()
    DeflaterOutputStream(outputStream, Deflater(Deflater.BEST_COMPRESSION)).use {
        it.write(input)
        it.finish()
    }

    return outputStream.toByteArray()
}

fun main() {
    val compressed = deflate("test".toByteArray())
    val base64 = Base64.getUrlEncoder().encodeToString(compressed)
    println(base64)
}

Then in Dart:

void main() {
  const compressed = "eNorSS0uAQAEXQHB";
  final decoded = base64Url.decode(compressed);
  final decompressed = Inflate(decoded).getBytes(); // returns and empty list
  final decompressedString = utf8.decode(decompressed);
  print(decompressedString);
}

This seems weird as both are supposed to use the same "deflate" algorithm.

Gieted commented 1 year ago

Never mind, you just need to set nowrap parameter to true, and then it works:

fun deflate(input: ByteArray): ByteArray {
    val outputStream = ByteArrayOutputStream()
    DeflaterOutputStream(outputStream, Deflater(Deflater.BEST_COMPRESSION, true)).use {
        it.write(input)
        it.finish()
    }

    return outputStream.toByteArray()
}