Skip to content

Commit

Permalink
Add checking of gzip type data before decompression
Browse files Browse the repository at this point in the history
  • Loading branch information
rjmangubat23 committed Sep 2, 2022
1 parent 4f7023f commit 6b811c8
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import org.idpass.smartscanner.lib.platform.utils.BitmapUtils
import org.idpass.smartscanner.lib.platform.utils.GzipUtils
import org.idpass.smartscanner.lib.scanner.config.Modes
import org.json.JSONObject
import java.io.ByteArrayInputStream
import java.util.zip.ZipException


Expand Down Expand Up @@ -150,7 +151,8 @@ class QRCodeAnalyzer(
private fun getGzippedData(rawBytes: ByteArray?) : String? {
var data: String? = null
try {
data = if (rawBytes != null) GzipUtils.decompress(rawBytes) else null
val inputStream = ByteArrayInputStream(rawBytes)
data = if (rawBytes != null && GzipUtils.isGZipped(inputStream)) GzipUtils.decompress(rawBytes) else null
} catch (ez : ZipException) {
ez.printStackTrace()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,13 @@
*/
package org.idpass.smartscanner.lib.platform.utils

import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.*
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream

object GzipUtils {
@Throws(IOException::class)
fun compress(jsonString : String) : ByteArray {
fun compress(jsonString: String) : ByteArray {
val os = ByteArrayOutputStream(jsonString.length)
val gos = GZIPOutputStream(os)
gos.write(jsonString.toByteArray())
Expand All @@ -38,16 +36,33 @@ object GzipUtils {
@Throws(IOException::class)
fun decompress(bytes: ByteArray) : String {
val BUFFER_SIZE = 32
val `is` = ByteArrayInputStream(bytes)
val gis = GZIPInputStream(`is`, BUFFER_SIZE)
val string = StringBuilder()
val inputStream = ByteArrayInputStream(bytes)
val gis = GZIPInputStream(inputStream, BUFFER_SIZE)
val sb = StringBuilder()
val data = ByteArray(BUFFER_SIZE)
var bytesRead: Int
while (gis.read(data).also { bytesRead = it } != -1) {
string.append(String(data, 0, bytesRead))
sb.append(String(data, 0, bytesRead))
}
gis.close()
`is`.close()
return string.toString()
inputStream.close()
return sb.toString()
}

fun isGZipped(inputStream: InputStream): Boolean {
var input: InputStream = inputStream
if (!input.markSupported()) {
input = BufferedInputStream(input)
}
input.mark(2)
var magic = 0
try {
magic = input.read() and 0xff or (input.read() shl 8 and 0xff00)
input.reset()
} catch (e: IOException) {
e.printStackTrace(System.err)
return false
}
return magic == GZIPInputStream.GZIP_MAGIC
}
}

0 comments on commit 6b811c8

Please sign in to comment.